0PricingLogin
AI Engineering Academy · Lesson

Building a ReAct Agent with LangChain

Assemble a full ReAct agent using LangChain's AgentExecutor with a web search tool, a calculator tool, and a document lookup tool, then trace its reasoning steps.

LangChain's Agent Ecosystem

LangChain provides a complete stack for building agents: tools define what the agent can do, prompts give it its instructions and reasoning format, the LLM does the thinking, and the AgentExecutor runs the loop that dispatches tool calls and feeds observations back. You configure each piece separately so you can swap components without rewriting everything.

Assembling a ReAct Agent

The quickest way to build a ReAct agent in LangChain is with create_react_agent. You pass it an LLM, a list of tools, and a prompt template. It returns a runnable that generates Thought/Action/Observation steps automatically. Wrap it in an AgentExecutor to manage the loop.

from langchain import hub
from langchain.agents import create_react_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

# 1. Define tools
@tool
def search(query: str) -> str:
    '''Search the web for current information. Input: a search query string.'''
    return f'Search results for "{query}": [mock result]'

@tool
def calculator(expression: str) -> str:
    '''Evaluate a math expression. Input: a valid Python math expression.'''
    try:
        return str(eval(expression))
    except Exception as e:
        return str(e)

tools = [search, calculator]

# 2. Load a ReAct prompt template
prompt = hub.pull('hwchase17/react')

# 3. Create the agent
llm = ChatOpenAI(model='gpt-4o', temperature=0)
agent = create_react_agent(llm, tools, prompt)

All lessons in this course

  1. The ReAct Framework: Think, Act, Observe
  2. Defining Tools for Your Agent
  3. Building a ReAct Agent with LangChain
  4. Handling Agent Failures and Loops
← Back to AI Engineering Academy