The agent loop and stop conditions

Study time
≈ 2 h (estimate)
Needs
L3-M01-L01
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-M01 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L01 · Next: L03

1. Introduction

An agent can fail in a way a single model call cannot: it does not stop. A loop that repeats the same call, or uses up the budget before recording a result, is a bug in the loop code, not in the model, and because that code lives in the application, a tester can check it with ordinary tests. This lesson teaches how to read one run of the loop step by step, list every stop reason, compute by hand the stopping point at the edge cases (exactly at the maximum number of steps, exactly out of budget), and understand what a loop guard does and what it misses.

Sources for this lesson: the "Building effective agents" article says a task usually ends when it is complete, but it is also common to add stopping conditions such as a maximum number of iterations to keep control [R1]; the Claude documentation describes the standard loop as a while loop on stop_reason [R2]; the ReAct paper reports one kind of failure that repeats a previous action [R3]. The lab uses a simulated policy and a fake cost unit (cu).

2. Learning objectives

  1. Read the history of one run and point out what each step does. Read: §8.2 part A.
  2. List the lab's six stop reasons and the order of checks. Practice: §4.2, §8.3 (lines 1 to 7).
  3. Compute by hand the stopping point at the edge cases for step count and budget. Practice: §8.2 part B, §8.3 (lines 1 to 5), §9 (TODO 2).
  4. Explain how a loop guard recognizes a repeated call (the canonical call key, the sandbox state) and its blind spots. Practice: §8.3 (lines 8, 10 and 11), §9 (TODO 1).
  5. Lint the loop's limits. Practice: §8.2 part D, §8.3 (line 9).
  6. Write your own guard and budget rule, and check them against the lab. Practice: §9.

3. Prerequisites and tools

  • L01 (the four parts of an agent, the tool layer, simulated policies), L1-M07 (pytest). The lab code is code-labs/l3-m01.
  • Separating the senses. A step in this lesson is one turn of the agent: one model call plus at most one tool call; it differs from a "step" in a tutorial and from a "step" of a plan in L03. The loop is the agent loop, not the bootstrap loop of Level 2. The stop reason says why the loop ended, which differs from the "gate verdict" (PASS/FAIL) of L2-M07-L04: a run that stops with final can still be wrong. State here is the contents of the notebooks in the sandbox; the guard compares it through a fingerprint (a hash), which differs from the conversation state of L1-M05-L05. The loop guard blocks a repeated tool call at run time; it differs from the guard of L2-M03-L02, a deterministic check placed next to a similar point. The budget is counted in the lab's fake cu; there are no real prices.

4. Concept explanation

4.1 The standard loop and why stop conditions are needed

The Claude tool use documentation describes the standard shape when the application runs the tools itself: send a request with a list of tools; if the model returns stop_reason: "tool_use", run each tool, send back a tool_result, and repeat; the loop exits on any other stop_reason (end_turn, max_tokens, stop_sequence, refusal), meaning the model has given its final answer or stopped for another reason the application must handle [R2]. Note that this standard loop exits on a signal from the model. A limit set by code, such as a maximum number of iterations, is something you add yourself; [R1] calls it "stopping conditions (such as a maximum number of iterations) to maintain control".

The ReAct paper set a step limit for its own experiments: 7 steps for HotpotQA and 5 for FEVER, because the authors saw that more steps did not improve results (a note in the paper: among the trajectories with a correct answer, only 0.84% on HotpotQA had exactly 7 steps and 1.33% on FEVER had exactly 5 steps); when ReAct could not return an answer within that number of steps, they fell back to the CoT-SC method [R3]. That is a choice for their task; the lab's 8 steps and 40 cu are the lab's choice, not the standard of any source.

4.2 The lab's six stop reasons

lab/loop.py stops for exactly one of six reasons:

  • final: the policy returns a final answer. (A plan action that uses no tool still costs one step and one model call, and then moves to the next step.)
  • max_steps: max_steps steps have run and nothing else has stopped the loop.
  • budget: the next step (a model call or a tool call) no longer fits in the budget.
  • error_limit: the number of consecutive failed tool calls reaches the limit.
  • loop_detected: the guard refuses a repeated call.
  • policy_error: the policy raises an error or returns an action of the wrong shape.
Decision diagram of one loop step: is there budget for one model call? No: stop with budget. Yes: call the model; an invalid action stops with policy_error. A valid action is one of three kinds: a final answer stops with final; a plan (no tool) goes straight to the check of step n; for a tool call: if the guard sees a repeated call, stop with loop_detected; if the budget does not cover the tool, stop with budget; otherwise run the tool and update the consecutive-error count. Reaching the error limit stops with error_limit; step n equal to max_steps stops with max_steps; otherwise the next step starts.
Diagram: The lab's six stop reasons

