How to beginner · 3 min read

How to create an agent in LangChain

Quick answer
To create an agent in LangChain, instantiate a language model like ChatOpenAI and combine it with tools and an agent class such as initialize_agent. This enables dynamic decision-making and tool usage within your AI workflows.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install langchain_openai langchain_community openai

Setup

Install the necessary packages and set your OpenAI API key as an environment variable.

  • Install LangChain and OpenAI SDK: pip install langchain_openai langchain_community openai
  • Set environment variable in your shell: export OPENAI_API_KEY='your_api_key' (Linux/macOS) or setx OPENAI_API_KEY "your_api_key" (Windows)
bash
pip install langchain_openai langchain_community openai

Step by step

This example creates a simple agent that uses the OpenAI gpt-4o model and a calculator tool to answer questions and perform calculations.

python
import os
from langchain_openai import ChatOpenAI
from langchain_community.agents import initialize_agent
from langchain_community.tools import Calculator

# Initialize the language model
llm = ChatOpenAI(model_name="gpt-4o", temperature=0, openai_api_key=os.environ["OPENAI_API_KEY"])

# Initialize tools
calculator = Calculator()

# Create an agent with the tools and the language model
agent = initialize_agent(
    tools=[calculator],
    llm=llm,
    agent_type="zero-shot-react-description",
    verbose=True
)

# Run the agent with a query
response = agent.run("What is 25 multiplied by 4?")
print(response)
output
100

Common variations

You can customize agents by:

  • Using different models like gpt-4o-mini or gemini-1.5-pro.
  • Adding multiple tools such as search, database queries, or custom APIs.
  • Using async calls with asyncio for concurrency.
  • Changing the agent type to chat-zero-shot-react-description or conversational-react-description for different reasoning styles.
python
import asyncio

async def async_agent_example():
    llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0, openai_api_key=os.environ["OPENAI_API_KEY"])
    calculator = Calculator()
    agent = initialize_agent(
        tools=[calculator],
        llm=llm,
        agent_type="zero-shot-react-description",
        verbose=False
    )
    response = await agent.arun("Calculate 12 divided by 3.")
    print(response)

asyncio.run(async_agent_example())
output
4.0

Troubleshooting

  • If you get an authentication error, verify your OPENAI_API_KEY environment variable is set correctly.
  • If the agent returns unexpected answers, try lowering the temperature or adding more descriptive tool documentation.
  • For timeout errors, check your network connection and consider increasing request timeouts in the client.

Key Takeaways

  • Use initialize_agent with ChatOpenAI and tools to create powerful LangChain agents.
  • Customize agents by changing models, tools, and agent types for your use case.
  • Always set your API key in os.environ to avoid authentication issues.
Verified 2026-04 · gpt-4o, gpt-4o-mini, gemini-1.5-pro
Verify ↗