Building Your First ReAct Agent with LangGraph
AI Agents
ReAct Agent with LangGraph â From Zero to Production
LangGraph models agent workflows as cyclic graphs with nodes (functions) and edges (conditional routing). This tutorial builds a complete ReAct agent with state persistence, tool orchestration, and mathematical foundations.
- Graph-Based Workflows â Model agent logic as state machines with loops and branches
- Persistent State â Resume conversations across sessions with checkpointing
- Tool Integration â Bind tools to LLMs with structured output parsing
- Production Ready â Streaming, error recovery, and cost tracking built in
ReAct Agent Architecture
What is a ReAct Agent?
ReAct (Reasoning + Acting) interleaves deliberation with action in large language models. Unlike pure chain-of-thought reasoning, a ReAct agent alternates between generating thoughts (reasoning about what to do next) and actions (calling tools to get real information). This loop continues until the agent has enough information to produce a final answer.
Why LangGraph?
LangGraph extends LangChain by modeling agent workflows as cyclic graphs. Unlike linear chains, LangGraph supports loops, conditional branching, and persistent state â essential for real-world agent applications.
| Feature | LangChain AgentExecutor | LangGraph |
|---|---|---|
| Loop support | Limited | Full cyclic graphs |
| State management | Memory objects | TypedDict with checkpointing |
| Human-in-the-loop | Difficult | Built-in pause/resume |
| Streaming | Basic | Token-by-token |
| Persistence | Manual | Automatic checkpointing |
Step 1: Environment Setup
Install Dependencies
pip install langchain langchain-openai langgraph langchain-core pydantic tiktoken
export OPENAI_API_KEY="sk-your-key-here"
Verify Installation
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
llm = ChatOpenAI(model="gpt-4o")
print(llm.invoke("Say hello!").content)
# "Hello! How can I help you today?"
Step 2: Define Agent State
LangGraph agents revolve around a State object that flows through the graph. Each node reads from and writes to this state.
from typing import TypedDict, Annotated, List
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
from langgraph.graph.message import add_messages
class AgentState(TypedDict):
"""State that flows through the LangGraph agent."""
messages: Annotated[List[BaseMessage], add_messages]
next_action: str
iteration: int
total_cost: float
tool_results: List[dict]
Step 3: Define Tools
LangChain's @tool decorator creates structured tool definitions that the LLM can call.
from langchain_core.tools import tool
@tool
def web_search(query: str) -> str:
"""Search the web for current information about a topic.
Args:
query: The search query string
Returns:
Search results as a formatted string
"""
# In production, use actual search API (Tavily, Serper, etc.)
mock_results = {
"nyc weather": "New York City: 72°F, sunny, humidity 45%, wind 8mph NW",
"london weather": "London: 58°F, overcast, humidity 72%, wind 12mph W",
"tokyo weather": "Tokyo: 68°F, partly cloudy, humidity 60%, wind 5mph SE",
}
query_lower = query.lower()
for key, value in mock_results.items():
if key in query_lower:
return value
return f"Weather data for '{query}': 70°F, clear skies"
@tool
def calculator(expression: str) -> str:
"""Evaluate a mathematical expression safely.
Args:
expression: Mathematical expression to evaluate (e.g., "85 * 0.15")
Returns:
The calculated result as a string
"""
try:
result = eval(expression, {"__builtins__": {}}, {
"abs": abs, "round": round, "min": min, "max": max,
"sum": sum, "len": len, "int": int, "float": float,
})
return str(result)
except ZeroDivisionError:
return "Error: Division by zero"
except Exception as e:
return f"Calculation error: {str(e)}"
@tool
def get_current_time() -> str:
"""Get the current date and time.
Returns:
Current timestamp as a formatted string
"""
from datetime import datetime
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Step 4: Build the LangGraph Agent
Create the Graph
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
# Bind tools to LLM
llm = ChatOpenAI(model="gpt-4o", temperature=0)
llm_with_tools = llm.bind_tools([web_search, calculator, get_current_time])
# Define agent node
def agent_node(state: AgentState):
"""Call the LLM with current messages."""
response = llm_with_tools.invoke(state["messages"])
return {
"messages": [response],
"iteration": state.get("iteration", 0) + 1,
}
# Define tool node
tool_node = ToolNode([web_search, calculator, get_current_time])
# Define routing logic
def should_continue(state: AgentState):
"""Decide: use tools or end."""
last_message = state["messages"][-1]
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
return "tools"
return END
# Build the graph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)
# Add edges
workflow.set_entry_point("agent")
workflow.add_conditional_edges("agent", should_continue, {"tools": "tools", END: END})
workflow.add_edge("tools", "agent") # After tools, go back to agent
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions