Sub topic 10
Turn limits and loop guards
This chapter assumes you have read the handoff and orchestrator chapters and can write a basic agent loop in Python. Here you add the limits that stop that loop from running forever.
Why loops happen
An agent loop ends only when the model returns a final answer. Models don't always do that. Two agents can hand off to each other because each thinks the other is the better fit. An agent can call the same tool with the same arguments and expect a different result. An orchestrator can keep re-delegating a subtask that a specialist keeps failing.
Each extra turn costs tokens and time. An unbounded loop can run up a large bill before anyone notices.
Layer the guards
One limit is not enough. Use several, from coarse to specific.
| Guard | What it stops | Typical response |
|---|---|---|
| Turn limit (`max_turns`) | Any runaway loop | Raise an error or return a partial result |
| Repeated-action check | Same tool call or handoff repeated | Stop early with a clear reason |
| Budget cap (tokens, cost, wall-clock time) | Slow or expensive runs | Abort and report spend |
| Per-child limit | One specialist looping inside an orchestrator | Fail that tool call only |
The turn limit is the backstop. The repeated-action check catches most loops sooner, so you spend fewer turns finding out.
A guarded loop
This version extends the basic loop. It counts each handoff and each identical tool call, and it stops when one repeats more than max_repeats times. The demo model always hands off, so the two agents ping-pong until the guard fires.
import json
from collections import Counter
from dataclasses import dataclass, field
from typing import Callable
class LoopGuardError(RuntimeError):
pass
@dataclass
class Agent:
name: str
tools: dict[str, Callable] = field(default_factory=dict)
handoffs: dict[str, "Agent"] = field(default_factory=dict)
def run_guarded(start, messages, call_model, max_turns=10, max_repeats=2):
agent = start
seen = Counter()
for _ in range(max_turns):
reply = call_model(agent, messages)
if reply["type"] == "final":
return agent.name, reply["text"]
if reply["type"] == "handoff":
key = ("handoff", agent.name, reply["target"])
else:
args = json.dumps(reply["args"], sort_keys=True)
key = ("tool", agent.name, reply["name"], args)
seen[key] += 1
if seen[key] > max_repeats:
raise LoopGuardError(f"repeated action: {key}")
if reply["type"] == "handoff":
agent = agent.handoffs[reply["target"]]
continue
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise LoopGuardError("max_turns exceeded")
a, b = Agent("a"), Agent("b")
a.handoffs["b"] = b
b.handoffs["a"] = a
def ping_pong(agent, messages):
return {"type": "handoff", "target": "b" if agent.name == "a" else "a"}
try:
run_guarded(a, [], ping_pong)
except LoopGuardError as err:
print(err)The guard fires on turn 5, when the handoff from a to b happens a third time. Without it, the run would use all 10 turns.
Choosing limits
- Set
max_turnsfrom observed runs. Measure a normal run's turn count, then allow about two to three times that. - Keep
max_repeatslow, usually 2 or 3. A legitimate retry rarely needs more. - Count tool calls by name and arguments, not by name alone. Calling
searchfive times with different queries is fine. - In an orchestrator, give each specialist its own limit. Then one stuck worker fails its own call instead of using the manager's whole budget.
Exercise
In the demo, max_repeats=2 and the agents alternate handoffs. On which turn does the guard raise, and why not turn 4?
Show answer
Turn 5. Turns 1 to 4 give two a-to-b handoffs and two b-to-a handoffs, so each key has a count of 2, which is not greater than max_repeats. Turn 5 is the third a-to-b handoff, so its count of 3 exceeds the limit.