Efficiency: step count, redundant calls, loops

Study time
≈ 2 h (estimate)
Needs
L3-M04-L03
Updated
2026-11-04

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M04 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L03 (step-level judges and their calibration) · Next: L05

1. Introduction

Two agents lend the right book and both match the reference path in mode in_order. One does it in three calls; the other asks the same question three times, asks for the notice three times although it was blocked, and takes twice the time. The end state (L3-M03) and the matcher (L02) cannot tell these two runs apart. Efficiency is the third view: how long the path is, where it repeats, how many times it retries after an error, how much it spends on things that are not on the path.

This lesson builds five efficiency measures on the L01 record, each with a flag for a reader and a blind spot pinned by a test. It also stresses the most important point: efficiency is not quality. An agent that does nothing has the best step ratio of all. Every agent is simulated, costs are made-up units (cu) and times are made-up ticks; no model, network or API is called.

2. Learning objectives

  1. Compute the step ratio against the reference path and explain why a low ratio is not flagged. Read: §4.1, §4.2.
  2. Detect redundant calls and loops, and explain the role of the idempotency key. Practice: §8.2 (parts A, B), §8.3 (lines 1, 2, 5).
  3. Detect retries after an error and state when a retry is right. Practice: §8.2 (part A), §8.3 (lines 3, 4).
  4. Compute the wasted cost in cu and in ticks, and state why a blocked call costs ticks but no cu. Practice: §8.2 (part A).
  5. Read efficiency next to the outcome, never alone. Practice: §8.2 (part C). Read: §6.1.
  6. Find the waste in a ten-call run. Practice: §9.

3. Required knowledge and tools

  • L01 (the record, ticks, cu), L02 (counted calls, maximum matching), L3-M01-L02 (the loop guard, stop reasons), L3-M02-L04 (idempotency keys, blocked, duplicate). Code lab code-labs/l3-m04.
  • Separating the meanings. Efficiency in this lesson measures the path of one run against the reference path; it differs from the real cost and latency of the system that L3-M06 will measure (the lab uses made-up units). A loop here is a block of calls repeated back to back at least three times, measured after the run; it differs from the loop guard (loop_detected) of L3-M01-L02, which blocks a repeated call during the run. Redundant means asking again what was already asked; it differs from the tool layer's duplicate (L3-M02-L04), the status when the same idempotency key is sent again with the same arguments.
  • The old policy still stands: no model call. The measures only flag; a person decides whether a repeat is waste or necessary, and which limits are acceptable.

4. Concept explanations

4.1 Five measures and their flags

  • Step ratio = tool calls made (every status) / calls of the reference path. 1 is the reference length, 0 is no call at all. Flag OVER_STEPS when the ratio is above 3/2.
  • Redundant call: a call whose call key (call_key: the tool name plus the canonical JSON of the arguments, idempotency_key dropped) equals that of an earlier call, whatever either status. Flag REDUNDANT. The idempotency key is dropped because a new key does not make a new request.
  • Loop: a block of calls repeated back to back at least three times ([{start, length, repeats}]); one call repeated three times in a row is a loop of length 1. Twice is redundant, three times in a row is a loop. Flag LOOP.
  • Retry after an error: a call of the same tool right after a call of that tool that ended in failed, blocked, rejected or denied; the earlier error code is recorded. Flag RETRY_AFTER_ERROR.
  • Wasted cost: the cu (and ticks) of every call that is not matched with the reference path, rejected calls included. The useful part comes from the maximum matching of L02; a failed call that is on the path (such as LIMIT in t04) is useful. Flag WASTED_COST; a separate flag UNCOUNTED_CALLS when some calls did not count.
Diagram of the efficiency measures: the trajectory record gives the step ratio, redundant calls, loops and retries after an error; the record and the reference path together give the wasted cost in cu and ticks, and the reference path is also used for the step ratio; all five measures give flags for a reader, and the flags are read next to the outcome and the process.
Diagram: Five measures and their flags

