Skip to content
Rabat, Morocco
Tutorials

Building AI Agents with LangChain and OpenAI: Complete Guide for 2025

November 14, 2025
Building AI Agents with LangChain and OpenAI
So you want to build AI agents? That's awesome! Let me tell you what makes them special. AI agents are basically autonomous systems that can actually think, plan, and get things done. They're not just chatbots that respond to messages. These agents can interact with APIs, databases, and other services to accomplish real goals. The cool part? With LangChain and OpenAI's powerful models, building production-ready AI agents is actually doable now. I've been working with these tools for a while, and I'm excited to show you how it all works. In this tutorial, we're going to build intelligent AI agents from scratch. We'll start with the basics and work our way up to advanced multi-agent architectures. By the end, you'll have everything you need to build your own agents. Here's why I'm excited about AI agents right now. They're basically the next big thing in AI applications, and here's what makes them so powerful:
  • Autonomous Decision Making: These agents can actually break down complex tasks into steps and figure things out on their own
  • Tool Integration: They can connect to APIs, databases, and external services. Think of them as having access to the whole internet
  • Memory and Context: They remember conversations and learn from interactions. It's like talking to someone who actually pays attention
  • Multi-Agent Collaboration: Multiple agents can work together on complex problems. It's like having a team that never gets tired
Pretty cool, right? Let's build one. Before we dive in, let's make sure you have everything you need:
  • Python 3.9 or higher installed (if you don't have it, grab it from python.org)
  • An OpenAI API key (get one here - it's pretty straightforward)
  • Basic understanding of Python and APIs (don't worry if you're not an expert, we'll walk through everything)
Got everything? Great! Let's get started. Alright, let's get everything set up. First, we need to install the packages we'll be using. Just run this in your terminal:
pip install langchain langchain-openai langchain-community python-dotenv
Next, we need to store your API key securely. Create a
.env
file in your project root (make sure it's in your
.gitignore
so you don't accidentally commit it):
OPENAI_API_KEY=your-api-key-here
Just replace
your-api-key-here
with your actual OpenAI API key. Keep this file safe!
Okay, here's where it gets fun. Let's build your first AI agent! We're going to start simple - an agent that can answer questions and do basic calculations. Don't worry, we'll make it more powerful later. For now, let's get something working:
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.tools import Tool
from langchain_core.messages import HumanMessage
import os
from dotenv import load_dotenv

load_dotenv()

# Initialize the LLM
llm = ChatOpenAI(
    model="gpt-4-turbo-preview",
    temperature=0,
    api_key=os.getenv("OPENAI_API_KEY")
)

# Define custom tools
def calculate(expression: str) -> str:
    """Evaluate a mathematical expression safely."""
    try:
        result = eval(expression)
        return str(result)
    except:
        return "Error: Invalid expression"

def get_weather(city: str) -> str:
    """Get weather information for a city."""
    # In production, this would call a weather API
    return f"The weather in {city} is sunny, 22°C"

# Create tools
tools = [
    Tool(
        name="Calculator",
        func=calculate,
        description="Useful for performing mathematical calculations. Input should be a valid Python expression."
    ),
    Tool(
        name="Weather",
        func=get_weather,
        description="Get current weather information for any city."
    )
]

# Create the prompt template
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI assistant with access to tools."),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad")
])

# Create the agent
agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Run the agent
response = agent_executor.invoke({
    "input": "What's 25 * 4 + 100? Also, what's the weather in Paris?",
    "chat_history": []
})

print(response["output"])
Let me break down how these agents actually work. Think of an AI agent like a team member who has access to tools and remembers what you've talked about. Here are the key pieces: This is the brain of your agent. I like to use OpenAI's GPT-4 Turbo because it's really good at reasoning through complex tasks. It's what makes your agent smart. These are like the agent's superpowers. They're functions your agent can call to interact with the outside world. Think of things like:
  • API calls (fetching data from external services)
  • Database queries (getting information from your database)
  • File operations (reading and writing files)
  • Web scraping (getting data from websites)
The agent decides when to use these tools based on what you ask it to do. This is what makes conversations feel natural. Your agent remembers what you've talked about. LangChain gives you a few options:
  • ConversationBufferMemory: Remembers everything (good for short conversations)
  • ConversationSummaryMemory: Summarizes long conversations (saves tokens!)
  • Vector Store Memory: Uses semantic search to find relevant past interactions (really powerful for long-term memory)
This is the conductor of the orchestra. It manages the whole decision-making process:
  1. You ask something
  2. The LLM thinks "hmm, do I need a tool for this?"
  3. If yes, it picks the right tool and uses it
  4. The tool gives back results
  5. The LLM takes those results and gives you a final answer
Pretty neat, right? Now let's make it more powerful. Okay, now we're getting into the really cool stuff. Sometimes one agent isn't enough. For complex tasks, you can create multiple specialized agents that work together. It's like having a team where each person has their own expertise. Let me show you how:
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.tools import Tool
import os

class ResearchAgent:
    def __init__(self):
        self.llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0)
        self.tools = [
            Tool(
                name="WebSearch",
                func=self.web_search,
                description="Search the web for information"
            )
        ]
        prompt = ChatPromptTemplate.from_messages([
            ("system", "You are a research specialist. Find accurate information."),
            MessagesPlaceholder(variable_name="chat_history"),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad")
        ])
        self.agent = create_openai_tools_agent(self.llm, self.tools, prompt)
        self.executor = AgentExecutor(agent=self.agent, tools=self.tools)

    def web_search(self, query: str) -> str:
        # In production, integrate with Google Search API or Serper
        return f"Search results for: {query}"

    def research(self, topic: str) -> str:
        return self.executor.invoke({"input": f"Research: {topic}"})["output"]

