← Back to Agentic AI map
Lesson 1.10 · Agents From Scratch

Error Handling & Retries

Catch bad output, unknown tools, and tools that blow up - and keep the agent running.

robustness

What you will be able to do

  • Name the three failures a hand-built agent meets, and who caused each one
  • Validate model output, and retry it with corrective feedback
  • Turn an unknown tool and a failing tool into Observations the model can act on
  • Explain why errors should neither crash the agent nor disappear silently
  • Count what retries cost, and bound them
  • Give the model a way out when no tool can help

The idea, in plain English

Everything that can go wrong in the Lesson 1.6 loop eventually does. The model writes a reply in the wrong format. It asks for a tool that does not exist. Or the tool itself fails with an error.

Each failure gets its own fix, because each one has a different cause. Wrong format: tell the model and ask again. Unknown tool: reply with the list of real tools. A tool that fails: catch the error and send it back as text. Nothing crashes, nothing is hidden - the model always finds out what went wrong and gets a chance to fix it.

Two limits stop this from going on forever: max_steps for the whole run, and max_retries_per_step for each reply. We ran it against a local model - and found a fourth failure the three fixes do not cover.

Worked example: Add retry logic to the ReAct loop from Lesson 1.6.

workflowThree failures, three fixesstep 1 / 4

Failure 1 - the reply cannot be read

No Action and no Final Answer - "Action: (no action needed, just a thought)", say. The original loop gave up here. Now it appends a nudge and asks again, up to max_retries_per_step times.

made by
the model
fix
nudge + retry
costs
one more call
limit
max_retries_per_step

One agent step, and every way it can go wrong. Each failure ends up as text the model reads on its next turn - never as a crash.

An everyday example: when things go wrong in the shop

Back to the shop. The owner and the helper work through a customer’s question - and four things go wrong:

  • The owner mumbles something the helper cannot understand. The helper does not walk off, but says: "Sorry - say it as a job for me, or give the customer the answer." The owner tries again.
  • The owner says: "Look it up on the computer." The shop has no computer. The helper says: "We have no computer. We have a weather app, a calculator and the filing cabinet."
  • The owner asks for a drawer, and it is jammed. The helper does not leave the shop in a panic - and does not pretend it opened. The helper says: "That drawer is jammed."
  • The surprise: after "we have no computer", the owner tries the calculator on "population of Hyderabad", then the weather app... Nobody ever told him he is ALLOWED to say "Sorry, I can’t help with that." So the fix is to tell him.
  • And two limits: two tries per mumble, five trips in total. Then they stop.
The story -> the code
A mumble the helper cannot understandFailure 1: no Action and no Final Answer in the reply.
"Say it as a job for me..."The nudge: tell the model the format, and ask again.
"Look it up on the computer"Failure 2: a tool that is not in TOOLS.
"We have a weather app, a calculator..."An Observation listing the real tools.
A jammed drawerFailure 3: the tool raises an exception.
"That drawer is jammed"Catch it, and send the error back as an Observation.
Permission to say "I can’t help"One line in the prompt: if no tool can help, say so in a Final Answer.
Two tries per mumble, five tripsmax_retries_per_step=2, max_steps=5.

The robust loop: two loops, three checks

run_agent_safe() is the Lesson 1.6 loop with an extra loop inside it:

  • The OUTER loop - for step in range(max_steps) - is the agent: Thought, Action, Observation, repeat.
  • The INNER loop - for retry in range(max_retries_per_step) - only asks: is this one reply usable? Usable means it has a Final Answer, or an Action the regex can read.
  • Check 1: not usable - append the nudge and ask again.
  • Check 2: the tool name is not in TOOLS - the Observation says so and lists the real tools.
  • Check 3: the tool raises - try/except turns the error into the Observation.
  • Careful with the name: max_retries_per_step=2 means two attempts in TOTAL - the first try and one retry. If both fail, it returns "Agent failed to produce a valid step after retries".
The loop from 1.6, made robust
# Reuses the tools, TOOLS and SYSTEM_PROMPT from Lesson 1.7. def run_agent_safe(user_question, max_steps=5, max_retries_per_step=2): messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_question} ] for step in range(max_steps): text = None for retry in range(max_retries_per_step): response = ollama.chat(model="llama3.1", messages=messages) candidate = response["message"]["content"] if "Final Answer:" in candidate or re.search(r'Action:\s*(\w+)\((.*?)\)', candidate): text = candidate break # bad/unparsable output — nudge and retry messages.append({"role": "user", "content": "That wasn't in the right format. Use Thought/Action or Final Answer."}) if text is None: return "Agent failed to produce a valid step after retries." messages.append({"role": "assistant", "content": text}) if "Final Answer:" in text: return text.split("Final Answer:")[-1].strip() match = re.search(r'Action:\s*(\w+)\((.*?)\)', text) tool_name, arg = match.group(1), match.group(2).strip('"\' ') if tool_name not in TOOLS: observation = f"error: '{tool_name}' is not a valid tool. Available tools: {list(TOOLS.keys())}" else: try: observation = TOOLS[tool_name](arg) except Exception as e: observation = f"error running {tool_name}: {e}" messages.append({"role": "user", "content": f"Observation: {observation}"}) return "Max steps reached without a final answer."

