Sub topic 8
Handling errors, retries, and stop conditions
This chapter assumes you can write Python, call web APIs, and read JSON. It also assumes you have seen the agent loop from the previous chapter: the model picks a tool, your code runs it, and the result goes back into the history. Here we cover what happens when something goes wrong, and how the loop knows when to stop.
Why agents need an error strategy
A normal program fails in a few predictable places. An agent fails in more places, because a model is choosing the actions. Four kinds of failure are common:
- The model asks for a tool that does not exist.
- The model passes bad arguments, such as a missing field or a wrong type.
- The tool itself fails: a timeout, a rate limit, a bad response from an API.
- The model never finishes. It repeats the same call or wanders without making progress.
The first three are errors. The fourth is a stop-condition problem. Each needs a different response.
Three layers of handling
Think of error handling as three layers, from the inside out.
| Layer | What goes wrong | Typical response |
|---|---|---|
| Tool | Network error, invalid input, missing record | Retry if the error is transient, otherwise return the error as text |
| Loop | Model requests an unknown tool or sends bad arguments | Return the error to the model so it can correct itself |
| Run | Too many steps, repeated calls, budget exceeded | Stop and report the reason |
The key idea is that most errors should become observations. An observation is the text the model reads after a tool call. If you raise an exception instead, the whole run dies and the model never gets a chance to adapt.
Return errors as observations
The run_tool function below does this. It looks up the tool by name, calls it, and turns every failure into a JSON string.
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, TOOLS[name](**arguments) raises a TypeError. The except block catches it and returns something like {"error": "get_weather() got an unexpected keyword argument 'town'"}. The model reads that message on the next step and usually fixes the call.
This works only if the message is useful. Compare two messages:
- Poor:
{"error": "failed"} - Better:
{"error": "city must be a non-empty string, got ''"}
A good error message says what was wrong and, when possible, what a valid call looks like. The model is the reader, so write for it.
Retrying transient failures
Not every failure should go back to the model. If a request times out, the model has no new information to act on. It will probably issue the same call again, and that costs a model call and more context. Retry transient failures inside the tool layer instead.
A failure is transient when trying again might succeed: timeouts, rate limits (HTTP 429), and server errors (HTTP 5xx). A failure is permanent when trying again cannot help: a bad argument, a missing record (404), or a permission denial.
The standard technique is exponential backoff with jitter. You wait longer after each failed attempt, and you add a random amount so many clients do not retry at the same moment.
import random
import time
class TransientError(Exception):
"""Raised by tools for failures that may succeed on retry."""
def with_retries(fn, attempts: int = 3, base_delay: float = 0.5):
for attempt in range(attempts):
try:
return fn()
except TransientError:
if attempt == attempts - 1:
raise
delay = base_delay * (2 ** attempt) + random.uniform(0, 0.25)
time.sleep(delay)
# Example: a flaky tool that fails twice, then succeeds.
calls = {"n": 0}
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("service busy")
return "ok"
print(with_retries(flaky))This prints ok after two short waits. If all attempts fail, the last TransientError is raised. Your run_tool then catches it and returns it to the model as an error observation, so the model knows the tool is unavailable and can choose another approach or tell the user.
Retries have limits you must respect:
- Retry only idempotent operations by default. An operation is idempotent if running it twice has the same effect as running it once. Reading a record is idempotent. Sending an email or charging a card is not. Retrying a timed-out payment may charge the customer twice, because the first request might have succeeded.
- For non-idempotent tools, use an idempotency key, a unique ID the service uses to ignore duplicates, or do not retry.
- Cap the attempts. Unbounded retries turn a brief outage into a stuck run.
Stop conditions
The loop from the previous chapter has one stop condition built in: the model answers without a tool call. That is the success case. A reliable agent needs more.
| Condition | Why it matters |
|---|---|
| Final answer | The normal, successful exit |
| Step limit | Prevents endless loops and runaway cost |
| Repeated call detection | Catches a model stuck calling the same tool with the same arguments |
| Consecutive error limit | Stops a run where every tool call fails |
| Time or token budget | Bounds latency and spend |
| Human interrupt | Lets a person cancel a run |
The basic loop already has a step limit:
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."Here is a version that adds repeated-call detection and a consecutive-error limit. It reuses run_tool from above.
def run_agent_safe(call_model, user_goal: str, max_steps: int = 8,
max_repeats: int = 2, max_errors: int = 3) -> str:
messages = [{"role": "user", "content": user_goal}]
seen = {}
errors_in_a_row = 0
for _ in range(max_steps):
reply = call_model(messages)
call = reply.get("tool_call")
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": call})
if call is None:
return reply["content"]
key = (call["name"], json.dumps(call["arguments"], sort_keys=True))
seen[key] = seen.get(key, 0) + 1
if seen[key] > max_repeats:
return f"Stopped: repeated call to {call['name']} with the same arguments."
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
if '"error"' in result:
errors_in_a_row += 1
if errors_in_a_row >= max_errors:
return "Stopped: too many consecutive tool errors."
else:
errors_in_a_row = 0
return "Stopped: step limit reached."The string check for "error" is a shortcut to keep the example short. In production, have tools return a structured result with an explicit ok field so a successful result that happens to contain the word "error" is not miscounted.
Testing failure paths
Use a scripted model to test stop conditions without calling a real model. This one keeps requesting the same tool, so the repeat guard should fire.
def looping_model(messages):
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
print(run_agent_safe(looping_model, "Weather in Oslo?"))The output is Stopped: repeated call to get_weather with the same arguments. after the third identical call.
Reporting why a run stopped
A bare string like "Stopped" hides information. When a run ends without an answer, tell the caller why. Better still, return a structured result with a status such as completed, step_limit, repeat_limit, or error_limit, plus the message history. This lets your application show a sensible message, retry with a different strategy, or hand off to a person. The later chapters on tracing and evaluation rely on these reasons to find patterns in failures.
Common mistakes
- Raising exceptions out of tools. The run crashes and the model cannot recover.
- Retrying non-idempotent actions without an idempotency key.
- Setting no step limit, or a very high one. A stuck loop then costs real money.
- Vague errors such as "failed". The model cannot adjust its next call.
- Treating a stop as a failure of the whole system. A clear "I could not finish, and here is why" is a correct outcome.
- Letting the model retry forever on a permanent error. Distinguish transient from permanent failures in the tool layer.
Exercise
A tool that sends a customer email times out. Should the tool layer retry it automatically? Explain what you would do instead.
Show answer
Not by default. The timeout does not show whether the first request failed, so a retry could send the email twice. Send the request with an idempotency key so the service ignores duplicates, and then retry. If the service does not support keys, return an error observation that says the outcome is unknown, so the model or a person can check before acting again.
Exercise
In run_agent_safe, max_repeats is 2 and the model makes the same call three times in a row. On which call does the loop stop, and does the tool run on that call?
Show answer
It stops on the third call. The counter reaches 3, which is greater than 2, and the check happens before run_tool, so the tool does not run a third time.
Exercise
Why is returning {"error": "city must be a non-empty string, got ''"} better than raising a ValueError out of the tool?
Show answer
A raised exception ends the run, and the model never sees it. The returned message becomes an observation, so the model learns what was wrong and can fix its arguments on the next step.