The order in the diagram is a convention of the lab and decides the outcome at the edge cases. For example, a final on exactly the last step is still final, because the final answer is checked before max_steps is considered.

4.3 A loop that repeats

The ReAct paper names a failure pattern specific to the method: the model repeats its earlier thoughts and actions, that is, it does not know what to do next to get out of the loop; the authors file it under "reasoning error" and suspect greedy decoding as the cause, noting that this is only their guess [R3]. For a tester, the practical conclusion does not depend on the cause: you need a guard outside the model. In the lab, ReAct(stuck_after=k) is a switch that makes the simulated policy repeat its last call after k successful calls; it is a way to build the failure in order to try the guard, not a model of how often real failures occur.

5. Technical deep dive

5.1 One step and the edge cases

Each step: check the budget for one model call (2 cu); call the policy; if it is final, stop; if it is a tool call, ask the guard, check the budget for the tool (1 or 2 cu), run the tool, and update the error counter. An unknown tool costs 1 cu so that guessing names is not free. used never exceeds budget; a test runs budgets from 2 to 30 on three tasks to assert it.

The table below (from the demo, simulated; a step that calls calc costs 2 + 1 = 3 cu):

Situation Stop reason Steps Cost
final at step 3, max_steps = 3 final 3 8
final at step 4, max_steps = 3 max_steps 3 9
budget 6, 3 cu per step budget 2 6
budget 5, 3 cu per step budget 2 5

Row 3: spending exactly the whole budget of 6 is valid; the third step does not start because 6 + 2 exceeds 6. Row 4: the second step starts (3 + 2 = 5 fits), but the calc call would push the total to 6, so it does not run; used stops at 5.

5.2 The loop guard

LoopGuard(threshold) refuses the threshold-th call with the same key while the state has not changed. The key is the tool name plus the canonical JSON of the arguments (sorted keys, no whitespace, NFC strings, invisible characters removed); broken JSON arguments are keyed by the cleaned text. The state is the fingerprint of the notebooks in the sandbox. Two consequences to remember:

  • It counts over the whole run, not only consecutively: with four writes to the same notebook a with content 1, 2, 1, 2 (each write changes the state), a guard with threshold 2 blocks only at the second visit to the same (call, state) pair; the test test_a_state_change_makes_a_repeat_legitimate pins the blocking point at step 4.
  • Identical retries of a broken-JSON call also share a key. When the policy is made to "slip" with probability 1, react is blocked with loop_detected after two errors, before reaching error_limit at three errors (the test pins the stop reason and an error count of 2). The threshold is also a trade-off: with threshold 3 task t05 (a tool that fails transiently once) finishes after one retry, while with threshold 2 the retry is treated as a repeat (§8.3).

Blind spots: 7*9 and then 7 * 9 are two different keys, so are 1 and 1.0, and two calls with different arguments that are equally useless (1+1 then 1+2 forever) are not blocked; the test test_guard_blind_spots_are_real pins that.

5.3 The limits lint

lint_limits accepts only real integers: True, 3.0, NaN, inf, strings, None and non-positive numbers are all rejected; a budget smaller than the price of one model call is BUDGET_BELOW_ONE_MODEL_CALL; a guard threshold below 2 is BAD_LOOP_THRESHOLD because threshold 1 would block every first call. run_agent calls this lint and raises ValueError before running anything (fail closed). The lint does not know which values are reasonable for a product.

6. The QA perspective

6.1 The stop-condition test suite

A policy with a script for each stop reason, plus the edge cases: final on the last step, max_steps right after it, a budget exactly spent and one cu short, consecutive errors with one success in between (the counter must go back to 0), repeated calls in different key orders, and a policy that fails or returns the wrong shape. The lab builds them with Scripted (replaying a list of actions), with no model needed.

6.2 What this check does not say

  • final does not mean the answer is right; you need the end-state oracle (L01) and L3-M03.
  • Stopping on budget or max_steps can leave a half-finished state: a notebook written before the stop is still there. The trace (L04) records the stop reason; the sandbox state is not in the lab's trace and must be taken from elsewhere (the list of notebooks, the sandbox fingerprint) so the report is accurate.
  • The guard catches exact repeats by key, not semantic repeats.

7. Real-world scenarios

Scenario 1 (fictional): "The assistant asks the same question again". HocVui Assistant calls lookup with the same key several times because the policy is stuck. Without the guard, the run ends at max_steps (the demo sets 6) after six identical calls; with a guard of threshold 3, it stops at loop_detected after two calls that did run (§8.2 part C). QA adds this scenario to the test suite.