Anthropic's article lists "transcript analysis (turns taken, token usage)" among code-based graders, gives an example configuration that tracks the number of turns, tool calls, total tokens and latency, and says that once evals exist, latency, token usage, cost per task and error rates can be tracked on a static bank of tasks [R1]. The Google Cloud page defines trajectory precision as the share of predicted calls that are also in the reference [R2]; low precision (L02) and wasted cost are two views of the same thing, one counting calls, one counting money.

4.2 Efficiency is not quality

claim_only calls no tool: step ratio 0, no waste, no flag. no_verify skips the check: ratio 2/3, shorter than the reference, and the end result is still right. Rewarding "shorter" alone rewards exactly two defective agents. That is why report does not flag a low ratio: catching an agent that skipped work is the job of the oracle (wrong end state) and the matcher (missing calls). The reverse holds too: a repeat can be necessary (asking again after the state really changed), a retry after a transient error can be right. An efficiency flag is a question for a reader, not a verdict.

The lab's limits (a ratio of 3/2, three repeats, the idempotency key dropped) are choices of this lab, not standards of any source. Changing a limit changes what is flagged; the owner writes down the reason.

5. Technical deep dive

5.1 lab/efficiency.py

  • call_key(step, ignore=("idempotency_key",)): a string that is equal for two calls that ask the same thing. Arguments that are not a JSON object are keyed on a digest of the raw text (two identical junk calls are still equal). It never raises and always returns a string (usable as a set key).
  • step_counts(tr): {steps, calls, counted, uncounted}. step_ratio(tr, path): a fraction, None for an empty path.
  • redundant(tr, ignore): the index values of the redundant calls. With ignore=() (keys compared too), a retry under a new key is not redundant: the blind spot of exact keys.
  • loops(tr, ignore, min_repeats=3): scans left to right; at each position takes the shortest block repeated back to back at least min_repeats times, reports it and jumps past it. A cycle with another call in between (A B A C A B) is not seen.
  • retries_after_error(tr): [{index, tool, after}].
  • wasted_cost(tr, path): {total, useful, wasted, rate, ticks_total, ticks_wasted}; rate is None when nothing was spent. Ticks are counted on tool-call steps, not on the final answer. A blocked or denied call costs 0 cu in this tool layer, so retrying a blocked call costs steps and ticks but no cu.
  • report(tr, path, max_ratio=3/2): every measure and the list of flags. No flag means no check fired, not "efficient enough".

6. QA perspective

6.1 What the efficiency measures do not say

  • A low ratio is not flagged: an agent that does nothing has clean efficiency flags. Always read next to the oracle and the matcher.
  • A cycle with another call in between is not a loop under this definition; a loop whose arguments change each time is seen only when the changing keys are in ignore.
  • A necessary repeat is flagged as redundant too; a retry after a transient error is flagged too. Flags need a reader.
  • cu and ticks are the lab's made-up units. Real cost (tokens, money, latency) has another structure and belongs to L3-M06.
  • The "useful" part is chosen by the matching: when a call on the path is repeated, the earliest one is matched and the later ones count as waste, even when the successful one is a later one.
  • Efficiency is measured against one reference path. An agent that takes another valid path (cautious) is charged waste for its extra step.

7. Real-world scenarios

Scenario 1 (fictional): "New key, old request". On t04 the student already has a book; borrow_book returns LIMIT. Agent retry_limit retries twice, each time with a new idempotency key, so the tool layer does not see a duplicate. With exact keys, redundant sees nothing; with the key dropped it sees two redundant calls and a loop (§8.2, part B). QA keeps the default of dropping the key and writes the reason in the report.

Scenario 2 (fictional): "Shortest wins". An internal leaderboard uses the step ratio alone. claim_only is first with ratio 0, no_verify second with 2/3. QA puts the outcome column next to the ratio column (§8.2, part C) and proposes dropping the one-dimensional leaderboard.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l3-m04
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 125 passed

8.2 Run the demo

python -m lab.demo l04

Output (copied from a real run on Python 3.14.6 and 3.12.3 (Linux), 2026-11-04; both versions give identical output). Every agent is simulated:

