Sub topic 11
Handling failures and retries
This chapter assumes you have read the handoff and orchestrator chapters and know the run loop and the as_tool wrapper. You should also be comfortable with Python exceptions. It covers what to do when a specialist agent or a tool breaks partway through a multi-agent run.
Why failures spread
In a multi-agent system, one failure can become several. A tool times out inside a specialist. The specialist returns an empty string. The orchestrator treats that string as a finished result and passes it to the writer, which produces a confident answer built on nothing. The error disappears and bad output takes its place.
Failures fall into three groups, and each needs a different response.
| Failure type | Example | Response |
|---|---|---|
| Transient | Timeout, rate limit, HTTP 503 | Retry with backoff |
| Recoverable by the model | Bad tool arguments, unknown handoff target | Return the error text to the agent so it can correct itself |
| Permanent | Missing permission, deleted order | Stop retrying and escalate or fail clearly |
Retry only what is safe to retry
A retry repeats the call. That is fine for a search and dangerous for "issue refund". Retry only transient errors, and only for operations that are idempotent, meaning that running them twice has the same effect as running them once. For side effects, pass an idempotency key so the downstream system can ignore duplicates.
Use exponential backoff with a little random jitter. This stops many parallel agents from retrying at the same moment.
import random
import time
class TransientError(Exception):
"""Timeouts, rate limits, 5xx responses. Safe to retry."""
def with_retries(fn, attempts=3, base_delay=0.5):
def wrapped(*args, **kwargs):
for attempt in range(1, attempts + 1):
try:
return fn(*args, **kwargs)
except TransientError:
if attempt == attempts:
raise
delay = base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.1)
time.sleep(delay)
return wrapped
def safe_tool(fn):
"""Turn exceptions into text the calling agent can read."""
def wrapped(**kwargs):
try:
return fn(**kwargs)
except Exception as exc:
return f"ERROR: {type(exc).__name__}: {exc}"
return wrapped
calls = {"n": 0}
def flaky_search(query: str) -> str:
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("search backend timed out")
return f"results for {query!r}"
search = safe_tool(with_retries(flaky_search, base_delay=0.01))
print(search(query="refund policy")) # succeeds on the third attemptThe order matters. with_retries sits inside safe_tool, so retries happen first. Only an error that survives all attempts becomes text for the agent.
Make failures visible to the orchestrator
When the orchestrator calls a specialist through as_tool, a failure inside the worker should arrive as an explicit error. It should not arrive as an empty or partial answer. Prefix error strings consistently, as ERROR: does above, and tell the orchestrator in its instructions what to do when it sees one. It can retry with a clearer task, try another specialist, or report the gap in its final answer.
Common errors
- Retrying inside every layer. If the tool, the specialist, and the orchestrator each retry three times, one outage produces 27 calls. Retry at one layer, usually closest to the failing call.
- Letting the model retry forever. Keep
max_turnsas the outer limit, because error text can send an agent into a loop of identical failing calls. - Swallowing errors. Returning
""on failure hides the problem from the orchestrator and from your traces. - Retrying non-idempotent actions without a key.
Exercise
A specialist agent calls a tool that raises a permission error. Should with_retries retry it, and what should the orchestrator receive?
Show answer
No. A permission error is permanent, so retrying only wastes time and cost. with_retries should catch only TransientError, so the permission error passes through to safe_tool. safe_tool turns it into an ERROR: string. The orchestrator can then report the gap or escalate instead of treating the result as an answer.