Sub topic 3
Turn Limits and Loop Guards
Assume you know basic Python, JSON, message-based LLM APIs, and tool calling. A multi-agent run needs explicit boundaries because agents can repeatedly call tools, hand off control, or retry the same failure.
Turn limits and loop guards
A turn limit caps the number of model decisions in one run. A loop guard detects repeated states, agents, or tool calls.
def run(agent, messages, call_model, max_turns=8):
seen = set()
for turn in range(max_turns):
reply = call_model(agent, messages)
state = (agent.name, reply["type"], reply.get("name"),
reply.get("target"))
if state in seen:
raise RuntimeError("repeated agent state")
seen.add(state)
if reply["type"] == "final":
return reply["text"]
if reply["type"] == "handoff":
agent = agent.handoffs[reply["target"]]
elif reply["type"] == "tool":
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "content": str(result)})
raise TimeoutError("agent turn limit exceeded")Use a separate budget for model turns, tool calls, retries, and elapsed time. A limit should produce a diagnosable failure, not silently return an incomplete answer.
Handling failures and retries
Retry only transient failures, such as timeouts or rate limits. Use exponential backoff with jitter. Do not retry invalid arguments or authorization failures. Make side-effecting tools idempotent, meaning repeating the request has the same effect as running it once.
Parallel fan-out and merging
An orchestrator can send independent subtasks to specialists in parallel. It then validates and merges their results. Parallel work reduces latency but increases cost and makes partial failure likely.
flowchart TD
A[Orchestrator] --> B[Research agent]
A --> C[Analysis agent]
A --> D[Policy agent]
B --> E[Validate and merge]
C --> E
D --> ETracing and evaluation
Record a run ID, parent-child agent relationship, prompt version, tool name, latency, token usage, outcome, and error. Evaluate complete workflows with test cases, not only individual agent answers. Check correctness, tool safety, escalation behavior, and termination.
Security and trust boundaries
Treat every agent output as untrusted data. Validate structured payloads against a schema, restrict each agent’s tools, and never let delegated text grant permissions. Keep secrets outside prompts and logs.
> callout warning > Delegation expands the permission graph. A specialist should receive only the data and tools required for its task.
Cost, latency, and approval
Each handoff or specialist call adds model cost and usually latency. Set budgets before execution. Require human approval before irreversible actions such as refunds, account changes, or external messages.
| Workflow need | Suitable control |
|---|---|
| Independent research tasks | Parallel fan-out |
| Irreversible action | Human approval |
| Repeated delegation | Turn and state limits |
Exercise
What should happen when an agent reaches its turn limit while handling a refund?
Show answer
Stop the run, record the trace, report an incomplete decision, and escalate to a human instead of issuing the refund.