Scenario 2 (fictional): "The budget runs out before the notebook is written". The task that writes the perimeter into a notebook (t04) needs 12 cu. With a budget of 9, the run stops on budget just before the notes_add call: no notebook, no answer. With a budget of 10, the notebook has been written but there is still no final answer (§8.3, the last three lines). The report records the stop reason and the half-finished state, not "random failure".

8. Hands-on tutorial

8.1 Setup

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

8.2 Run the demo

python -m lab.demo l02

Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-04; the two versions are identical). Every policy, tool and cost is simulated:

A. react on t04: stop=final steps=4 used=12 model_calls=4 tool_calls=3
   step 1: tool_call lookup -> Tổng chiều dài và chiều rộng, nhân 2.
   step 2: tool_call calc -> 44
   step 3: tool_call notes_add -> saved
   step 4: final
B. boundaries (model call 2 cu, calc 1 cu)
   final on step 3, max_steps 3: stop=final steps=3 used=8
   final on step 4, max_steps 3: stop=max_steps steps=3 used=9
   budget 6: stop=budget steps=2 used=6
   budget 5: stop=budget steps=2 used=5
C. a policy that repeats its last call (react, t03, stuck_after=1)
   guard threshold 3: stop=loop_detected steps=3 tool_calls=2
   guard off (threshold 50): stop=max_steps steps=6 tool_calls=6
D. limit lint
   (8, 40) -> []
   (0, 40) -> ['BAD_MAX_STEPS']
   (True, 40) -> ['BAD_MAX_STEPS']
   (8, 1) -> ['BUDGET_BELOW_ONE_MODEL_CALL']
   (8, 40, 3, 1) -> ['BAD_LOOP_THRESHOLD']

Reading the output: part A is one complete run of task t04 (look up the formula, compute, write the notebook, answer): four steps, 12 cu. Part B is the four edge cases of §5.1. Part C runs the same stuck policy with and without the guard: at threshold 3 the third call is refused, so only two tool calls run; with the guard off the loop runs all six steps (the demo sets max_steps to 6). Part D is the limits lint (the parameters are max_steps, budget, then error_limit and the guard threshold).

8.3 Try it yourself

Save it as try_l02.py in the lab's root directory (next to lab/, not inside lab/), run python try_l02.py, then delete the file:

import json

from lab import policies as P, tasks as T
from lab.loop import LoopGuard, lint_limits, run_agent
from lab.tools import Sandbox
import tempfile

calc = lambda e: {"kind": "tool_call", "tool": "calc", "arguments": json.dumps({"expression": e})}
final = {"kind": "final", "text": "Đáp án: 2"}
bad = lambda i: {"kind": "tool_call", "tool": f"nope{i}", "arguments": "{}"}
with tempfile.TemporaryDirectory() as root:
    n = [0]

    def run(actions, **kw):
        n[0] += 1
        r = run_agent(P.Scripted(actions), Sandbox(f"{root}/s{n[0]}"), **kw)
        return r["stop_reason"], r["steps"], r["used"]
    four_calcs = [calc("1+1"), calc("2+2"), calc("3+3"), calc("4+4")]
    for budget in (12, 9, 8, 7):
        print("budget", budget, run(four_calcs, max_steps=9, budget=budget))
    print("final on step 2, max_steps 2:", run([calc("1+1"), final], max_steps=2))
    print("errors 3 in a row:", run([bad(1), bad(2), bad(3), final], max_steps=9))
    print("errors with a success between:", run([bad(1), bad(2), calc("1+1"), bad(3), bad(4), final], max_steps=9))

g = LoopGuard(3)
a, b = '{"expression": "1+1"}', '{"expression":"1+1"}'
print([g.allow("calc", x, "f") for x in (a, b, a)])
print(lint_limits(8, float("nan")), lint_limits(3, 40, 3, 2), lint_limits(-1, 0))

t5 = next(t for t in T.load_tasks() if t["id"] == "t05")
with tempfile.TemporaryDirectory() as root:
    for threshold in (3, 2):
        r = run_agent(P.ReAct(t5), T.make_sandbox(f"{root}/t{threshold}", t5), loop_threshold=threshold)
        print("t05 react, loop_threshold", threshold, "->", r["stop_reason"], r["steps"], r["errors"])

t4 = next(t for t in T.load_tasks() if t["id"] == "t04")
with tempfile.TemporaryDirectory() as root:
    for budget in (12, 10, 9):
        sb = T.make_sandbox(f"{root}/b{budget}", t4)
        r = run_agent(P.ReAct(t4), sb, budget=budget)
        print("t04 react, budget", budget, "->", r["stop_reason"], r["steps"], r["used"], sb.note_names())

