How to use create_react_agent in LangChain
Quick answer
Use
create_react_agent from langchain.agents to build an AI agent that uses React-style reasoning with tools. Initialize your language model and tools, then call create_react_agent with these to get an agent ready for interaction.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install langchain openai
Setup
Install the required packages and set your OpenAI API key as an environment variable.
pip install langchain openai Step by step
This example demonstrates creating a React agent with LangChain using OpenAI's GPT-4o model and a simple tool. The agent uses React-style reasoning to decide which tool to call and how to respond.
import os
from langchain.agents import create_react_agent
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
# Initialize the language model
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Define a simple tool
def greet(name: str) -> str:
return f"Hello, {name}!"
greet_tool = Tool(
name="greet",
func=greet,
description="Greets a person by name."
)
# Create the React agent with the LLM and tools
agent = create_react_agent(llm=llm, tools=[greet_tool])
# Run the agent with a user query
response = agent.invoke("Greet Alice")
print(response) output
Hello, Alice!
Common variations
- Use different LLMs like
gpt-4o-minior Anthropic models with LangChain adapters. - Integrate multiple tools for complex workflows.
- Use async versions of LangChain components for concurrency.
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - Ensure your tools have clear
descriptionfields for better agent reasoning. - If the agent does not respond as expected, try lowering
temperatureto 0 for deterministic output.
Key Takeaways
- Use
create_react_agentto build agents that reason step-by-step with tools in LangChain. - Always provide descriptive tools to improve agent decision-making.
- Set
temperature=0for consistent agent responses during testing. - You can combine multiple tools for complex agent workflows.
- Verify environment variables to avoid authentication issues.