A. efficiency per run (ratio = calls / reference calls; cost in cu and made-up ticks)
   t01/diligent: ratio=1 redundant=[] loops=[] retries=[] wasted=0/5 cu (rate 0), 0/4 ticks; flags=[]
   t01/cautious: ratio=4/3 redundant=[] loops=[] retries=[] wasted=1/6 cu (rate 1/6), 1/5 ticks; flags=['WASTED_COST']
   t01/redundant: ratio=4/3 redundant=[2] loops=[] retries=[] wasted=1/6 cu (rate 1/6), 1/5 ticks; flags=['REDUNDANT', 'WASTED_COST']
   t02/no_verify: ratio=3/4 redundant=[] loops=[] retries=[(2, 'NOT_AVAILABLE')] wasted=2/6 cu (rate 1/3), 2/5 ticks; flags=['RETRY_AFTER_ERROR', 'WASTED_COST']
   t01/junk_calls: ratio=1 redundant=[] loops=[] retries=[] wasted=3/3 cu (rate 1), 3/3 ticks; flags=['WASTED_COST', 'UNCOUNTED_CALLS']
   t01/claim_only: ratio=0 redundant=[] loops=[] retries=[] wasted=0/0 cu (rate None), 0/0 ticks; flags=[]
   t06/retry_blocked: ratio=3/2 redundant=[5, 6] loops=[(4, 1, 3)] retries=[(5, 'APPROVAL_REQUIRED'), (6, 'APPROVAL_REQUIRED')] wasted=0/5 cu (rate 0), 2/7 ticks; flags=['REDUNDANT', 'LOOP', 'RETRY_AFTER_ERROR', 'WASTED_COST']
   t04/retry_limit: ratio=2 redundant=[3, 4] loops=[(2, 1, 3)] retries=[(3, 'LIMIT'), (4, 'LIMIT')] wasted=4/7 cu (rate 4/7), 4/7 ticks; flags=['OVER_STEPS', 'REDUNDANT', 'LOOP', 'RETRY_AFTER_ERROR', 'WASTED_COST']
   t01/looper: ratio=4 redundant=[3, 4, 5, 6, 7, 8, 9, 10, 11, 12] loops=[(1, 2, 6)] retries=[] wasted=11/12 cu (rate 11/12), 11/12 ticks; flags=['OVER_STEPS', 'REDUNDANT', 'LOOP', 'WASTED_COST']
B. retry_limit on t04 changes the idempotency key each time: redundant ignoring the key=[3, 4], with exact keys=[]; loops ignoring the key=1, with exact keys=0
C. the shortest path is not the best one: step ratio per agent on t01 next to the outcome
   0    claim_only     outcome_pass=False
   2/3  no_verify      outcome_pass=True
   2/3  self_praise    outcome_pass=True
   1    diligent       outcome_pass=True
   1    junk_calls     outcome_pass=False
   1    retry_blocked  outcome_pass=True
   1    retry_limit    outcome_pass=True
   1    wrong_book     outcome_pass=False
   1    wrong_student  outcome_pass=False
   4/3  cautious       outcome_pass=True
   4/3  redundant      outcome_pass=True
   4    looper         outcome_pass=False

Reading the output: part A: diligent has no flag. cautious has ratio 4/3 (below 3/2, so no OVER_STEPS) and wastes 1 cu on asking about B002: a second valid path is still charged waste. redundant adds the flag REDUNDANT for step 2. no_verify on t02 borrows B004 (NOT_AVAILABLE) and then B001: the second borrow is flagged as a retry after an error although it is a reasonable fallback. junk_calls has ratio 1 but wastes everything, flag UNCOUNTED_CALLS. claim_only has no flag. retry_blocked on t06 has a ratio of exactly 3/2 (not above), sends the notice three times in a row (a loop of length 1 from step 4), 0 cu wasted but 2 ticks: a blocked call costs no cu. retry_limit has ratio 2. looper makes 12 calls, a loop of length 2 repeated 6 times, waste 11/12. Part B: changing the idempotency key hides the repeat only when keys are compared. Part C: sorted by increasing ratio, the shortest agent (claim_only) fails the outcome, the next two skip the check, and the longest, looper, fails too.

8.3 Try it yourself

Save as try_l04.py in the lab's root folder (next to lab/, not inside lab/), run python try_l04.py, then delete the file. The runs are built by hand with build_record; no agent is run:

