Introduction
In our last lesson, we implemented the ReAct pattern, giving our agent an explicit Thought -> Action -> Observation cycle. This was a significant step, as it made the agent's reasoning transparent and auditable. However, our implementation made a critical, simplifying assumption: that every tool action succeeds perfectly. In any real-world system, this "happy path" is the exception, not the rule. APIs time out, files are not found, and parameters are malformed.
This lesson confronts that reality. We will focus on making our agent resilient by teaching it to handle failure. You will learn how to catch tool execution errors and, crucially, how to propagate those errors back to the LLM as observations. This enables the agent to perform in-loop recovery: it can see that its action failed, reason about the cause, and re-plan its next move. This principle of treating failures as signals rather than catastrophic events is fundamental to building the robust, production-grade systems you aim to architect.
The Frailty of Agents and the Necessity of Recovery
An agent that collapses at the first sign of trouble is little more than a demo. Production-grade reliability, a concept you're deeply familiar with from your work in distributed systems, demands that we anticipate and manage failure. In agentic systems, failures can be particularly insidious.
5 Problems Getting LLM Agents into Production
To frame the problem, let's start with this discussion on the challenges of getting LLM agents into production.
Watch the first two points the speaker makes: Reliability: The speaker identifies reliability as the number one problem, noting that most agents are far from the "five nines" expected of production services. Tools: Here, the discussion focuses on how failing tools contribute to unreliability. Pay close attention to the final point made in this segment: the importance of a tool telling the LLM it has failed in a "beneficial way" to avoid endless loops.
The video highlights a critical insight: failure isn't just something to be avoided; it's something to be managed and communicated. When a tool fails, it's not enough for the system to crash. The agent itself needs to be informed why the tool failed so it can adjust its strategy. This is the essence of in-loop recovery.
The Recovery Mechanism: Errors as Observations
The elegance of the ReAct pattern is that we don't need a complex new mechanism to handle errors. We can leverage the existing Observation step.
The core idea is this:
- If a tool executes successfully, the
Observationis the result of that tool. - If a tool execution throws an error, the
Observationis a message describing that error.
By feeding the error back into the loop, we make the LLM aware of the failure. It sees its previous Thought and Action, followed by an Observation that says "Error: something went wrong." This gives the model all the context it needs to generate a new Thought, such as: "My last attempt to read the file failed. The error says 'File Not Found'. I must have used the wrong filename. I will try again with the correct name."
However, for this to work, the error message itself must be useful to the model. A raw Python stack trace is verbose and noisy, often confusing the LLM more than it helps. The key is to provide structured, concise, and actionable error messages.
Building Your Own Claude Code from Scratch - Designing with AI
This article, while focused on a coding agent, contains a universally applicable principle for tool design.
Read the short section under the heading design patterns for coding agent tools. The author makes a crucial point about structured errors over stack traces. Focus on the paragraph that begins "Structured errors over stack traces." This is precisely the principle we will implement.
Implementation: Building a Resilient Agent Loop
Let's modify the agent loop we designed in the previous lesson. The changes are concentrated in two areas: the tool execution logic and the system prompt.
1. Modifying the Tool Executor
Our current logic for running a tool is a simple function call. To handle errors, we will wrap this call in a try...except block.
Let's revisit the agent_loop function from the video "Create a ReAct Agent from Scratch" that we analyzed in the last lesson. The logic for executing a tool was roughly result_from_tool = eval(f"{chosen_tool}('{argument}')"). We will make this robust.
# Recall the loop structure from our previous lesson's resources
# (e.g., Alejandro AO's video, section starting at 00:45:04)
# ... inside the loop, after parsing the action ...
if chosen_tool in tools:
try:
# Execute the tool function
tool_function = tools[chosen_tool]
tool_output = await tool_function(argument) # Assuming async tools
# Format a successful observation
next_prompt = f"Observation: {tool_output}"
except Exception as e:
# Catch ANY exception during tool execution
print(f"Tool '{chosen_tool}' failed with error: {e}")
# Format an error observation
# This is the crucial step: we are *telling* the LLM about the error.
next_prompt = f"Observation: Error: {e}"
else:
# Handle the case where the LLM hallucinates a non-existent tool
next_prompt = f"Observation: Error: Tool '{chosen_tool}' not found."
# The loop then continues, feeding `next_prompt` back to the agent.
This simple try...except block is the core of the implementation. Instead of crashing the loop, any exception is caught and transformed into an Observation that the LLM can understand and act upon.
2. Updating the System Prompt
The LLM won't know how to handle these new error observations unless we instruct it to. We must update our system prompt to include guidance on error recovery.
An addition to our previous ReAct prompt could look like this:
... Your available actions are: ...If an Action results in an error, the Observation will begin with 'Error:'. You must use the information in the error message to diagnose the problem and correct your plan in your next Thought. If a tool is not found, try to use a different tool.
You could even include a "few-shot" example of a failure and recovery in the prompt to make the desired behavior even more explicit.
A Worked Example: In-Loop Recovery
Let's trace an execution where the agent makes a mistake and recovers.
Goal: Calculate the sum of the populations of Mars and Jupiter.
Tools: get_planet_population(planet_name) and calculate(expression).
Iteration 1:
- User Query: "What is the sum of the populations of Mars and Jupiter?"
- LLM Output (Thought + Action):
Thought: I need to find the population of Mars and Jupiter and then add them. First, I'll get the population of Mars.\nAction: get_planet_population[Mars] - Tool Execution: The
get_planet_populationtool is called. However, it's designed for planets with known populations, and Mars is uninhabited (or let's assume our tool has no data for it). The tool raises an error:ValueError("No population data available for planet 'Mars'"). - Observation (fed back to LLM):
Observation: Error: No population data available for planet 'Mars'
Iteration 2:
- Prompt History now includes:
... Action: get_planet_population[Mars]\nObservation: Error: No population data available for planet 'Mars' - LLM Output (Thought + Action):
Thought: The action to get the population of Mars failed because there is no data. This makes sense as Mars is not populated. The question might be a trick question or based on a misunderstanding. I will state that Mars has a population of 0 and proceed with getting Jupiter's population.\nAction: get_planet_population[Jupiter] - Tool Execution: The tool successfully returns Jupiter's population (which is also 0, but the tool call succeeds).
- Observation:
Observation: 0
Iteration 3:
- Prompt History now includes:
... Action: get_planet_population[Jupiter]\nObservation: 0 - LLM Output (Thought + Action):
Thought: I have determined that the population of Mars is 0 and the population of Jupiter is 0. I can now calculate the sum.\nAction: calculate[0 + 0] - Tool Execution: The
calculatetool returns0. - Observation:
Observation: 0
Iteration 4:
- LLM Output (Final Answer):
Thought: I have all the information. The sum of the populations is 0. I will now provide the final answer.\nAction: finish[The sum of the populations of Mars and Jupiter is 0.]
In this example, the agent didn't crash. The error became a part of its reasoning process, allowing it to adapt its plan and still reach a logical conclusion.
A Hierarchy of Recovery Strategies
What we have implemented is a form of re-planning. This is a powerful technique, but it's just one of several recovery strategies. As you design more complex systems, it's useful to think about a hierarchy of responses to failure.
Error Recovery and Graceful Degradation in AI Agents - Engineering Notes
This article provides an excellent framework for thinking about agent resiliency from a systems perspective.
First, read the introduction to understand the different levels of error recovery. Next, study the section on Algorithms & Patterns. Pay special attention to the "Retry Hierarchy" (Level 0 to Level 4). This gives you a structured vocabulary for different recovery actions. Finally, review the Key Takeaways at the end. These are excellent guiding principles for building production-ready agents.
The article's "Retry Hierarchy" is a valuable mental model. Our current implementation primarily enables Level 3: Replan, where the agent abandons its immediate failed action and generates a new one based on the error. In future lessons, particularly in Module 9 on reliability, we will explore implementing other levels, such as automatic retries for transient errors (Level 0) and escalating to a human (Level 4).
Conclusion
Today, we've made our agent significantly more robust by transforming it from a "happy path" optimist into a pragmatic realist. It now understands that failure is a possibility and, more importantly, knows how to learn from it.
Here are your key takeaways from this lesson:
- Errors are signals, not stoppers: In a ReAct loop, tool failures should not crash the system. They should be treated as observations that inform the agent's next thought.
- Implementation is straightforward: Wrapping tool calls in a
try...exceptblock and formatting the exception as anObservationstring is the core mechanism. - Actionable error messages are critical: The LLM can only recover if the error message is clear and concise. Avoid dumping raw stack traces into the context.
- Prompting guides recovery: The system prompt must instruct the agent on how to interpret and react to error observations.
- Recovery is a spectrum: Our re-planning mechanism is one of several strategies in a hierarchy of recovery patterns, providing a foundation for more advanced reliability engineering later.
Our agent can now think, act, and recover from its own mistakes. But how does it know when its work is truly done? An agent that can recover from errors might also get stuck in a recovery loop. In the next lesson, we will address this by implementing configurable stopping conditions, giving us control over when to terminate the agent's execution loop based on iteration counts, token limits, or explicit goal completion signals.