Hello! Welcome to the next lesson in your journey to becoming an AI Engineer.
In our last lesson, you successfully built the "brain" of a Plan-and-Execute agent: the planner. You learned how to use LangGraph and a powerful LLM to decompose a complex user request into a structured, multi-step plan. We ended with a generated plan, but no way to act on it.
Today, we build the "hands." This lesson is all about the "Execute" part of the architecture. You will learn how to build an agent that takes a pre-defined plan and systematically carries out each step, using tools to interact with the world and gather information. By the end, you'll have a complete, functioning Plan-and-Execute agent that can tackle complex tasks from start to finish.
The Plan-and-Execute Architecture Revisited
Let's briefly revisit the core concept. The Plan-and-Execute pattern separates the strategic thinking from the tactical action.
- Planner: Creates a high-level sequence of steps.
- Executor: Carries out each step in the sequence.
This is a powerful pattern that brings several advantages, as noted in the LangChain blog post on the topic.
To understand the benefits of the Plan-and-Execute model we're building, read this introductory section from the LangChain blog post 'Plan-and-Execute Agents'.
Read the first few sections of the blog post, starting from the introduction down to the 'Background' section. Focus on the three key benefits mentioned: speed, cost savings, and performance.
Our goal is to build the second component, the Executor, and integrate it with the Planner you built previously. The Executor's job is to loop through the plan, executing each step one by one and passing the results along.