from lab import efficiency as E, trace as T

g1 = {"tool": "get_book", "args": {"book_id": "B001"}}
g2 = {"tool": "get_book", "args": {"book_id": "B002"}}
s1 = {"tool": "search_books", "args": {"query": "atlas"}}


def borrow(key, status="applied", code=None):
    return {"tool": "borrow_book", "args": {"book_id": "B001", "student_id": "S0042", "idempotency_key": key}, "status": status, "code": code, "cost": 2}


path = [g1, {"tool": "borrow_book", "args": {"book_id": "B001", "student_id": "S0042"}}]
runs = {"abab": [g1, g2, g1, g2, g1, g2, borrow("k1")],
        "abac": [g1, g2, g1, s1, g1, g2, borrow("k1")],
        "retry": [g1, borrow("k1", "failed", "LIMIT"), borrow("k2", "failed", "LIMIT"), borrow("k3")],
        "junk": [g1, {"tool": "borrow_book", "args": "{book_id: B001}", "status": "rejected", "code": "BAD_JSON"}, borrow("k1")]}
for name, calls in runs.items():
    tr = T.build_record(name, "t01", "hand", calls, "Done.")
    r = E.report(tr, path)
    print(name, r["ratio"], r["redundant"], [(x["start"], x["length"], x["repeats"]) for x in r["loops"]],
          [(x["index"], x["after"]) for x in r["retries"]], f'{r["cost"]["wasted"]}/{r["cost"]["total"]}', r["flags"])
tr = T.build_record("retry", "t01", "hand", runs["retry"], "Done.")
print(E.redundant(tr, ignore=()), E.call_key(tr["steps"][1]) == E.call_key(tr["steps"][2]))

Output (Python 3.14.6 and 3.12.3, Linux, identical):

abab 7/2 [3, 4, 5, 6] [(1, 2, 3)] [] 5/8 ['OVER_STEPS', 'REDUNDANT', 'LOOP', 'WASTED_COST']
abac 7/2 [3, 5, 6] [] [] 5/8 ['OVER_STEPS', 'REDUNDANT', 'WASTED_COST']
retry 2 [3, 4] [(2, 1, 3)] [(3, 'LIMIT'), (4, 'LIMIT')] 4/7 ['OVER_STEPS', 'REDUNDANT', 'LOOP', 'RETRY_AFTER_ERROR', 'WASTED_COST']
junk 3/2 [] [] [(3, 'BAD_JSON')] 1/4 ['RETRY_AFTER_ERROR', 'WASTED_COST', 'UNCOUNTED_CALLS']
[] True

Reading: line 1: B001, B002 repeated three times in a row is a loop of length 2 from step 1; four redundant calls; ratio 7/2. Line 2: a search_books inserted in the middle: the same redundant calls (except step 4) but no loop any more, the blind spot of the "back to back" definition. Line 3: three borrows with three different keys, the first two LIMIT: redundant, a loop of length 1, two retries after an error; 4 of 7 cu wasted; the useful part is get_book and the first (failed) borrow, because the matching picks the earliest call. Line 4: one broken-JSON call (rejected, 1 cu) then the right call: ratio 3/2 is not above the limit, with a retry after an error and an uncounted call. Line 5: with keys compared there is no redundant call, although the default call keys of steps 2 and 3 are equal.

8.4 Run the lesson tests

python -m pytest tests/test_l04_efficiency.py -v

Result: 12 passed. Read test_a_new_idempotency_key_hides_a_repeat_unless_the_key_is_ignored, test_loop_blind_spot_an_interleaved_cycle_is_not_seen and test_blind_spot_the_shortest_path_is_not_the_best.

8.5 Troubleshooting

Symptom Cause Fix
step_ratio returns None The reference path is empty Fix the path (L02, EMPTY_PATH); a ratio means nothing without a reference
A loop you can see is not reported Another call sits in between, or the arguments change each time That blind spot is pinned; tell the reader, or add the changing key to ignore if the owner agrees
wasted_cost reports 0 cu for a clearly wasteful run Blocked calls cost 0 cu Read ticks_wasted and the flags REDUNDANT, LOOP

9. Independent exercise