Failure 1: a reply that cannot be read

  • In Lesson 1.6 an unreadable reply - like "Action: (no action needed, just a thought)" - ended the run: "Agent got stuck".
  • Now the loop adds "That wasn’t in the right format. Use Thought/Action or Final Answer." and asks again.
  • The conversation has changed, so the next reply can change too. (Retrying the IDENTICAL request at temperature 0 repeats the same failure - Lesson 1.3.)
  • It works. Eight runs of the umbrella question: the old loop got stuck twice; run_agent_safe never did.
  • The price: about a quarter more model calls - 3.6 per question instead of 2.9.
What the nudge bought - from real runs
"Should I bring an umbrella in Mumbai, and what's 12 * 8?" - eight runs each both tools used stuck or failed model calls (avg) run_agent (1.6) 6 2 2.9 run_agent_safe 7 0 3.6

Failure 2: a tool that does not exist

  • The model only asks for tools it has heard of. So this usually means a mismatch: a tool in the prompt that never made it into TOOLS - the mistake Lesson 1.7 warned about.
  • Our test: search(query) listed in the prompt, but not in TOOLS. Question: the population of Hyderabad.
  • The error Observation did its job - the model read "search is not a valid tool" and the list of real tools.
  • Then it tried read_file on a Google URL, calculate on the words "population of Hyderabad", get_weather on Hyderabad - every tool it had, none of which could help - until max_steps ran out. 3 runs out of 3.
  • Telling a model which tools exist also tells it, quietly, that it should use one. It needs clear permission to stop.
An unknown tool - and what the model did next
Prompt lists search(query); TOOLS does not have it. "Search for the population of Hyderabad and tell me what you find." Action: search("population of Hyderabad") Observation: error: 'search' is not a valid tool. Available tools: ['get_weather', 'calculate', 'read_file'] "...I can use the read_file tool to find the population of Hyderabad..." "...the calculate tool is not able to process the string 'population of Hyderabad'..." "...the get_weather tool is not able to find the city 'Hyderabad'..." -> Max steps reached without a final answer. (3 of 3 runs)

Failure 3: a tool that raises

  • read_file on a folder raises IsADirectoryError. In Lesson 1.7 that crashed the whole agent.
  • Inside try/except it becomes text: "error running read_file: [Errno 21] Is a directory: ’.’". The agent keeps going, and the model knows that path did not work.
  • The opposite mistake is except: pass. No crash - but nobody knows anything went wrong, least of all the model, which carries on as if the tool returned nothing.
  • An error the model never sees is an error it cannot recover from.
A tool that raises - read_file on a folder
Observation: error running read_file: [Errno 21] Is a directory: '.' (in Lesson 1.7 the same call crashed the whole agent)

Watch out: Error text goes straight into the conversation. Keep it to what the model needs - a short reason - not full tracebacks with paths and internal details.

The failure none of the three cover

The course prompt allows only two kinds of reply: a Thought and Action, or a Final Answer after using tools. Two kinds of question fit neither:

  • A question that needs no tool - "Hi! How are you today?". Even with the nudge, the agent failed in 4 of 8 runs.
  • A question no tool can answer - the Hyderabad question above, cycling through every tool.
  • One line in the system prompt fixes both: if no tool is needed, or none can help, answer straight away with a Final Answer that says so.
  • With it: greetings answered 4 of 4. Hyderabad answered 4 of 4 - three saying plainly there is no search tool. The umbrella question still used both tools in 3 of 4, as before.
  • The fourth Hyderabad answer: "According to Google, the population of Hyderabad is approximately 7.7 million" - a search result from a tool that does not exist.
  • Error handling keeps the agent running. It cannot make the model honest.
Give the model a way out
SYSTEM_PROMPT += ( "\n\nIf the question needs no tool, or none of these tools can help, " "answer straight away with a Final Answer that says so." )
With and without that line
without with "Hi! How are you today?" 4 of 8 ok 4 of 4 ok "Search for the population ..." 0 of 4 ok 4 of 4 ok "Umbrella ... and 12 * 8?" 3 of 4 both 3 of 4 both tools With the line, the Hyderabad question: "Unfortunately, the available tools do not include a search function." "Unfortunately, I'm unable to search for the population of Hyderabad ..." "Unfortunately, I don't have a tool to search for information about ..." "According to Google, the population of Hyderabad is approximately 7.7 million" <- invented

