CONCEPT The natural stop vs. the safety net
An agent loop ends naturally when stop_reason == "end_turn" — the model
decided it's finished and stopped requesting tools. That's the happy path. But an agent driven by a model
can also fail to stop: it loops on a broken tool, thrashes between two actions, or keeps "just
checking one more thing." A responsible harness never relies on end_turn alone. It wraps the
loop in independent kill-switches so a stuck agent can't burn unbounded tokens and money.
| Termination condition | Fires when | Why you need it |
|---|---|---|
end_turn | Model stops asking for tools | The natural, desired completion |
| Max-iterations cap | Loop count hits a hard limit | Stops runaway / thrashing loops cold |
| Token / cost budget | Cumulative usage exceeds a ceiling | Caps spend even if steps stay "valid" |
| Time budget | Wall-clock deadline passes | Bounds latency for the caller |
| Explicit done-signal | Model calls a finish tool / emits a sentinel | Clear, testable success beyond end_turn |
pause_turn cap | Too many server-side continuations | Server tools pause & resume — cap the re-sends too |
end_turn is the natural stop, but it is not a guarantee.
Always add a max-iterations cap plus token/time budgets so a misbehaving loop terminates regardless of what
the model does.CONCEPT pause_turn is a loop too
When the model uses a server-side tool, a turn can come back with
stop_reason == "pause_turn" instead of finishing. The correct response is to re-send the
turn to resume it. That is itself a loop — and like the main loop, an unbounded stream of
pause_turn continuations can run away. Cap the number of continuations the same
way you cap iterations.
DIAGRAM A bounded loop
budget left?
time left?"} G -->|"no — cap hit"| K["🔴 Force stop
return partial + flag"] G -->|yes| C["messages.create()"] C --> S{"stop_reason?"} S -->|end_turn| E["🟢 Done (natural)"] S -->|pause_turn| P["Re-send to resume
(count against cap)"] P --> G S -->|tool_use| T["Run tools → append results"] T --> G classDef ok fill:#d4edda,stroke:#28a745,color:#155724; classDef stop fill:#f8d7da,stroke:#dc3545,color:#721c24; class E ok; class K stop;
CODE A bounded agent loop
The end_turn check is the natural exit; the MAX_ITERS guard and budget checks are
the safety net that guarantees termination even when the model won't stop on its own.
MAX_ITERS = 20 # hard cap — the runaway kill-switch TOKEN_LIMIT = 200_000 # cost budget across the whole loop DEADLINE = time.time() + 120 # wall-clock time budget (seconds) used_tokens, pauses = 0, 0 for i in range(MAX_ITERS): # cap: loop CANNOT exceed MAX_ITERS if used_tokens > TOKEN_LIMIT or time.time() > DEADLINE: break # budget / time exhausted → stop resp = client.messages.create(model="claude-opus-4-8", max_tokens=4096, tools=TOOLS, messages=messages) used_tokens += resp.usage.input_tokens + resp.usage.output_tokens if resp.stop_reason == "end_turn": # NATURAL stop — the happy path break if resp.stop_reason == "pause_turn": # server-side tool paused pauses += 1 if pauses > 5: break # cap continuations too messages.append({"role": "assistant", "content": resp.content}) continue # re-send to resume messages.append({"role": "assistant", "content": resp.content}) messages.append({"role": "user", "content": run_tools(resp.content)}) else: log("⚠️ hit MAX_ITERS without end_turn — returning partial result")
for…else runs only if the loop exhausts MAX_ITERS without a
break — i.e. the agent never reached end_turn. That's your runaway alarm.TRADE-OFFS How tight to set the caps
✅ Tighter caps
- Bounded, predictable cost per run
- Runaway loops die fast
- Latency stays within SLA
⚠️ Tighter caps
- May cut off legitimately long tasks
- More "partial result" outcomes to handle
- Needs graceful truncation / resume logic
EXAM TRAPS
end_turn." → With no cap, a stuck agent runs
forever — runaway cost. Always pair the natural stop with a max-iterations cap and budgets.pause_turn. → Server-side tools return
pause_turn; you must re-send to resume, and cap those continuations too or they
can loop.PRACTICE
Q1 · What is the natural termination condition, and why isn't it enough?
stop_reason == "end_turn" — the model stopped requesting tools. It's not enough
because a malfunctioning or thrashing agent may never emit end_turn; without a cap it loops
indefinitely, driving runaway cost.
Q2 · Your agent returns pause_turn. What do you do, and what must you guard?
Re-send the turn to resume the server-side tool. Guard it with a
continuation cap (e.g. max 5 pauses), because an unbounded stream of pause_turn
re-sends is itself a runaway loop.
Q3 · Iteration cap is 20 but a run cost $40 in 6 iterations. What was missing?
A token / cost budget. Iteration count alone doesn't bound spend — a few turns with massive contexts can be expensive. Add a cumulative token ceiling (and a time budget) alongside the iteration cap.