Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Principle:Langchain ai Langgraph ReAct Agent Construction

From Leeroopedia
Revision as of 17:43, 16 February 2026 by Admin (talk | contribs) (Auto-imported from principles/Langchain_ai_Langgraph_ReAct_Agent_Construction.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Attribute Value
Concept Building a ReAct (Reason+Act) agent that iteratively reasons and calls tools
Workflow ReAct_Agent_Creation
Type Principle
Repository Langchain_ai_Langgraph
Source libs/prebuilt/langgraph/prebuilt/chat_agent_executor.py

Overview

ReAct agent construction is the process of assembling a complete agent graph that implements the Reason+Act loop -- a pattern where a language model alternates between reasoning about the current state and taking actions via tool calls. The create_react_agent function is the primary factory for building these agents in LangGraph. It constructs a StateGraph with an "agent" node (for LLM inference), a "tools" node (for tool execution), and conditional edges that implement the iterative loop. The function handles model initialization, tool binding, prompt composition, structured output generation, pre/post model hooks, and graph compilation into a single, high-level API call.

Description

The ReAct Pattern

The ReAct (Reasoning + Acting) pattern structures agent behavior as an iterative cycle:

  1. Reason: The language model examines the current conversation history (including prior tool results) and decides what to do next.
  2. Act: If the model determines it needs more information, it generates tool calls. If it has enough information, it produces a final text response.
  3. Observe: Tool results are appended to the message history, and the cycle returns to step 1.

This cycle continues until the model produces a response without tool calls, signaling that it has reached a conclusion. The pattern naturally handles multi-step reasoning, error recovery (the model can retry failed tool calls), and information gathering from multiple sources.

Graph Topology

The create_react_agent function constructs a StateGraph with the following topology:

  • Entry point: Either "agent" or "pre_model_hook" (if a pre-model hook is configured).
  • Agent node: Calls the language model with the current message history. Produces an AIMessage that may contain tool_calls.
  • Conditional routing: After the agent node, a should_continue function inspects the response:
    • If tool_calls are present, route to "tools" (v1) or dispatch individual tool calls via Send (v2).
    • If no tool calls, route to "post_model_hook", "generate_structured_response", or END.
  • Tools node: A ToolNode that executes the requested tools and appends ToolMessage results.
  • Return edge: After tool execution, control returns to the entry point (agent or pre-model hook) for the next reasoning cycle.

In version "v2" (the default), individual tool calls are dispatched as separate Send operations, enabling fine-grained parallelism and better error isolation. In version "v1", all tool calls in a single AIMessage are processed together by the tool node.

Pre-Model and Post-Model Hooks

The hook system provides extension points in the agent loop:

  • Pre-model hook: Executes before every LLM call. This is the recommended place for message trimming, summarization, or context window management. The hook receives the full graph state and returns an update that must include either messages (to overwrite state messages) or llm_input_messages (to provide LLM input without modifying state).
  • Post-model hook: Executes after every LLM call but before tool execution routing. This enables human-in-the-loop approval, guardrails, output validation, or logging. The post-model hook receives the full state (including the latest AIMessage) and returns a state update.

Structured Output

When a response_format is provided, the agent adds a "generate_structured_response" node that runs after the agent loop completes (i.e., when the model stops calling tools). This node uses model.with_structured_output(schema) to make a separate LLM call that formats the final response according to the provided schema (Pydantic model, TypedDict, JSON Schema, or OpenAI function schema). The result is stored in the structured_response state key.

Remaining Steps Guard

The agent includes a safety mechanism based on the remaining_steps state field (managed by RemainingSteps). When remaining steps drop below 2 and tool calls are present, the agent returns a message indicating it needs more steps, preventing a GraphRecursionError.

Usage

from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool

@tool
def search(query: str) -> str:
    """Search for information."""
    return f"Results for: {query}"

@tool
def calculator(expression: str) -> str:
    """Evaluate a math expression."""
    return str(eval(expression))

# Basic agent
agent = create_react_agent(
    "openai:gpt-4",
    tools=[search, calculator],
    prompt="You are a helpful research assistant.",
)

# Agent with hooks and structured output
from pydantic import BaseModel

class ResearchResult(BaseModel):
    summary: str
    sources: list[str]

agent = create_react_agent(
    "anthropic:claude-3-7-sonnet-latest",
    tools=[search],
    prompt="You are a research assistant. Search for information and provide a structured summary.",
    response_format=ResearchResult,
    pre_model_hook=my_trimming_function,
    post_model_hook=my_validation_function,
    version="v2",
)

result = agent.invoke({"messages": [("user", "Research quantum computing")]})

Theoretical Basis

The ReAct pattern was formally introduced by Yao et al. in "ReAct: Synergizing Reasoning and Acting in Language Models" (2022). The key insight is that interleaving reasoning traces (chain-of-thought) with actions (tool calls) enables LLMs to handle complex tasks that require both planning and information retrieval. Compared to pure chain-of-thought reasoning, ReAct agents can ground their reasoning in external observations, reducing hallucination and improving factual accuracy.

LangGraph's implementation maps the ReAct pattern onto a state machine formalism. The graph nodes represent discrete processing stages (reasoning, acting, observing), and the edges encode the transition logic. This state machine interpretation provides several advantages:

  • Deterministic control flow: The conditional routing logic is explicit and inspectable, unlike implicit reasoning in prompts.
  • Interruptibility: The graph can be paused at any node boundary for human-in-the-loop intervention.
  • Persistence: State checkpointing enables resuming agent execution across sessions.
  • Composability: The compiled agent is itself a Runnable, allowing it to be embedded as a subgraph in larger multi-agent systems.

The version "v2" dispatch mechanism using Send implements a scatter-gather pattern where tool calls are fanned out to parallel executors and their results are gathered back into the message history before the next reasoning step.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment