How to beginner · 3 min read

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.

bash
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.

python
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-mini or claude-3-5-sonnet-20241022 with their respective SDKs.
  • Run AgentExecutor asynchronously by using async methods if supported.
  • Combine multiple tools for complex workflows.
  • Customize agent types such as chat-zero-shot-react-description or conversational-react-description.

Troubleshooting

  • If you get authentication errors, verify your OPENAI_API_KEY environment variable is set correctly.
  • If the agent does not respond as expected, check that tools have correct name and description.
  • For verbose debugging, set verbose=True in initialize_agent to see detailed logs.

Key Takeaways

  • Use initialize_agent to create an AgentExecutor combining tools and language models.
  • Pass input text to AgentExecutor.run() to execute the agent workflow.
  • Set verbose=True for detailed execution logs during development.
Verified 2026-04 · gpt-4o, gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