class WritingAgent:
    def __init__(self):
        self.llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0.7)
        self.tools = []
        prompt = ChatPromptTemplate.from_messages([
            ("system", "You are a professional writer. Create engaging content."),
            MessagesPlaceholder(variable_name="chat_history"),
            ("human", "{input}"),
        ])
        self.agent = create_openai_tools_agent(self.llm, self.tools, prompt)
        self.executor = AgentExecutor(agent=self.agent, tools=self.tools)

    def write(self, content: str, style: str = "professional") -> str:
        return self.executor.invoke({
            "input": f"Write about: {content} in a {style} style"
        })["output"]

# Orchestrator agent that coordinates other agents
class OrchestratorAgent:
    def __init__(self):
        self.research_agent = ResearchAgent()
        self.writing_agent = WritingAgent()
        self.llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0)

    def create_content(self, topic: str) -> str:
        # Step 1: Research
        research = self.research_agent.research(topic)

        # Step 2: Write
        content = self.writing_agent.write(
            f"Topic: {topic}\nResearch: {research}",
            style="engaging"
        )

        return content

# Usage
orchestrator = OrchestratorAgent()
result = orchestrator.create_content("The future of AI agents")
print(result)
Alright, let's make this agent actually useful by connecting it to real APIs and services. This is where agents really shine - they can interact with the real world:
from langchain.tools import Tool
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits import create_sql_agent

# Connect to your database
db = SQLDatabase.from_uri("postgresql://user:pass@localhost/dbname")

# Create SQL agent
agent = create_sql_agent(
    llm=ChatOpenAI(model="gpt-4-turbo-preview"),
    db=db,
    verbose=True
)

# Query the database
result = agent.invoke({
    "input": "How many users signed up last month?"
})
import requests
from langchain.tools import Tool

def fetch_github_repo(repo: str) -> str:
    """Fetch GitHub repository information."""
    try:
        response = requests.get(f"https://api.github.com/repos/{repo}")
        data = response.json()
        return f"Repo: {data['name']}, Stars: {data['stargazers_count']}, Language: {data['language']}"
    except:
        return "Error fetching repository"

github_tool = Tool(
    name="GitHubRepo",
    func=fetch_github_repo,
    description="Get information about a GitHub repository. Input format: 'owner/repo'"
)

tools.append(github_tool)
Now let's talk about memory. This is what makes your agent feel like it's actually paying attention. Here's how to implement it:
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)

# Use memory in agent executor
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    memory=memory,
    verbose=True
)

# The agent will remember previous conversations
response1 = agent_executor.invoke({"input": "My name is John"})
response2 = agent_executor.invoke({"input": "What's my name?"})
# Response: "Your name is John"
Okay, let's be real. Things go wrong sometimes. If you're going to put this in production, you need to handle errors gracefully. Here's how I do it:
from langchain.callbacks import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler

