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

Building Your First ReAct Agent with LangGraph

AI AgentsBuilding Your First AgentđŸŸĸ Free Lesson

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

python
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.

python
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.

python
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

python
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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Agents Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement