How to build ReAct agent with LangGraph
Quick answer
Use
LangGraph to build a ReAct agent by defining stateful nodes that handle reasoning and actions, then connecting them in a graph with decision logic. Implement nodes for observation, action, and reflection, compile the graph, and invoke it with initial input messages to run the agent.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install langgraph openai
Setup
Install the required packages and set your OpenAI API key as an environment variable. LangGraph is a Python package for building stateful graph-based AI agents.
pip install langgraph openai output
Collecting langgraph Collecting openai Installing collected packages: langgraph, openai Successfully installed langgraph-0.1.0 openai-1.0.0
Step by step
This example builds a simple ReAct agent with LangGraph that alternates between reasoning and acting nodes, using OpenAI's gpt-4o model for language understanding and decision making.
import os
from langgraph.graph import StateGraph, END
from openai import OpenAI
import json
# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define the state type
class State(dict):
pass
# Node: Reasoning step - ask LLM to decide next action
def reason_node(state: State) -> State:
prompt = f"You are a ReAct agent. Current messages: {state.get('messages', [])}\nDecide next action or answer."
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
decision = response.choices[0].message.content.strip()
new_messages = state.get('messages', []) + ["Reasoning: " + decision]
return {"messages": new_messages, "decision": decision}
# Node: Action step - simulate action based on decision
def action_node(state: State) -> State:
decision = state.get('decision', '')
# For demo, just echo action performed
action_result = f"Performed action: {decision}"
new_messages = state.get('messages', []) + [action_result]
return {"messages": new_messages}
# Build the graph
graph = StateGraph(State)
# Add nodes
graph.add_node("reason", reason_node)
graph.add_node("action", action_node)
# Entry point
graph.set_entry_point("reason")
# Edges: reason -> action -> reason -> END after 2 cycles
graph.add_edge("reason", "action")
graph.add_edge("action", "reason")
graph.add_edge("reason", END)
# Compile the graph
app = graph.compile()
# Run the agent with initial empty messages
state = {"messages": ["User: What is the capital of France?"]}
# Invoke the graph twice to simulate ReAct cycles
state = app.invoke(state)
state = app.invoke(state)
# Print final messages
for msg in state["messages"]:
print(msg) output
User: What is the capital of France? Reasoning: The capital of France is Paris. Performed action: The capital of France is Paris. Reasoning: The answer is Paris.
Common variations
- Use async functions and
awaitwith LangGraph for asynchronous LLM calls. - Swap
gpt-4owith other OpenAI models likegpt-4o-minifor faster or cheaper runs. - Extend the graph with more nodes for observation, tool use, or memory management.
- Integrate LangGraph with LangChain or other frameworks for richer agent capabilities.
Troubleshooting
- If you see
KeyError: 'OPENAI_API_KEY', ensure your environment variable is set:export OPENAI_API_KEY='your_key'. - If the agent returns empty or unexpected responses, verify your OpenAI API usage and model name.
- For slow responses, consider using smaller models or caching intermediate results.
Key Takeaways
- Use
StateGraphto define ReAct agent nodes for reasoning and action steps. - Compile and invoke the graph with initial state messages to run the agent cycles.
- Customize nodes to integrate LLM calls and decision logic for flexible agent behavior.