Lesson 42.3 · 3 of 4 · 6 min read · Reviewed 24 Nov 2026
Stop conditions, turn limits and budgets
By the end, you can
- Set turn limits and budgets that stop a run in code.
- Handle a run that stops early, with a clear message instead of silence.
A model that keeps calling tools won’t stop on its own. Stop conditions belong in your code.
Three limits every agent needs
- Turns.
maxTurnsin the Agent SDKClaude Agent SDK: Anthropic’s library for building agents on the same loop that powers Claude Code, with tools, hooks, subagents and MCP., or a counter in your own loop. Pick it from your evalsEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria.: the 95th-percentile turns on successful runs, plus some headroom. - Budget. Track
usageon every response and stop when the run’s cost or tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. pass a cap. The SDK reportstotal_cost_usdon the result. - Time. A wall-clock deadline, so a slow tool can’t hold a user for minutes.
Catch loops early
A run that repeats the same tool call with the same input is stuck. Keep a count of each name and input pair, and stop at the third repeat. The Playground’s A loop that never ends failure lab shows this happening, and the fix.
End well
When a limit trips, don’t throw away the work. Return a partial result: what was found, what’s left, and the next step (“I’ve opened a ticket for the team”). Log which limit tripped, so you can tune limits from real data.
Key points
- Every agent needs a hard turn limit and a cost or time budget enforced in code.
- Detect loops: the same tool called with the same input several times means stop.
- When a limit trips, end gracefully: say what was done, what wasn't, and what happens next.
Guard a loop with limits and repeat detection
Write a guard that stops an agent loop on turns, budget, wall-clock time or a repeated call, and ends with a useful partial result.
You will have: A LoopGuard class and three scripted runs, each stopped by a different limit, with a graceful summary for each.
Steps
- Read the scripted runs: each is a list of tool calls with a token cost and a simulated duration.
- Write LoopGuard.check(call) to track turns, tokens and elapsed seconds against their caps.
- Count each (name, input) pair, using a stable JSON key without the call id, and stop on the third repeat.
- When a limit trips, return a summary: what was done, what limit tripped, and the next step.
- Run all three scripts and print each summary.
Done when
- The stuck run stops on the third identical call.
- The expensive run stops on the token budget.
- Every stop prints the completed work and which limit tripped.
Open in the Playground No API key needed.
Starter code (Python)
import json
class LoopGuard:
def __init__(self, max_turns=10, max_tokens=20000, max_seconds=60):
self.max_turns, self.max_tokens, self.max_seconds = max_turns, max_tokens, max_seconds
self.turns = self.tokens = self.seconds = 0
self.seen = {}
def check(self, call):
# TODO: update counters; return a reason string if a limit trips, else None
# TODO: key repeats on (name, json.dumps(input, sort_keys=True)) and stop at the third
return None
stuck = [{"id": f"t{i}", "name": "search", "input": {"q": "refund policy"}, "tokens": 500, "secs": 2} for i in range(6)]
pricey = [{"id": f"p{i}", "name": "read_doc", "input": {"doc": i}, "tokens": 6000, "secs": 3} for i in range(6)]
slow = [{"id": f"s{i}", "name": "supplier_quote", "input": {"sku": i}, "tokens": 300, "secs": 25} for i in range(6)]
for name, run in [("stuck", stuck), ("pricey", pricey), ("slow", slow)]:
g, done = LoopGuard(), []
for call in run:
reason = g.check(call)
if reason:
break
done.append(call["name"])
print(name, done)
Show a solution
import json
class LoopGuard:
def __init__(self, max_turns=10, max_tokens=20000, max_seconds=60):
self.max_turns, self.max_tokens, self.max_seconds = max_turns, max_tokens, max_seconds
self.turns = self.tokens = self.seconds = 0
self.seen = {}
def check(self, call):
self.turns += 1
self.tokens += call["tokens"]
self.seconds += call["secs"]
key = (call["name"], json.dumps(call["input"], sort_keys=True))
self.seen[key] = self.seen.get(key, 0) + 1
if self.seen[key] >= 3:
return f"repeated call {call['name']} x3"
if self.turns > self.max_turns:
return "turn limit"
if self.tokens > self.max_tokens:
return f"token budget ({self.tokens} > {self.max_tokens})"
if self.seconds > self.max_seconds:
return f"time limit ({self.seconds}s > {self.max_seconds}s)"
return None
stuck = [{"id": f"t{i}", "name": "search", "input": {"q": "refund policy"}, "tokens": 500, "secs": 2} for i in range(6)]
pricey = [{"id": f"p{i}", "name": "read_doc", "input": {"doc": i}, "tokens": 6000, "secs": 3} for i in range(6)]
slow = [{"id": f"s{i}", "name": "supplier_quote", "input": {"sku": i}, "tokens": 300, "secs": 25} for i in range(6)]
for name, run in [("stuck", stuck), ("pricey", pricey), ("slow", slow)]:
g, done = LoopGuard(), []
for call in run:
reason = g.check(call)
if reason:
print(f"{name}: stopped: {reason}. Done: {len(done)} calls. Left: {len(run) - len(done)}. Next: hand the open items to a person.")
break
done.append(call["name"])
Do it Fix a runaway loop in the failure lab in the Playground. No API key needed.