🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Building Your First ReAct Agent with LangGraph

AI AgentsBuilding Your First AgentđŸŸĸ Free Lesson

Advertisement

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

LangGraph ReAct Agent ArchitectureUSER INPUT — Natural Language Query"What is the weather in NYC and calculate 15% tip on $85?"Agent Node (LLM)Reason about taskSelect tools to callGenerate structured outputTool NodeExecute tool callsweb_search("NYC weather")calculator("85 * 0.15")State UpdateAppend tool resultsUpdate message historyCheckpoint stateLoop: Agent → Tools → State → AgentDECISION: should_continue() — More tool calls needed?If tool_calls in last message → continue | If no tool_calls → ENDFINAL ANSWER"NYC weather is 72°F sunny. 15% tip on 12.75."LangGraph State (TypedDict)messages:List[BaseMessage]next_action:striteration:inttotal_cost:float

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.

FeatureLangChain AgentExecutorLangGraph
Loop supportLimitedFull cyclic graphs
State managementMemory objectsTypedDict with checkpointing
Human-in-the-loopDifficultBuilt-in pause/resume
StreamingBasicToken-by-token
PersistenceManualAutomatic 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

Need Expert AI Agents Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement