Hello! Welcome back to your AI engineering journey.
In the last lesson, you built a complete, end-to-end Plan-and-Execute agent. This agent can take a complex request, create a multi-step plan, and execute each step in sequence. However, our agent is currently quite optimistic—it assumes every step will succeed and that the initial plan is perfect. The real world is messy, and robust agents need to be able to handle unexpected problems.
Today, we'll address this by teaching our agent to be more resilient. You will learn how to implement dynamic re-planning, enabling your agent to handle execution errors and adapt when the situation changes. This is a critical step toward building more autonomous and reliable AI systems.

Why Re-planning is Essential: Understanding Failure Modes
Before we can build a more resilient agent, we need to understand the kinds of problems it might encounter. In traditional software, errors are often deterministic. In AI agents, especially those using LLMs and external tools, failures can be more complex and unpredictable.
To get a structured overview of what can go wrong, let's explore the common failure modes in agentic systems.
Error Recovery and Fallback Strategies in AI Agent Development
This article from GoCodeo provides an excellent breakdown of the common failure modes in agent systems, which helps explain why simple error handling isn't enough.
Read the sections 'Why Robust Error Handling is Critical in AI Agent Development' and 'Key Categories of Errors in AI Agent Systems'. As you read, focus on understanding the difference between execution-level, semantic, and state errors.
As you've just read, our agent can fail in several ways:
- Execution-Level Errors: A tool call fails. For example, a web search API key is invalid, or a database is unreachable. These are often caught as exceptions in your code.
- Semantic Errors: The LLM generates a syntactically correct but logically flawed action. For example, it calls the
web_searchtool with a nonsensical query that returns no useful results. - State Errors: The agent's internal belief about the world becomes desynchronized from reality. It might assume a file was created by a previous step, but the action failed silently.
A simple try...except block can handle some execution errors, but it can't fix a flawed plan. If the agent's initial strategy is wrong, it needs the ability to stop, reassess, and create a new plan. This is the core idea of dynamic re-planning.
The Re-planner Pattern
To implement this, we'll introduce a new component to our agent's architecture: a Replanner.
The new workflow will look like this:
- Plan: Create the initial plan.
- Execute: Attempt to execute the current step.
- Evaluate: After execution, check the outcome.
- If successful, continue to the next step.
- If there's an error or the result is not useful, trigger the replanner.
- Re-plan: Create a new plan based on the original goal, the steps already taken, and the error that occurred. Then, go back to the Execute step with the new plan.
The LangChain team has explored several architectures that incorporate this idea. Let's watch a short clip that introduces the concept.
The following video from the LangChain team discusses advanced planning agents. This first clip introduces the 'replanner' as a powerful, optional component in the Plan-and-Execute model.
Watch from 02:32 to 03:35. Pay attention to how the agent workflow is broken down into Planner, Executor, and an optional Replanner, which introduces the looping logic we need.
This re-planning loop is what makes an agent truly adaptive. It can recover from tool failures, dead ends, and bad assumptions, much like a human would.

