Sub topic 10
Turn Limits and Loop Guards
This chapter assumes you can read the Agent and run code from the handoff chapter, that you know what a tool call is, and that you are comfortable with Python dataclasses and JSON. It covers how to stop a multi-agent run that will not stop on its own.
Why multi-agent runs loop
A single agent loop ends when the model returns a final answer. Multi-agent systems add more ways to keep going. Each handoff or delegation gives the run another chance to continue, and no single agent sees the whole run.
Common loop shapes:
- Ping-pong handoff. Agent A hands off to B because the request looks like B's job. B decides it is A's job and hands it back. Neither makes progress.
- Repeated tool call. An agent calls the same tool with the same arguments, gets the same error or empty result, and tries again.
- Runaway delegation. An orchestrator calls a specialist. The specialist is also allowed to delegate, and the chain gets deeper with each call.
- Slow drift. The agent keeps doing different but useless work, such as searching with slightly reworded queries. No two steps are identical, so a duplicate check never fires.
Each turn costs tokens and time, so a loop is a billing problem as well as a correctness problem. You need guards that do not depend on the model deciding to stop.
The turn limit
The simplest guard is a hard cap on loop iterations. The run function from the handoff example already has one:
for _ in range(max_turns):
reply = call_model(agent, messages)
...
raise RuntimeError("max_turns exceeded")Three details matter.
- A turn is one model call. Handoffs and tool calls each use a turn, because each one needs a model call to produce it. A task needing 3 tool calls, 1 handoff, and a final answer uses 5 turns. Set the limit above your realistic worst case, not your average.
- The limit does not compose by default. In the orchestrator example, each specialist runs through its own
runcall with its ownmax_turns. An orchestrator with a limit of 10 that calls specialists with a limit of 10 can make up to 100 model calls. The nested limits multiply. - Raising is a choice. Raising an exception makes the failure visible. Returning a partial result is friendlier, but it can hide the failure from the caller. Pick one deliberately and keep it the same across the system.
A shared budget fixes the multiplication problem. Pass one counter into every nested run.
from dataclasses import dataclass
class BudgetExceeded(RuntimeError):
pass
@dataclass
class Budget:
turns_left: int
def spend(self) -> None:
if self.turns_left <= 0:
raise BudgetExceeded("turn budget exhausted")
self.turns_left -= 1
def run_with_budget(start, messages, call_model, budget: Budget):
agent = start
while True:
budget.spend()
reply = call_model(agent, messages)
if reply["type"] == "final":
return agent.name, reply["text"]
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)}
)If as_tool passes the same Budget object to each specialist's run, a whole request, including every nested call, draws from one pool of turns.
Loop guards
A turn limit stops a loop only after it has burned the whole budget. Loop guards detect the pattern earlier. They are checks that run each turn and stop the run, or change its course, when they see a known bad pattern.
Repeated-call detection
Record each tool call as a name plus its arguments. If the same call appears too many times, stop.
import json
from collections import Counter
class RepeatCallGuard:
def __init__(self, limit: int = 3):
self.limit = limit
self.seen = Counter()
def check(self, name: str, args: dict) -> None:
key = (name, json.dumps(args, sort_keys=True))
self.seen[key] += 1
if self.seen[key] > self.limit:
raise RuntimeError(f"tool {name} repeated with identical arguments")Using sort_keys=True makes {"a": 1, "b": 2} and {"b": 2, "a": 1} count as the same call. Some repeats are legitimate, such as polling a job status, so allow a few and make the limit configurable per tool.
Handoff cycle detection
For handoffs, track the sequence of agent names. A cycle shows up as the same agent appearing again with no new tool results between visits.
class HandoffGuard:
def __init__(self, max_visits: int = 2):
self.max_visits = max_visits
self.visits = Counter()
def enter(self, agent_name: str) -> None:
self.visits[agent_name] += 1
if self.visits[agent_name] > self.max_visits:
raise RuntimeError(f"agent {agent_name} entered too many times")A visit limit of 2 allows one legitimate return, for example triage to billing and back to triage. It blocks ping-pong on the third entry. If your design never returns to a previous agent, set the limit to 1.
Depth limits for delegation
For orchestrators, pass a depth counter and increment it on each nested call. Refuse to delegate when it exceeds a small number, usually 2 or 3. The simplest rule is that specialists get no delegation tools at all, so depth is fixed at 1.
No-progress detection
Slow drift defeats exact-match checks. Two cheaper signals help:
- Turns since the last new information. If the last N tool results add nothing new (empty, or already in the message history), stop.
- A required exit condition. Instruct the agent to produce its final answer by a specific step, and treat a missed deadline as a failure.
These are heuristics. They will have false positives, so log when they fire.
Combining the guards
Put the checks in one place so no code path skips them. A wrapper around the model call is a good location, because every turn passes through it.
def guarded_run(start, messages, call_model, budget, tool_guard, handoff_guard):
agent = start
handoff_guard.enter(agent.name)
while True:
budget.spend()
reply = call_model(agent, messages)
if reply["type"] == "final":
return agent.name, reply["text"]
if reply["type"] == "handoff":
agent = agent.handoffs[reply["target"]]
handoff_guard.enter(agent.name)
continue
tool_guard.check(reply["name"], reply["args"])
result = agent.tools[reply["name"]](**reply["args"])
messages.append(
{"role": "tool", "name": reply["name"], "content": str(result)}
)Note the order: the guard runs before the tool, so a repeated destructive call never executes a fourth time.
What happens when a guard fires
Raising an exception is only half the design. Decide what the caller does next.
| Guard fired | Reasonable response |
|---|---|
| Turn budget exhausted | Return an error to the user, or escalate to a human with the message history attached |
| Repeated tool call | Feed an error message back to the model once ("this call already failed, try something different"), then stop on the next repeat |
| Handoff cycle | Route to a fallback agent or a human, since the routing logic is wrong for this input |
| Depth limit | Return a tool error so the orchestrator handles the task itself |
Feeding the model a message about the guard gives it a chance to recover. Do this only once per guard, or the recovery message becomes part of the loop.
Edge cases
- Side effects before the limit. When the budget runs out mid-task, earlier tool calls have already happened. A refund issued on turn 4 is not undone by a failure on turn 9. Make tools idempotent where you can, and record which side effects occurred so a human can check.
- Counting turns across retries. A retry after a transient error should usually spend budget too. Otherwise a flapping service can extend a run indefinitely.
- Parallel calls. If an orchestrator fans out several specialists at once, a shared budget needs a lock or an atomic counter. A plain integer decrement can race.
- Limits that are too tight. A limit of 3 turns will fail legitimate tasks that need a tool call, a handoff, and a final answer. Measure real runs and set limits from the observed maximum plus a margin.
- Silent truncation. Do not stop the loop and return the last intermediate message as if it were the answer. The user will read it as a finished result.
Summary of the guards
| Guard | Catches | Cost of false positive |
|---|---|---|
| Turn limit | Any unbounded loop | Legitimate long tasks fail |
| Shared budget | Multiplying nested limits | Same as turn limit |
| Repeat-call guard | Identical retried calls | Valid polling is blocked |
| Handoff visit limit | Ping-pong between agents | Valid return trips are blocked |
| Depth limit | Runaway delegation | Deep decompositions fail |
| No-progress check | Slow drift | Slow but valid work is cut off |
Exercise
An orchestrator has maxturns=8 and calls a specialist through astool. The specialist's run also uses max_turns=8, and each specialist call is stuck in a loop. What is the worst-case number of model calls for one user request, and what change caps it at 12 in total?
Show answer
Each of the orchestrator's 8 turns can call the specialist, and each specialist run can use 8 model calls. In the worst case the orchestrator makes 8 calls and the specialist runs make 7 x 8 = 56 more if the last orchestrator turn is a final answer, or 8 x 8 = 64 if every orchestrator turn delegates, so roughly 64 to 72 calls. Create one Budget(turns_left=12) per request and pass the same object into every nested run, so every model call from any agent calls budget.spend(). The run then raises BudgetExceeded once 12 calls have been made in total.
Exercise
Two agents, billing and triage, hand off to each other forever. A HandoffGuard with max_visits=2 is used, and the run starts at triage. On which handoff does the guard raise?
Show answer
The start counts as the first visit to triage. Triage hands to billing (billing visit 1), billing hands back to triage (triage visit 2, allowed), triage hands to billing (billing visit 2, allowed), billing hands to triage (triage visit 3), and the guard raises on that fourth handoff.