Sub topic 8
Handling errors, retries, and stop conditions
This chapter assumes you can read Python, have seen the agent loop from the previous chapter, and know what a tool call is. Here you will make that loop survive failures and stop at the right time.
Why agents need error handling
An agent calls a model and tools many times in one run. Each call can fail, and one unhandled failure ends the whole run. Failures fall into two groups:
- Tool errors: bad arguments, an unknown tool, a timeout, or an exception inside your function.
- Transient errors: rate limits or network drops when calling the model or an API.
The two groups need different handling. Tool errors go back to the model as text. Transient errors are retried by your code.
Return tool errors as text
The model chose the arguments, so it can often fix them. The run_tool function catches exceptions and returns them as JSON instead of crashing.
import json
def get_weather(city: str) -> str:
# Stand-in for a real API call.
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})If the model calls get_weather with a wrong argument name, the TypeError message comes back as an observation. The model can read it and try again.
Retry transient failures
A rate limit says "try later", so the model does not need to see it. Retry in code, wait longer after each failure, and add random jitter so many clients do not retry at the same moment.
import random
import time
def with_retries(fn, attempts: int = 4, base_delay: float = 0.5):
for attempt in range(attempts):
try:
return fn()
except (TimeoutError, ConnectionError):
if attempt == attempts - 1:
raise
time.sleep(base_delay * 2 ** attempt + random.random() * 0.1)Retry only errors that can succeed on a second try. Retrying a validation error wastes time. Retrying a tool that sends an email can send it twice, so retry such tools only if they are idempotent (safe to repeat).
Stop conditions
A loop with no exit can run forever and cost money. Use several stops:
- Final answer: the model replies without a tool call.
- Step limit:
max_stepscaps the number of iterations. - Repeated failure: the same call fails several times in a row.
- Budget: a cap on tokens, cost, or elapsed time.
The loop below has the first two stops. It is unchanged from the previous chapter.
def run_agent(call_model, user_goal: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
return reply["content"]
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."Common mistakes
- Catching errors and returning an empty string. The model cannot tell failure from success.
- Retrying everything, including non-idempotent actions.
- Having no step limit, or setting it so high it never triggers.
- Returning the limit message as if it were a real answer. Callers should be able to tell a stopped run from a finished one.
Exercise
A tool raises "city is required" because the model omitted an argument. Should your code retry the same call, or return the error to the model? Why?
Show answer
Return the error to the model as text. Retrying the same call would fail again because the arguments are unchanged. The model can read the message, fix the arguments, and call the tool again. Reserve code-level retries for transient failures such as timeouts and rate limits.
Exercise
Name two stop conditions besides the step limit, and say what each one protects against.
Show answer
A repeated-failure check protects against loops where the model keeps making the same failing call. A budget cap (tokens, cost, or time) protects against runs that stay under the step limit but still cost too much or run too long.