Implementing Dynamic Re-planning in LangGraph
Now, let's get practical. We'll modify the Plan-and-Execute agent you built in the previous lesson. The key will be to replace our simple should_continue conditional edge with a more intelligent node that can evaluate outcomes and trigger a replan.
LangGraph is perfectly suited for these kinds of cyclical, state-driven workflows. The documentation provides a clear strategy for handling errors that the LLM can recover from.
Thinking in LangGraph - Docs by LangChain
The LangGraph documentation explains how to think about and implement different error handling strategies. We'll focus on the pattern for handling 'LLM-recoverable errors'.
Read the section 'Handle errors appropriately'. The key strategy for us is under 'LLM-recoverable errors': store the error in the state and loop back. The code snippet showing how to catch a ToolError and update the state is the exact pattern we will implement.
Modifying the Agent for Re-planning
We'll make three main changes to our previous code:
- Update
AgentState: We'll add a field to hold error messages, which will serve as the input for our replanner. - Modify the
executornode: We'll wrap the tool execution in atry...exceptblock. If an error occurs, we'll catch it and store the error message in the state. - Create a
replannernode: This new node will be called when an error is detected. It will receive the context of the failure and generate a new plan. - Update the graph's logic: We'll add a new conditional edge to route the flow to the
replannerwhen an error is present in the state.
Here is the full, updated code. Pay close attention to the try...except block in execute_step, the new replanner node, and the updated decide_next_step conditional edge.
import os
import asyncio
from typing import List, TypedDict, Optional
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langgraph.graph import StateGraph, END
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain import hub
from langchain_community.tools.tavily_search import TavilySearchResults
# --- Environment Setup ---
# os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
# os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = "YOUR_LANGSMITH_API_KEY"
# --- 1. State and Plan/Step Definitions ---
class Step(BaseModel):
step_instruction: str = Field(..., description="The instruction for this step.")
class Plan(BaseModel):
steps: List[Step] = Field(..., description="The list of steps to execute.")
class StepOutput(TypedDict):
step: int
output: str
# UPDATED: AgentState now includes an error field for re-planning
class AgentState(TypedDict):
input: str
plan: Plan
past_steps: List[StepOutput]
current_step: int
response: str
error: Optional[str] # To store any error messages
# --- 2. Tool Definition ---
search_tool = TavilySearchResults(max_results=2)
search_tool.name = "web_search"
search_tool.description = "A tool for searching the web to find information."
tools = [search_tool]
# --- 3. Planner, Executor, and Replanner Agent Definitions ---
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
# Planner (from previous lesson)
planner_prompt = ChatPromptTemplate.from_template(
"You are an expert planner. Your job is to create a step-by-step plan to answer the user's request.\n"
"User's Request:\n{input}"
)
planner = planner_prompt | llm.with_structured_output(Plan)
# NEW: Replanner
replanner_prompt = ChatPromptTemplate.from_template(
"""You are an expert replanner. Your job is to create a new, improved plan to answer the user's request.
A previous plan failed because of the error below.
Original Request:
{input}
Previous Plan:
{plan}
Steps taken so far:
{past_steps}
Error that caused failure:
{error}
Based on this, create a new, robust plan to address the user's request. The plan should avoid the previous error."""
)
replanner = replanner_prompt | llm.with_structured_output(Plan)
# Executor (from previous lesson)
executor_prompt = hub.pull("hwchase17/openai-tools-agent")
executor_agent = create_tool_calling_agent(llm, tools, executor_prompt)
agent_executor = AgentExecutor(agent=executor_agent, tools=tools, verbose=True)
# Responder (from previous lesson)
responder_prompt = ChatPromptTemplate.from_template(
"You are an expert summarizer. Synthesize the results of a multi-step plan to answer the user's original request.\n"
"Original Request: {input}\n"
"Results of executed steps:\n{past_steps}\n\n"
"Synthesize these results into a final, comprehensive answer."
)
responder = responder_prompt | llm
# --- 4. Graph Node and Edge Functions ---
async def plan_step(state: AgentState):
print("---GENERATING PLAN---")
plan_result = await planner.ainvoke({"input": state["input"]})
print(f"Plan: {[s.step_instruction for s in plan_result.steps]}")
return {"plan": plan_result, "current_step": 0, "past_steps": [], "error": None}
# NEW: Node for re-planning
async def replan_step(state: AgentState):
print("---RE-PLANNING---")
past_steps_str = "\n".join([f"Step {s['step']}: {s['output']}" for s in state['past_steps']])
plan_str = "\n".join([f"Step {i+1}: {s.step_instruction}" for i, s in enumerate(state['plan'].steps)])
replan_result = await replanner.ainvoke({
"input": state["input"],
"plan": plan_str,
"past_steps": past_steps_str,
"error": state["error"]
})
print(f"New Plan: {[s.step_instruction for s in replan_result.steps]}")
# Reset the execution state for the new plan
return {"plan": replan_result, "current_step": 0, "past_steps": [], "error": None}
# UPDATED: Executor now handles errors
async def execute_step(state: AgentState):
step_index = state["current_step"]
step = state["plan"].steps[step_index]
print(f"\n---EXECUTING STEP {step_index + 1}---")
print(step.step_instruction)
try:
result = await agent_executor.ainvoke({"input": step.step_instruction, "chat_history": []})
output = StepOutput(step=step_index + 1, output=result["output"])
new_past_steps = state["past_steps"] + [output]
return {"past_steps": new_past_steps, "current_step": step_index + 1, "error": None}
except Exception as e:
# Catch the error and store it in the state
print(f"---ERROR IN STEP {step_index + 1}---")
print(str(e))
return {"error": str(e)}
async def generate_response(state: AgentState):
# Same as previous lesson
print("\n---GENERATING FINAL RESPONSE---")
past_steps_str = "\n".join([f"Step {s['step']}: {s['output']}" for s in state['past_steps']])
response = await responder.ainvoke({"input": state["input"], "past_steps": past_steps_str})
return {"response": response.content}
# UPDATED: Conditional edge is now more intelligent
def decide_next_step(state: AgentState):
# If there was an error, we replan
if state.get("error"):
return "replan"
# If we have finished all steps, we generate the final response
if state["current_step"] >= len(state["plan"].steps):
return "end"
# Otherwise, continue to the next step
else:
return "continue"
# --- 5. Assemble the Graph ---
workflow = StateGraph(AgentState)
workflow.add_node("planner", plan_step)
workflow.add_node("executor", execute_step)
workflow.add_node("replanner", replan_step)
workflow.add_node("responder", generate_response)
workflow.set_entry_point("planner")
# From planner, go to executor
workflow.add_edge("planner", "executor")
# After replanning, go to the executor
workflow.add_edge("replanner", "executor")
# After executing a step, decide what to do next
workflow.add_conditional_edges(
"executor",
decide_next_step,
{"continue": "executor", "replan": "replanner", "end": "responder"}
)
workflow.add_edge("responder", END)
app = workflow.compile()
# --- 6. Run the Agent ---
async def main():
# Let's craft a request that is likely to cause an error
# A non-existent tool name will cause a ToolException in the agent_executor
faulty_request = "Research the performance of NVIDIA's stock in 2023. Then, use the 'non_existent_tool' to analyze the data."
final_state = await app.ainvoke({"input": faulty_request})
print("\n\n---FINAL ANSWER---")
print(final_state['response'])
asyncio.run(main())
When you run this code with the faulty_request, you'll see a new behavior:
- The
plannercreates a plan that includes using thenon_existent_tool. - The
executortries to execute this step and fails, catching an exception. - The
decide_next_stepedge sees the error in the state and routes the flow to thereplanner. - The
replannersees the error and generates a new plan that avoids the mistake (e.g., by just using theweb_searchtool). - The new plan is then executed successfully, leading to a final answer.
This ability to self-correct is a hallmark of advanced agentic systems.
Test your understanding!
Our current replanner is triggered only by exceptions caught in the execute_step node.
What if a step succeeds but produces a useless result? For example, a web search for "key drivers of NVIDIA's growth in 2023" returns "Sorry, no results found.". The step didn't error, but the plan can't proceed without that information.
How would you modify the agent to handle this kind of "semantic failure"?
Show answer
You would need to add an "evaluation" step or enhance the execute_step logic. Here's one approach:
- Create an
evaluate_stepnode: This node would run afterexecute_step. - Define Evaluation Criteria: The node would use an LLM to check if the output from the last step is useful and sufficient for the next steps in the plan. The prompt might be:
"Given the plan and the previous step's output, is the output sufficient to proceed? Answer YES or NO." - Update
decide_next_step: This conditional edge would now start from theevaluate_stepnode. If the evaluation is "NO", it would populate theerrorfield in the state (e.g.,"Error: The output of the last step was insufficient.") and route to thereplanner.
This makes the agent even more robust, as it can now recover not just from hard crashes but also from logical dead ends. The data science agent shown in the video from Together AI (LINK) uses this iterative "execute-and-evaluate" loop to perform complex data analysis.
Conclusion
Congratulations! You have significantly upgraded your agent's intelligence. It can now not only plan and execute but also recover from failures and adapt its strategy on the fly.
Key Takeaways:
- Dynamic Re-planning is crucial for building robust agents that can operate in unpredictable environments.
- Failures can be categorized into execution, semantic, and state errors, each requiring different handling.
- In LangGraph, re-planning can be implemented by adding an
errorfield to the state, usingtry...exceptblocks in execution nodes, and creating areplannernode. - Conditional edges are the control mechanism that allows the graph to dynamically switch between execution and re-planning loops based on the agent's state.
What's Next?
You have now mastered the core mechanics of building a single, sophisticated agent. In our next module, we will explore a powerful new paradigm: multi-agent systems. You will learn how to build systems where multiple specialized agents collaborate, delegate tasks, and work together to solve even more complex problems.