class RobustAgentExecutor(AgentExecutor):
    def invoke(self, input_dict, config=None):
        try:
            # Set max iterations to prevent infinite loops
            config = config or {}
            config["max_iterations"] = 15

            return super().invoke(input_dict, config)
        except Exception as e:
            return {
                "output": f"I encountered an error: {str(e)}. Let me try a different approach.",
                "error": str(e)
            }

# Usage with error handling
robust_executor = RobustAgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=15,
    max_execution_time=30  # seconds
)
Alright, let's talk about making this production-ready. I've learned a few things the hard way, so let me share what works: API costs can add up fast. Trust me, I've been there. Here's how to keep them under control:
import time
from functools import wraps

def rate_limit(calls_per_minute=60):
    min_interval = 60.0 / calls_per_minute
    last_called = [0.0]

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            elapsed = time.time() - last_called[0]
            left_to_wait = min_interval - elapsed
            if left_to_wait > 0:
                time.sleep(left_to_wait)
            ret = func(*args, **kwargs)
            last_called[0] = time.time()
            return ret
        return wrapper
    return decorator

@rate_limit(calls_per_minute=30)
def api_call():
    # Your API call here
    pass
Here's a pro tip: not every task needs GPT-4. Use cheaper models when you can:
# Use GPT-3.5 for simple tasks
simple_llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

# Use GPT-4 only for complex reasoning
complex_llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0)

def route_to_model(task_complexity: str):
    if task_complexity == "simple":
        return simple_llm
    return complex_llm
import logging
from langchain.callbacks import StdOutCallbackHandler

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class LoggingCallback(StdOutCallbackHandler):
    def on_agent_action(self, action, **kwargs):
        logger.info(f"Agent action: {action.tool}")

    def on_tool_end(self, output, **kwargs):
        logger.info(f"Tool output: {output}")

callbacks = [LoggingCallback()]
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    callbacks=callbacks,
    verbose=True
)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from langchain.agents import AgentExecutor

app = FastAPI()

class AgentRequest(BaseModel):
    message: str
    conversation_id: str = None

@app.post("/agent/chat")
async def chat_with_agent(request: AgentRequest):
    try:
        response = agent_executor.invoke({
            "input": request.message,
            "chat_history": get_conversation_history(request.conversation_id)
        })
        return {"response": response["output"]}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
So where are people actually using these agents? Let me give you some real examples I've seen:
  1. Customer Support: Companies are using agents to automatically resolve tickets and route complex issues. It's pretty impressive.
  2. Data Analysis: Agents that can query databases and generate insights. No more writing SQL queries!
  3. Content Creation: Research agents that find information and writing agents that turn it into articles. The whole pipeline is automated.
  4. Code Generation: Agents that can build applications from specifications. Wild, right?
  5. E-commerce: Shopping assistants that actually understand what you're looking for and help you find it.
The possibilities are pretty endless. What would you build? We've covered a lot! Building AI agents with LangChain and OpenAI really does open up incredible possibilities. When you combine powerful LLMs with tool integration, memory, and good architecture, you can create systems that actually solve problems on their own. Here's what I want you to remember:
  • Start simple and iterate (don't try to build everything at once)
  • Use appropriate models for each task (save money where you can)
  • Implement robust error handling (things will break, be ready)
  • Monitor costs and performance (trust me on this one)
  • Design for scalability from the start (you'll thank yourself later)
You've got everything you need to start building. Now go make something cool!
  1. Experiment with different agent types and tools
  2. Build a project-specific agent for your use case
  3. Optimize for your specific requirements
  4. Deploy and monitor in production
Happy building! 🚀

Enjoyed this tutorial?

Seriously, thank you for spending your time here. If you made it to the end, you’re the kind of person who cares about craft, not just quick fixes.If you’d like to support my work, pick one (no pressure). It genuinely helps me keep writing and improving these tutorials.
Subscribe to get a heads-up when I publish the next one. I keep it low-volume, and I only send what I’d personally want to read.

Subscribe to Josias's Newsletter

I occasionally write about software engineering, technology, and share thoughts on innovation and engineering.
One last thing: if you know someone who’d benefit from this, sharing it with them is one of the best compliments you can give. I appreciate you.