0
0
LangchainHow-ToBeginner ยท 3 min read

How to Use AgentExecutor in Langchain: Simple Guide

Use AgentExecutor in Langchain to run an agent with tools and a language model. Initialize it with an agent and tools, then call run() with your input to get the agent's response.
๐Ÿ“

Syntax

The AgentExecutor is created by passing an agent and a list of tools. You then call run() with a string input to execute the agent's logic.

  • agent: The agent logic that decides how to use tools.
  • tools: A list of tools the agent can use to answer queries.
  • run(input): Runs the agent with the given input string.
python
from langchain.agents import AgentExecutor

executor = AgentExecutor(agent=agent, tools=tools)
result = executor.run("Your input here")
๐Ÿ’ป

Example

This example shows how to create a simple agent with a tool and run it using AgentExecutor. The agent uses a language model and a tool to answer a question.

python
from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from langchain.tools import Tool

# Define a simple tool
def echo_tool(text: str) -> str:
    return f"Echo: {text}"

# Wrap the tool
tools = [Tool(name="EchoTool", func=echo_tool, description="Echoes input text.")]

# Initialize the language model
llm = OpenAI(temperature=0)

# Initialize the agent with the tools and llm
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=False)

# Run the agent
output = agent.run("Say hello using the echo tool.")
print(output)
Output
Echo: Say hello using the echo tool.
โš ๏ธ

Common Pitfalls

Common mistakes when using AgentExecutor include:

  • Not passing the correct agent or tools when creating the executor.
  • Forgetting to call run() with a string input.
  • Using tools that do not match the agent's expected interface.
  • Not handling asynchronous calls if your agent or tools require async.

Always ensure your tools are properly wrapped and your agent is compatible with the tools.

python
from langchain.agents import AgentExecutor

# Wrong: Missing tools
executor_wrong = AgentExecutor(agent=agent, tools=None)  # This will cause errors

# Right: Provide tools list
executor_right = AgentExecutor(agent=agent, tools=tools)
๐Ÿ“Š

Quick Reference

  • AgentExecutor(agent, tools): Create executor with agent and tools.
  • run(input: str): Run the agent with input string.
  • Tools must be wrapped with Tool class.
  • Agent decides how to use tools to answer queries.
โœ…

Key Takeaways

Create AgentExecutor by passing a valid agent and a list of tools.
Call run() with a string input to execute the agent's logic.
Ensure tools are properly wrapped and compatible with the agent.
Avoid missing tools or incorrect parameters to prevent errors.
AgentExecutor simplifies running agents with multiple tools in Langchain.