Output (Python 3.14.6 and 3.12.14 identical):

budget 12 ('budget', 4, 12)
budget 9 ('budget', 3, 9)
budget 8 ('budget', 3, 8)
budget 7 ('budget', 2, 6)
final on step 2, max_steps 2: ('final', 2, 5)
errors 3 in a row: ('error_limit', 3, 9)
errors with a success between: ('final', 6, 17)
[True, True, False]
['BAD_BUDGET'] [] ['BAD_MAX_STEPS', 'BAD_BUDGET']
t05 react, loop_threshold 3 -> final 3 1
t05 react, loop_threshold 2 -> loop_detected 2 1
t04 react, budget 12 -> final 4 12 ['chu_vi']
t04 react, budget 10 -> budget 3 10 ['chu_vi']
t04 react, budget 9 -> budget 3 8 []

Reading it: each triple is (stop reason, steps, cost). Lines 1 to 4: four calc steps (3 cu each) fit a budget of 12 exactly; budgets 9 and 8 both stop at step 3 but differ in used (9 and 8), because at 8 the step 3 model call fits but the calc call does not; budget 7 does not let step 3 start. Line 5: final at step 2 with max_steps 2 is still final. Lines 6 and 7: three unknown tools in a row (3 cu per step) hit error_limit, while one successful call in between resets the counter to 0, so the run reaches final after six steps, 17 cu. Line 8: two JSON strings that differ in spaces share a key, so the third call is refused. Line 9: the lint of NaN, of a valid limits set with threshold 2, and of two wrong values. Lines 10 and 11: task t05 with guard thresholds 3 and 2; at threshold 2 a valid retry after a transient error is treated as a repeat and the run stops at loop_detected. The last three lines: task t04 with budgets 12, 10 and 9; at 10 the notebook chu_vi has been written but the run stops at step 3 without a final answer, and at 9 the run stops before the write call (cost 8, no notebook).

8.4 Run the lesson's tests

python -m pytest tests/test_l02_loop.py -v

Result: 14 passed. Read test_max_steps_exactly_at_the_limit, test_budget_exactly_exhausted, test_budget_is_never_exceeded, test_a_repeating_policy_is_stopped_by_the_guard and test_guard_blind_spots_are_real. The tests run on in-memory values and files in pytest's temporary directory.

8.5 Troubleshooting

Symptom Cause Fix
ValueError: invalid limits A limit is not a real integer, or the threshold is below 2 Call lint_limits to see the error code

9. Independent exercise

Problem: Write your own loop guard and budget rule, then let the tests compare them with the lab.

Requirements: complete exercises/test_l02_loop.py:

  1. TODO 1: my_loop_guard(calls, threshold): the index (from 0) of the first refused call, or None. Think about what "same arguments" means for JSON text.
  2. TODO 2: my_budget_stop(steps, budget, max_steps, model_cost=2): return (reason, number of steps started, cost) for a scenario with a cost per step.

Test data: exercises/ex_loop_cases.json (eight cases for TODO 1); TODO 2 is tried on combinations of budget and step count generated by the test.

Deliverable: the two functions above, in the file exercises/test_l02_loop.py itself.

Acceptance criteria: python -m pytest exercises/test_l02_loop.py passes (2 tests), compared with the lab's LoopGuard and run_agent. The tests do not check performance, do not check how you treat 1 versus 1.0, and do not check whether the limits are reasonable for a product.

Hints: TODO 1: build the key from the tool name and the parsed arguments and compare keys, not raw strings; remember the state. TODO 2: simulate each step following the diagram in §4.2 and check the budget before spending, not after.

10. Knowledge check

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

P02 · True or false

Same script (three calc steps, then the final answer at step 4) but budget 40 cu and max_steps 4. Because the loop has run all 4 steps, the stop reason is max_steps.

P04 · Select all that apply