Problem: A hand-written run of ten calls for the fictional student S0077, with a two-call reference path. Find the waste.

Requirements: complete exercises/test_l04_efficiency.py:

  1. TODO 1: REDUNDANT, LOOPS (a list of (start, length, repeats)), RETRIES (a list of (index, after)). Write your prediction before running.
  2. TODO 2: RATIO (the step ratio) and WASTED (the wasted share of the cu), as strings such as "3/4".

Test data: exercises/ex_efficiency.json.

Deliverable: the five variables above, in the file exercises/test_l04_efficiency.py itself.

Acceptance criteria: python -m pytest exercises/test_l04_efficiency.py passes (2 tests), recomputed with lab.efficiency; the record must have no lint error.

Hints: TODO 1: write the call key of each step (idempotency key dropped) as a string of letters, then look for repeats in that string; remember the rule "shortest block, then jump past it". TODO 2: a rejected call still costs cu; the useful part holds only the calls matched with the path.

10. Knowledge check

0/8 done · Results are kept in this browser only.

P02 · True or false

In the lab, an agent that sends again a send_notice call that was blocked (blocked, APPROVAL_REQUIRED) increases the wasted cu.

P04 · Select all that apply

A hand-built run: get_book B003, then borrow_book B003 for S0123 returning failed with code LIMIT, then borrow_book again with a new idempotency key, LIMIT again. Costs: get_book 1 cu, each borrow_book 2 cu. Reference path: get_book B003, then borrow_book B003 for S0123. Select every flag report returns.

P05 · Spot the bug

A colleague writes a redundant-call finder. For retry_limit on t04 (two more borrow attempts with new idempotency keys), the function returns [], while the lab's redundant returns [3, 4]. Find the defect.

def my_redundant(tr):
    seen, out = set(), []
    for s in tr["steps"]:
        a = s["action"]
        if a and a.get("kind") == "tool_call":
            k = (a["tool"], a["arguments"])
            if k in seen:
                out.append(s["index"])
            seen.add(k)
    return out

P06 · Match

Match each behaviour with the flag report raises for it.

P08 · Recall

Lesson: L3-M01-L02

According to L3-M01-L02, what does the stop reason loop_detected mean?

11. Summary

  • Concepts: five measures (step ratio, redundant, loop, retry after an error, wasted cost); efficiency is not quality; the limits are the lab's choices [R1].
  • Skills: run report, read the flags, change ignore to see the role of the idempotency key, put the ratio next to the outcome.
  • Pitfalls: rewarding the shortest path; taking no flag as efficient; forgetting that blocked calls cost 0 cu; believing every repeat is wrong; measuring against one path and punishing another valid path [R2].
  • You can now: take a run and ask: how much longer than the reference it is, what it asked again, where it looped, which error it retried after, how much it spent off the path, and whether the result is right.

12. References

ID Title Publisher URL Accessed Relevance
R1 Demystifying evals for AI agents Anthropic https://www.anthropic.com/research/demystifying-evals-for-ai-agents 2026-11-04 Read the page text: transcript analysis (turns taken, token usage) in the table of code-based graders; the example configuration n_turns, n_toolcalls, n_total_tokens, latency; tracking latency, tokens, cost per task
R2 Evaluate Gen AI agents Google Cloud Documentation https://cloud.google.com/vertex-ai/generative-ai/docs/models/evaluation-agents 2026-11-04 Read the definition of trajectory_precision (the share of predicted calls found in the reference); the page is marked Preview

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
Step ratio Tỷ lệ bước: số lời gọi tool / số lời gọi của đường tham chiếu
Redundant call Lời gọi thừa: hỏi lại điều đã hỏi (khóa idempotency bỏ qua); khác trạng thái duplicate của lớp tool
Loop (efficiency) Vòng lặp: khối lời gọi lặp liền ít nhất ba lần, đo sau lần chạy; khác chốt kiểm loop_detected của L3-M01-L02
Retry after error Thử lại sau lỗi: gọi lại cùng tool ngay sau một lời gọi lỗi của tool đó
Wasted cost Chi phí lãng phí: cu và tick của lời gọi không ghép được với đường tham chiếu