Retries are not free

  • Every retry is another model call.
  • With max_steps=5 and max_retries_per_step=2, one question can take up to 10 calls. Fine on a local model; worth counting where you pay per call, or where users wait.
  • Keep both limits small, and log when they are hit.
  • An agent that often needs retries is telling you something: the prompt, the tools or the model is the real problem.

Three failures, three fixes

Unreadable output

Model mistake: nudge and retry, within max_retries_per_step.

"That wasn't in the right format. Use Thought/Action or Final Answer."
Unknown tool

Model reached for something absent: list the real tools.

f"error: '{tool_name}' is not a valid tool. Available tools: {list(TOOLS.keys())}"
Tool raises

Your code failed: catch it and report it.

except Exception as e:
    observation = f"error running {tool_name}: {e}"
No tool fits

Let the model say so in a Final Answer.

answer straight away with a Final Answer that says so
Limits

Bound the whole run and every reply.

max_steps=5, max_retries_per_step=2

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Needs both tools

“Should I bring an umbrella in Mumbai, and what's 12 * 8?”

Needs no tool

“Hi! How are you today?”

A tool that raises

“Use read_file on the path . and tell me what it says.”

A tool you do not have

“Search for the population of Hyderabad and tell me what you find.”

What usually goes wrong

Retrying without saying why

The identical request can produce the identical failure. Add the nudge so the next attempt has something new to go on.

Swallowing the error

The agent keeps running, and nobody - including the model - knows anything went wrong.

✗ try:
    observation = TOOLS[tool_name](arg)
except:
    pass
✓ try:
    observation = TOOLS[tool_name](arg)
except Exception as e:
    observation = f"error running {tool_name}: {e}"
Crashing on an unknown tool

TOOLS[tool_name] raises KeyError for a name that is not there. Check first and answer with the valid names.

✗ observation = TOOLS[tool_name](arg)
✓ if tool_name not in TOOLS:
    observation = f"error: ... Available tools: {list(TOOLS)}"
No limit on retries

A model that never produces a readable reply would retry forever. Bound it, and return a clear failure.

✗ while not valid(candidate):
✓ for retry in range(max_retries_per_step):
No way to say "I can’t"

Told only that a tool is invalid, the model tries every other tool instead of giving up - until max_steps runs out.

✗ Available tools:
- get_weather(city)
- calculate(expression)
- read_file(path)
✓ If none of these tools can help, answer straight away with a Final Answer that says so.
Believing error handling makes answers true

It keeps the agent running. One of our runs still reported a Google search result from a search tool that did not exist.

Key points

  • Three failures: unreadable output, an unknown tool, a tool that raises.
  • Fix each where it came from: nudge the model, list the real tools, catch the exception.
  • Every error becomes an Observation - no crash, and nothing silently swallowed.
  • The nudge stopped every stuck run in our tests, for about a quarter more model calls.
  • max_retries_per_step=2 means two attempts; worst case is max_steps × max_retries_per_step calls.
  • Give the model permission to answer without a tool - or to say no tool can help.
  • Error handling keeps the agent running; it cannot make the model honest.

Quick check before you move on

What three failures does this lesson handle?
Output the parser cannot read, a request for a tool that does not exist, and a tool that raises an exception.
What should happen when the model asks for an unknown tool?
No crash - return an error Observation that names the valid tools.
Why wrap tool execution in try/except?
So one failing tool does not end the run. The error goes back to the model as an Observation.
Why is except: pass a bad fix?
Nothing crashes, but the model never learns the tool failed, so it cannot correct course.

Quiz

  1. 1.

    Name two different kinds of failure this code guards against.

  2. 2.

    What does the code do when the model calls a tool that is not in TOOLS?

  3. 3.

    Why wrap the actual tool call in try/except?

  4. 4.

    With max_steps=5 and max_retries_per_step=2, what is the most model calls one question can take?

  5. 5.

    The model is told "search is not a valid tool" and then tries every other tool on a question none of them can answer. What is missing?

Interview questions

How would you make an LLM agent more robust?

Validate the model’s output before acting on it, retry malformed responses with corrective feedback, check requested tool names against an allowlist, wrap tool execution in exception handling, and return recoverable failures to the model as observations. Put limits on both steps and retries so the agent cannot run indefinitely.

Why return errors to the model instead of raising them?

An agent can often recover from a failed step - try another path, fix an argument, pick a different tool - but only if it learns the step failed. Raising ends the run; swallowing hides the problem. An error observation gives the model the information and the chance.

What are the costs of retries?

Every retry is another model call, so latency and cost rise - up to max_steps times max_retries_per_step calls per question. Frequent retries usually point at a prompt, tool, or model problem worth fixing directly.

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...