The default loop guard (threshold 3, counted over the whole run, comparing the call's canonical key under the same state fingerprint). Each scenario is a Scripted policy on a clean sandbox, ending with a final answer. Select every scenario whose stop reason is loop_detected.

P05 · Put in order

Put the things the loop does within one step in the order the lab checks them, from the first to the last (when no stop condition has fired, the step ends at the last item).

  1. Check the budget for the tool; if it is not enough, stop with budget
  2. If it is a tool call, ask the loop guard; if it refuses, stop with loop_detected
  3. If it is the final answer, stop with final
  4. Run the tool and update the consecutive error count; if it reaches the limit, stop with error_limit
  5. If max_steps steps have been run, stop with max_steps
  6. Call the policy; if the action has the wrong shape, stop with policy_error
  7. Check the budget for one model call; if it is not enough, stop with budget

P06 · Match

Match each scenario (Scripted policy, clean sandbox) with the stop reason.

P07 · Spot the bug

A colleague wrote their own function that computes the stopping point from each step's cost (each step: one model call, then the tool cost). The function has one bug that makes used exceed the budget. Find it.

def run_costs(step_costs, budget, max_steps, model_cost=2):
    used, steps = 0, 0
    for tool_cost in step_costs[:max_steps]:
        used += model_cost
        steps += 1
        if used > budget:
            return "budget", steps, used
        used += tool_cost
        if used > budget:
            return "budget", steps, used
    return "max_steps", steps, used

P08 · Short answer

A Scripted policy has three actions: lookup with {"key": "diện tích hình vuông"} ("area of a square"), notes_add writing the notebook hv, then the final answer; default max_steps. With a budget of 7 and with a budget of 6, how does the run stop, which notebooks does the sandbox have, and what should the report say? How many cu are needed at least to run the whole script?

P09 · Essay

Write 5-8 sentences reviewing the following configuration of an agent (simulated): max_steps 5, budget 21 cu, prices as in the lab (each model call 2 cu, the most expensive tool 2 cu). The team believes that "the two limits protect two different things". A trial with a Scripted policy calling notes_add with five different notebook names gives the result (max_steps, 5 steps, 20 cu). State the phenomenon, how to check it with tests, and what to do.

P11 · Recall

Lesson: L2-M03-L02

According to L2-M03-L02, the guard numbers_preserved catches 7 of 8 wrong-number sentences. Why does the eighth sentence slip through?

P12 · Recall

Lesson: L1-M05-L05

According to L1-M05-L05, with fake replies (a fixed trajectory), asserting the exact trajectory is reasonable; with a real model, assert properties instead (for example "no side effect without approval").

P13 · Recall

Lesson: L3-M01-L01

According to L3-M01-L01, why does call_tool treat Calc and calc (with a trailing space) as UNKNOWN_TOOL?

P14 · Multiple choice

What does lint_limits(0, 1) return (with error_limit 3, guard threshold 3 and one model call at the default 2 cu)?

P15 · Select all that apply

Select every pair of calls that the loop guard treats as the same key.

P16 · True or false

A policy that returns {"kind": "tool_call", "tool": "calc"} (missing arguments) makes run_agent throw an exception, and the run has no result to report.

11. Summary

  • Concepts: six stop reasons and the order of checks; edge cases for step count and budget; the canonical call key and the sandbox state; the limits lint.
  • Skills: computing the stopping point by hand, building a stop-condition test suite with a replay policy, reading the stop reason in a report.
  • Traps: treating final as correct; assuming the guard catches every repeat; setting a threshold without considering valid retries; forgetting that stopping midway leaves a half-finished state.
  • You can now: look at a run that stopped unusually and say which reason it stopped for, at which step, how much it cost, and what is left half-done.

12. References

ID Title Publisher URL Accessed Relevance
R1 Building effective agents Anthropic https://www.anthropic.com/engineering/building-effective-agents (redirects to /research/building-effective-agents) 2026-11-04 Read the page text (the passage on the loop, stopping conditions, human checkpoints); the two appendices were not read in full
R2 How tool use works (Claude Platform Docs) Anthropic https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works 2026-11-04 Read the page text (the passage on the agentic loop and the stop reasons)
R3 ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al., arXiv:2210.03629 v3, 10/03/2023, day/month/year) arXiv https://arxiv.org/abs/2210.03629 (read the HTML version https://arxiv.org/html/2210.03629) 2026-11-04 Read the full text of the HTML version in the passages on step limits, combination with CoT-SC and error analysis; the appendix was not read in full. The paper's results belong to its own settings

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Agent loop Vòng lặp agent: hỏi model, chạy tool, đưa kết quả lại, lặp
Step Bước: một lần gọi model cộng nhiều nhất một lần gọi tool
Stop condition / stop reason Điều kiện dừng / lý do dừng của vòng lặp
Budget (cu) Ngân sách tính bằng đơn vị chi phí giả
Loop guard Chốt kiểm vòng lặp: từ chối lời gọi lặp cùng khóa khi trạng thái không đổi
State fingerprint Dấu vân tay trạng thái: mã băm nội dung sandbox
Scripted policy Chính sách phát lại một danh sách hành động cố định, dùng để test
Fail closed Đóng khi lỗi: giới hạn sai thì không chạy