Skip to content
Learn Agentic AI
Learn Agentic AI12 min read3 views

Building LangChain Agents: Tools, AgentExecutor, and the ReAct Loop

Learn how to build LangChain agents that use tools to solve problems, understand the ReAct reasoning loop, and configure AgentExecutor for reliable agent behavior.

From Chains to Agents

A chain follows a fixed path: prompt goes in, response comes out. An agent, by contrast, decides at each step what action to take. It can call tools, inspect results, reason about what to do next, and repeat until it has enough information to answer the original question.

LangChain agents implement the ReAct (Reasoning + Acting) pattern. The model alternates between reasoning about the problem and taking actions (tool calls). This loop continues until the model decides it can produce a final answer.

Defining Tools

Tools are functions that an agent can invoke. Each tool has a name, a description (used by the LLM to decide when to call it), and an implementation.

flowchart TD
    START["Building LangChain Agents: Tools, AgentExecutor, …"] --> A
    A["From Chains to Agents"]
    A --> B
    B["Defining Tools"]
    B --> C
    C["Creating an Agent with Tool Binding"]
    C --> D
    D["Running the Agent"]
    D --> E
    E["The ReAct Loop Internals"]
    E --> F
    F["Multi-Tool Agent Example"]
    F --> G
    G["FAQ"]
    G --> DONE["Key Takeaways"]
    style START fill:#4f46e5,stroke:#4338ca,color:#fff
    style DONE fill:#059669,stroke:#047857,color:#fff
from langchain_core.tools import tool

@tool
def multiply(a: float, b: float) -> float:
    """Multiply two numbers together."""
    return a * b

@tool
def web_search(query: str) -> str:
    """Search the web for current information about a topic."""
    # In production, this would call a search API
    return f"Search results for: {query}"

print(multiply.name)        # "multiply"
print(multiply.description) # "Multiply two numbers together."

The @tool decorator automatically extracts the function name, docstring, and parameter types to build the tool schema. The LLM sees the name, description, and parameter schema when deciding which tool to call.

Creating an Agent with Tool Binding

Modern LangChain agents use the create_tool_calling_agent function, which leverages native tool-calling capabilities of chat models rather than parsing text output.

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import create_tool_calling_agent, AgentExecutor

# Define the prompt with required placeholders
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful math assistant."),
    MessagesPlaceholder("chat_history", optional=True),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad"),
])

# Create model and bind tools
llm = ChatOpenAI(model="gpt-4o", temperature=0)
tools = [multiply, web_search]

# Build the agent
agent = create_tool_calling_agent(llm, tools, prompt)

# Wrap in AgentExecutor
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

The agent_scratchpad placeholder is where intermediate tool calls and results are stored during the reasoning loop.

Running the Agent

result = executor.invoke({
    "input": "What is 47.5 multiplied by 23.8?"
})
print(result["output"])

With verbose=True, you will see the full reasoning trace:

See AI Voice Agents Handle Real Calls

Book a free demo or calculate how much you can save with AI voice automation.

flowchart TD
    CENTER(("Core Concepts"))
    CENTER --> N0["The agent receives the question"]
    CENTER --> N1["It decides to call the multiply tool wi…"]
    CENTER --> N2["The tool returns 1130.5"]
    CENTER --> N3["The agent produces the final answer: qu…"]
    CENTER --> N4["Reason — the LLM generates a response t…"]
    CENTER --> N5["Act — if tool calls are present, the ex…"]
    style CENTER fill:#4f46e5,stroke:#4338ca,color:#fff
  1. The agent receives the question
  2. It decides to call the multiply tool with arguments a=47.5, b=23.8
  3. The tool returns 1130.5
  4. The agent produces the final answer: "47.5 multiplied by 23.8 is 1,130.5"

The ReAct Loop Internals

Each iteration of the agent loop follows this pattern:

  1. Observe — the current state (user question plus any previous tool results) is formatted into the prompt
  2. Reason — the LLM generates a response that may include tool calls
  3. Act — if tool calls are present, the executor runs each tool and appends results to the scratchpad
  4. Repeat — the loop continues until the LLM responds without tool calls (the final answer)

