Sub topic 11
Handling failures and retries
This chapter assumes you know the Agent and run loop from the earlier chapters, and that you can read basic Python exception handling. In a multi-agent system, a failure in one agent can spread to the others. This chapter covers how to classify failures, retry the ones worth retrying, and report the rest so the system can recover or stop cleanly.
Where failures come from
A multi-agent run has more places to fail than a single agent. Each of these has a different cause and a different fix.
| Failure | Example | Usually transient? |
|---|---|---|
| Model call error | Timeout, rate limit, 5xx response | Yes |
| Malformed model output | Invalid JSON arguments, unknown tool name | Sometimes |
| Tool error | Database down, permission denied, bad argument | Depends on the cause |
| Bad handoff | Target agent name does not exist | No |
| Worker failure | A specialist called as a tool crashes or gives up | Depends on the cause |
| Wrong but successful result | A worker returns a confident, incorrect answer | No |
The last row is the hardest. No exception is raised, so retry logic never sees it. Catching it needs validation and evaluation, which the tracing chapter covers.
Transient and permanent errors
A retry only helps if the next attempt can succeed. Timeouts, rate limits, and temporary server errors are transient, so waiting and trying again often works. Invalid arguments, missing permissions, and unknown tools are permanent, so the same call fails again, and each retry only adds cost and delay.
Make this split explicit in code. Wrap errors from your tools and model client in two exception classes, then retry only one of them.
import random
import time
class TransientError(Exception):
"""Timeouts, rate limits, 5xx responses: worth retrying."""
class PermanentError(Exception):
"""Bad arguments, missing permissions: retrying will not help."""
def with_retries(fn, attempts=3, base_delay=0.5, sleep=time.sleep):
for attempt in range(1, attempts + 1):
try:
return fn()
except TransientError:
if attempt == attempts:
raise
delay = base_delay * 2 ** (attempt - 1)
sleep(delay + random.uniform(0, delay / 2))
calls = {"n": 0}
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("timeout")
return "ok"
print(with_retries(flaky, sleep=lambda s: None), calls["n"])This prints ok 3. The function failed twice and succeeded on the third attempt. The delay doubles after each failure (exponential backoff). The random jitter keeps many agents from retrying at the same instant after a shared outage. The sleep parameter lets a test skip the real waiting.
Decision flow for a failed call
Return errors as results
In the run function from earlier chapters, a tool that raises an exception ends the whole loop. For an orchestrator that is usually too harsh. The agent that made the call is often better placed to decide what to do next, so convert the failure into a message it can read.
def safe_tool(name, fn, attempts=3):
def wrapper(**kwargs):
try:
return with_retries(lambda: fn(**kwargs), attempts=attempts)
except TransientError as e:
return (
f"ERROR[{name}] unavailable after {attempts} attempts: {e}. "
"Do not retry. Continue without it or report the gap."
)
except PermanentError as e:
return (
f"ERROR[{name}] invalid request: {e}. "
"Fix the arguments or choose another approach."
)
return wrapperThe error text matters because the model reads it. A message that says what happened and what to do next ("Do not retry") keeps the model from looping on a dead tool. A bare stack trace gives it nothing to act on.
You can use the same wrapper on the workers from the orchestrator chapter. Wrap as_tool(researcher, call_model) with safe_tool("research", ...). If the research worker fails, the orchestrator receives an error string and can still call the writer with a note about the missing research. It does not lose the whole request.
Retries multiply across layers
Retries at different layers multiply. Suppose the model client retries 3 times, each tool retries 3 times, and the orchestrator re-runs a failed worker up to 3 times. One bad dependency can then produce 27 calls for a single user request.
- Retry at one layer for each kind of failure. Usually that is the lowest layer, next to the call that failed.
- Give each run a total retry budget, for example 5 retries across the whole workflow, and stop when it is spent.
- Count retried calls toward
max_turnsor a separate call limit. Retries must not hide a runaway loop.
Retrying side effects safely
Retrying a read is harmless. Retrying a write can do the action twice. A timeout does not mean the call failed. The request may have succeeded while the response was lost. If a issue_refund tool times out and you retry it, the customer may be refunded twice.
Two defenses work together:
- Give each side-effecting call an idempotency key, a unique ID generated once per logical action and sent with every retry. The receiving service uses it to ignore duplicates.
- Do not auto-retry a write that has no idempotency protection. Return an error result, or escalate, and let a person decide.
Malformed model output
Models sometimes return arguments that do not parse, or name a tool or handoff target that does not exist. In the run function above, agent.handoffs[reply["target"]] raises a KeyError on a bad target, and agent.tools[...] does the same for a bad tool name. These are not transient errors, so do not retry them blindly. Validate first, then send the model a specific correction:
def resolve_handoff(agent, target):
if target not in agent.handoffs:
allowed = ", ".join(sorted(agent.handoffs)) or "none"
return None, f"ERROR: unknown handoff target '{target}'. Allowed targets: {allowed}."
return agent.handoffs[target], NoneWhen resolve_handoff returns an error message, append it to the history as a tool message and let the model try again. Allow only one or two such corrections for each step. After that, treat the step as failed.
Partial failure in an orchestrator
An orchestrator that calls several workers can end up with some results and some errors. Decide the policy before you write the code:
- Required worker: the task cannot be completed without it, so fail the run or escalate.
- Optional worker: continue and say what is missing.
- Redundant worker: try a fallback, such as a second search agent or a simpler model.
Whichever policy applies, the final answer must not pretend the missing part exists. Put the gap in the orchestrator's instructions: "If a specialist returns an ERROR, say which part could not be completed." Without that line, models often fill the hole with invented content.
Failed handoffs
A handoff transfers control, so the failure modes differ from tool calls. If the target agent fails, there is no caller waiting to catch the error, because the previous agent has already stepped aside. Two practical rules:
- Keep the message history intact so a fallback agent, usually the triage agent or a human queue, can see what was attempted.
- Record the last successful agent and the error in the run state, so you can resume or escalate with context.
Handoffs also create a loop risk when A fails, hands to B, and B hands back to A. The turn limit from the previous chapter bounds this, and failure handling should respect it. If a handoff target has already failed in this run, do not route to it again.
Escalate when recovery is not possible
Some failures need a person: a permission error on a customer account, repeated invalid output, or an unprotected write that timed out. Stop the run, save the history and error, and hand it to a human queue with a short summary. The human-approval chapter covers that path.
Checklist
- Wrap model, tool, and handoff errors into transient and permanent classes.
- Retry transient errors with backoff and jitter, at one layer, within a total budget.
- Turn exhausted retries and permanent errors into readable error results.
- Protect side effects with idempotency keys.
- Decide whether each worker is required, optional, or redundant.
- Escalate with saved state when recovery fails.
Exercise
An orchestrator calls a charge_card tool. The call times out, and your retry wrapper calls it again. The customer is charged twice. What went wrong, and how do you prevent it?
Show answer
A timeout does not prove the first call failed. The request may have succeeded while the response was lost, so a blind retry repeated a side effect. Prevent it by generating one idempotency key per logical charge and sending the same key with every retry, so the payment service ignores duplicates. If the tool cannot support idempotency keys, do not auto-retry it. Return an error result or escalate to a human instead.
Exercise
Your model client retries 3 times, each tool retries 3 times, and the orchestrator re-runs a failed worker up to 3 times. How many calls can one failing request cause, and how would you reduce it?
Show answer
Up to 27 calls, because the retries at the three layers multiply (3 x 3 x 3). Reduce it by retrying at only one layer, usually the lowest, and by adding a total retry budget for the whole run that also counts toward the turn limit.