How to use AgentExecutor in LangChain
Quick answer
Use
AgentExecutor in LangChain to run AI agents that combine language models and tools for complex workflows. Instantiate an agent with a language model and tools, then create an AgentExecutor to execute tasks by calling its run method with input prompts.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install langchain openai
Setup
Install LangChain and OpenAI Python SDK, and set your OpenAI API key as an environment variable.
pip install langchain openai Step by step
This example shows how to create an AgentExecutor using LangChain with OpenAI's gpt-4o model and a simple tool. The agent can process input and use the tool to answer queries.
import os
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, Tool, AgentExecutor
# Define a simple tool function
def echo_tool(text: str) -> str:
return f"Echo: {text}"
# Create a Tool object
echo = Tool(
name="EchoTool",
func=echo_tool,
description="Echoes the input text back."
)
# Initialize the language model
llm = ChatOpenAI(model="gpt-4o", temperature=0, openai_api_key=os.environ["OPENAI_API_KEY"])
# Initialize the agent with the tool and LLM
agent_executor = initialize_agent(
tools=[echo],
llm=llm,
agent="zero-shot-react-description",
verbose=True
)
# Run the agent executor with an input
result = agent_executor.run("Please echo this message.")
print(result) output
Echo: Please echo this message.
Common variations
- Use different models like
gpt-4o-miniorclaude-3-5-sonnet-20241022with their respective SDKs. - Run
AgentExecutorasynchronously by using async methods if supported. - Combine multiple tools for complex workflows.
- Customize agent types such as
chat-zero-shot-react-descriptionorconversational-react-description.
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If the agent does not respond as expected, check that tools have correct
nameanddescription. - For verbose debugging, set
verbose=Trueininitialize_agentto see detailed logs.
Key Takeaways
- Use
initialize_agentto create anAgentExecutorcombining tools and language models. - Pass input text to
AgentExecutor.run()to execute the agent workflow. - Set
verbose=Truefor detailed execution logs during development.