The AgentExecutor manages this loop and provides safeguards:

executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=10,         # Prevent infinite loops
    handle_parsing_errors=True, # Recover from malformed output
    return_intermediate_steps=True, # Include tool call history
)

result = executor.invoke({"input": "Search for LangChain news"})

# Access intermediate steps
for step in result["intermediate_steps"]:
    action, observation = step
    print(f"Tool: {action.tool}, Input: {action.tool_input}")
    print(f"Result: {observation}")

Multi-Tool Agent Example

Here is a more complete agent that combines calculation and search capabilities.

from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import create_tool_calling_agent, AgentExecutor

@tool
def calculate(expression: str) -> str:
    """Evaluate a mathematical expression. Use Python syntax."""
    try:
        result = eval(expression)
        return str(result)
    except Exception as e:
        return f"Error: {e}"

@tool
def get_current_date() -> str:
    """Get today's date."""
    from datetime import date
    return date.today().isoformat()

tools = [calculate, get_current_date]

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant with access to tools. "
               "Always use tools when a calculation is needed."),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad"),
])

agent = create_tool_calling_agent(
    ChatOpenAI(model="gpt-4o-mini", temperature=0),
    tools,
    prompt,
)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

response = executor.invoke({
    "input": "What day is it and what is 2 raised to the 20th power?"
})
print(response["output"])

The agent will call both tools — get_current_date and calculate("2**20") — then combine the results into a coherent answer.

FAQ

What is the difference between create_tool_calling_agent and the older create_react_agent?

create_tool_calling_agent uses the native tool-calling API supported by modern LLMs, which returns structured tool calls in the response. create_react_agent relies on text-based parsing of the ReAct format. The tool-calling approach is more reliable and is the recommended default.

How do I prevent an agent from running forever?

Set max_iterations on the AgentExecutor. The default is 15. If the agent exceeds this limit, it returns an error message. You can also set max_execution_time (in seconds) as a wall-clock timeout.

Can an agent call the same tool multiple times?

Yes. The agent can call any tool any number of times across iterations. It can also call multiple tools in a single step if the model supports parallel tool calling.


#LangChain #AIAgents #ReAct #ToolUse #Python #AgenticAI #LearnAI #AIEngineering

Share
C

Written by

CallSphere Team

Expert insights on AI voice agents and customer communication automation.

Try CallSphere AI Voice Agents

See how AI voice agents work for your industry. Live demo available -- no signup required.

Related Articles You May Like

Use Cases

Automating Client Document Collection: How AI Agents Chase Missing Tax Documents and Reduce Filing Delays

See how AI agents automate tax document collection — chasing missing W-2s, 1099s, and receipts via calls and texts to eliminate the #1 CPA bottleneck.

AI Interview Prep

7 AI Coding Interview Questions From Anthropic, Meta & OpenAI (2026 Edition)

Real AI coding interview questions from Anthropic, Meta, and OpenAI in 2026. Includes implementing attention from scratch, Anthropic's progressive coding screens, Meta's AI-assisted round, and vector search — with solution approaches.

Learn Agentic AI

API Design for AI Agent Tool Functions: Best Practices and Anti-Patterns

How to design tool functions that LLMs can use effectively with clear naming, enum parameters, structured responses, informative error messages, and documentation.

Learn Agentic AI

AI Agents for IT Helpdesk: L1 Automation, Ticket Routing, and Knowledge Base Integration

Build IT helpdesk AI agents with multi-agent architecture for triage, device, network, and security issues. RAG-powered knowledge base, automated ticket creation, routing, and escalation.

Learn Agentic AI

Computer Use in GPT-5.4: Building AI Agents That Navigate Desktop Applications

Technical guide to GPT-5.4's computer use capabilities for building AI agents that interact with desktop UIs, browser automation, and real-world application workflows.

Learn Agentic AI

Prompt Engineering for AI Agents: System Prompts, Tool Descriptions, and Few-Shot Patterns

Agent-specific prompt engineering techniques: crafting effective system prompts, writing clear tool descriptions for function calling, and few-shot examples that improve complex task performance.