Building the Executor with LangGraph
We will continue using LangGraph to expand the workflow from our previous lesson. The core idea is to create a loop: after the planner runs, we enter a cycle where an executor node runs a step, and then a conditional edge decides whether to continue to the next step or finish.
Step 1: Expanding the Agent State
First, we need to enhance our AgentState to keep track of the execution progress. We need to know which step we're on and store the results of the steps that have been completed.
Let's modify the AgentState from the last lesson.
from typing import List, TypedDict
from langchain_core.pydantic_v1 import BaseModel, Field
# --- From Previous Lesson ---
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.")
# -----------------------------
# NEW: Structure to hold the output of a completed step
class StepOutput(TypedDict):
step: int
output: str
# UPDATED: AgentState now includes execution tracking
class AgentState(TypedDict):
input: str
plan: Plan
past_steps: List[StepOutput] # A list to store the results of completed steps
current_step: int # The index of the next step to execute
This updated state allows our graph to maintain context throughout the execution loop. past_steps acts as a memory of what's been done, and current_step is the pointer to what's next.
Step 2: Creating Tools for the Executor
An executor is only as useful as the tools it can wield. For this example, we'll give our agent a simple but powerful tool: a web search capability. We'll use LangChain's built-in TavilySearchResults wrapper for this.
If you don't have a Tavily API key, you can sign up for free on their website.
# Install the required library
pip install tavily-python
# Set your API key in your environment
# os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
Now, let's define our tool:
from langchain_community.tools.tavily_search import TavilySearchResults
# Initialize the search tool
search_tool = TavilySearchResults(max_results=2)
search_tool.name = "web_search" # Giving it a simple, clear name
search_tool.description = "A tool for searching the web to find information."
tools = [search_tool]
Step 3: Designing the Executor Agent
The executor's job is to take a single step's instruction (e.g., "Research NVIDIA's stock performance in 2023") and use the available tools to accomplish it. This sounds a lot like the ReAct agent we discussed in previous modules!
We can create a small, dedicated "executor agent" for this. LangChain provides a convenient create_tool_calling_agent function to build this kind of agent quickly.
from langchain import hub
from langchain.agents import create_tool_calling_agent
from langchain_openai import ChatOpenAI
# Get a pre-built prompt for a tool-calling agent
# This prompt instructs the LLM on how to use tools
executor_prompt = hub.pull("hwchase17/openai-tools-agent")
# Initialize a powerful LLM for the executor
# gpt-4-turbo is a good choice as it's skilled at tool use
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
# Create the agent runnable
executor_agent = create_tool_calling_agent(llm, tools, executor_prompt)
This executor_agent is now a self-contained component that can take an input (the step instruction) and orchestrate tool calls to get it done.
Step 4: Creating the Graph Nodes and Edges
Now we'll define the functions that will become the nodes in our LangGraph workflow.
A. The Executor Node
This node will execute a single step of the plan. It will use the AgentExecutor from LangChain, which wraps our executor_agent in a loop to handle the thought-action-observation cycle for a single step.
from langgraph.prebuilt import ToolExecutor
from langchain.agents import AgentExecutor
# The tool_executor is responsible for actually calling our tools (e.g., Tavily search)
tool_executor = ToolExecutor(tools)
# The agent_executor wraps our agent and tool_executor into a runnable loop
# This will handle the execution of a SINGLE step
agent_executor = AgentExecutor(agent=executor_agent, tools=tools, verbose=True)
async def execute_step(state: AgentState) -> AgentState:
step_index = state["current_step"]
plan = state["plan"]
step = plan.steps[step_index]
print(f"\n---EXECUTING STEP {step_index + 1}---")
print(step.step_instruction)
# Invoke the agent executor with the step instruction
result = await agent_executor.ainvoke({"input": step.step_instruction})
# Store the output
output = StepOutput(step=step_index + 1, output=result["output"])
# Update the state
new_past_steps = state["past_steps"] + [output]
return {"past_steps": new_past_steps, "current_step": step_index + 1}
B. The Responder Node
After all steps are executed, this final node will synthesize the results into a final answer for the user.
from langchain_core.prompts import ChatPromptTemplate
responder_prompt_template = """
You are an expert summarizer. Your job is to synthesize the results of a multi-step plan to answer the user's original request.
Original Request:
{input}
Here are the results of the executed steps:
{past_steps}
Synthesize these results into a final, comprehensive answer.
"""
responder_prompt = ChatPromptTemplate.from_template(responder_prompt_template)
responder = responder_prompt | llm
async def generate_response(state: AgentState) -> AgentState:
print("\n---GENERATING FINAL RESPONSE---")
# Format the past steps for the prompt
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}
C. The Conditional Edge
This function decides the next transition after a step is executed. Do we continue to the next step, or are we done?
def should_continue(state: AgentState) -> str:
if state["current_step"] >= len(state["plan"].steps):
return "end"
else:
return "continue"
Step 5: Assembling and Running the Full Graph
Now, let's put all the pieces together into a complete workflow. This code combines the planner from the last lesson with our new executor and responder.
To see a detailed example of a similarly complex, multi-step agent being built with LangGraph, you can explore this video.
Python Advanced AI Agent Tutorial - LangGraph, LangChain, Firecrawl & More!
The following video by Tech With Tim demonstrates building an advanced research agent using LangGraph. While we are building a more generic Plan-and-Execute agent, this video provides an excellent, in-depth look at defining a state, creating nodes for each step of a process, and connecting them into a controllable workflow.
Watch the section from 23:11 to 41:01. Pay close attention to how a StateGraph is used to define a workflow with distinct nodes like 'extract', 'research', and 'analyze'. This is the same principle we're applying to connect our 'planner', 'executor', and 'responder' nodes.
Here is the complete code to assemble and run our graph:
import os
import asyncio
from typing import List, TypedDict
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 langgraph.prebuilt import ToolExecutor
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
class AgentState(TypedDict):
input: str
plan: Plan
past_steps: List[StepOutput]
current_step: int
response: str # To store the final response
# --- 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 and Executor Agent Definitions ---
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
# Planner
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)
# Executor
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
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: {plan_result.steps}")
return {"plan": plan_result, "current_step": 0, "past_steps": []}
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)
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}
async def generate_response(state: AgentState):
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}
def should_continue(state: AgentState):
if state["current_step"] >= len(state["plan"].steps):
return "end"
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("responder", generate_response)
workflow.set_entry_point("planner")
workflow.add_edge("planner", "executor")
workflow.add_conditional_edges(
"executor",
should_continue,
{"continue": "executor", "end": "responder"}
)
workflow.add_edge("responder", END)
app = workflow.compile()
# --- 6. Run the Agent ---
async def main():
complex_request = "Research the performance of NVIDIA's stock in 2023, identify the key drivers for its growth, and write a short summary of the findings."
final_state = await app.ainvoke({"input": complex_request})
print("\n\n---FINAL ANSWER---")
print(final_state['response'])
asyncio.run(main())
When you run this script, you will see the entire Plan-and-Execute process unfold:
- The planner generates a series of steps.
- The executor invokes the
web_searchtool for each research-oriented step. - You'll see the verbose output from
AgentExecutorshowing the agent's "thoughts" and tool calls. - Finally, the responder synthesizes all the collected information into a coherent summary.
Test your understanding!
In our execute_step node, the agent uses an LLM to decide which tool to use based on the step's instruction. This is flexible but adds latency and cost.
Consider a plan where the steps are more explicit, like:Step 1: Use the 'web_search' tool with the query 'NVIDIA stock price January 1 2023'Step 2: Use the 'web_search' tool with the query 'NVIDIA stock price December 31 2023'
How could you modify the execute_step function to handle such explicit instructions without calling the agent_executor LLM?
Show answer
You could change the executor to be a simple Python function that parses the instruction instead of using an LLM.
def simple_execute_step(state: AgentState):
# ... get current step instruction ...
# Simple parsing logic
if "'web_search' tool" in step.step_instruction:
# Extract the query from the instruction string
query = # ... (use regex or string splitting to get the query)
# Directly call the tool
result = search_tool.invoke({"query": query})
# ... update state with result ...
else:
# Handle cases where the tool is not recognized
result = "Error: Could not parse tool from instruction."
# ...
This approach is less flexible but much faster and cheaper. It essentially treats the plan as a script written in a Domain-Specific Language (DSL). Architectures like ReWOO (Reasoning WithOut Observations) use a similar principle, where the planner generates tool calls with placeholders that the executor can fill in and run directly.
Conclusion
Excellent work! You have now built a complete, end-to-end Plan-and-Execute agent. You've successfully bridged the gap between high-level strategic planning and low-level tactical execution, a fundamental skill in building sophisticated AI agents.
Key Takeaways:
- The Executor component is responsible for carrying out the steps of a pre-defined plan.
- LangGraph's state management and conditional edges are perfectly suited for implementing the looping logic required by an executor.
- Each execution step can itself be a mini-agentic task, using a tool-calling agent to decide which action to take.
- Combining a planner, executor, and responder creates a robust and powerful agent architecture capable of handling complex, multi-step problems.
What's Next?
Our current agent is powerful, but it's also optimistic. It assumes every step will succeed and the initial plan is perfect. What happens if a tool call fails? Or if the information found in Step 2 makes Step 3 irrelevant?
In our next lesson, we will address this by learning how to implement dynamic re-planning, making our agent more resilient and intelligent in the face of errors and changing conditions.