AI Agent Python Tutorial: Build a Working Agent with LangChain in 30 Minutes
AI Agent Python Tutorial: Build a Working Agent with LangChain in 30 Minutes
Python is the most popular language for building AI agents. With LangChain, you can create a functional agent that searches the web, reads files, and executes multi-step tasks in under 30 minutes.
This tutorial walks you through building a Python AI agent from scratch -- no prior agent development experience needed. You'll end with a working agent you can extend for any workflow.
In this tutorial:
- Setting up your Python environment
- Building your first agent
- Adding tools to your agent
- Adding memory and context
- Running multi-step workflows
- Deploying your agent
- No-code alternative
Related tutorials: Build AI Agent From Scratch · Autonomous AI Agent Tutorial · JavaScript AI Agent Tutorial · AI Agent Tools Tutorial
Setting Up Your Python Environment
Prerequisites
- Python 3.10 or later
- An OpenAI API key (get one here)
- A terminal or IDE (VS Code recommended)
Step 1: Create a Virtual Environment
mkdir ai-agent-tutorial && cd ai-agent-tutorial
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
Step 2: Install Dependencies
pip install langchain langchain-openai langchain-community python-dotenv
Step 3: Set Your API Key
Create a .env file:
OPENAI_API_KEY=sk-your-key-here
Load it in Python:
from dotenv import load_dotenv
load_dotenv()
Building Your First Agent
An AI agent has three components: a language model, a set of tools, and a prompt that tells it how to behave.
The Simplest Agent (5 lines)
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful research assistant. Use tools when needed."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
This sets up the model and prompt. But without tools, the agent is just a chatbot. Let's fix that.
Adding Tools to Your Agent
Tools are functions the agent can call to interact with the outside world. Here are three useful tools for a research agent:
Tool 1: Web Search
from langchain_community.tools.tavily_search import TavilySearchResults
search = TavilySearchResults(max_results=3)
Tool 2: Calculator
from langchain_core.tools import tool
@tool
def calculate(expression: str) -> str:
"""Evaluate a math expression. Input should be a valid Python math expression."""
try:
result = eval(expression)
return f"Result: {result}"
except Exception as e:
return f"Error: {e}"
Tool 3: Save to File
@tool
def save_to_file(filename: str, content: str) -> str:
"""Save content to a file. Args: filename (str), content (str)"""
try:
with open(filename, "w") as f:
f.write(content)
return f"Saved to {filename}"
except Exception as e:
return f"Error: {e}"
Wire Everything Together
tools = [search, calculate, save_to_file]
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
Get AI agent tips in your inbox
Multi-agent workflows, BYOK tips, and product updates. No spam.
result = agent_executor.invoke({ "input": "Search for the latest Python release version, then save it to a file called python_version.txt" })
print(result["output"])
When you run this, the agent will:
1. Search the web for the latest Python version
2. Extract the version number
3. Save it to a file
4. Report back
## Adding Memory and Context
By default, agents have no memory of previous interactions. Adding conversation memory is straightforward:
```python
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
message_history = ChatMessageHistory()
agent_with_memory = RunnableWithMessageHistory(
agent_executor,
get_session_history=lambda session_id: message_history,
input_messages_key="input",
history_messages_key="chat_history",
)
Now your agent remembers context across messages:
# First message
agent_with_memory.invoke(
{"input": "My name is Alex and I work on AI agents."},
config={"configurable": {"session_id": "user-1"}}
)
# Second message - agent remembers your name
agent_with_memory.invoke(
{"input": "What's my name and what do I work on?"},
config={"configurable": {"session_id": "user-1"}}
)
Running Multi-Step Workflows
For complex tasks, agents need to plan and execute multiple steps. Here's a research workflow:
research_prompt = ChatPromptTemplate.from_messages([
("system", """You are a research agent. Follow this workflow:
1. Break the research question into sub-questions
2. Search for information on each sub-question
3. Synthesize findings into a structured report
4. Save the report to a file
Always cite your sources."""),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
research_agent = create_tool_calling_agent(llm, tools, research_prompt)
research_executor = AgentExecutor(
agent=research_agent,
tools=tools,
verbose=True,
max_iterations=10,
)
Run a research task:
result = research_executor.invoke({
"input": "Compare LangChain vs CrewAI vs AutoGen for building multi-agent systems. Create a comparison table and save it."
})
The agent will autonomously search, compare, and produce a structured output.
Deploying Your Agent
Option 1: REST API with FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class AgentRequest(BaseModel):
message: str
@app.post("/agent")
async def run_agent(request: AgentRequest):
result = agent_executor.invoke({"input": request.message})
return {"response": result["output"]}
Run with: uvicorn main:app --host 0.0.0.0 --port 8000
Option 2: Scheduled Tasks with Celery
For background processing, use Celery with Redis:
from celery import Celery
app = Celery('agent_tasks', broker='redis://localhost:6379')
@app.task
def run_research(query: str):
result = research_executor.invoke({"input": query})
return result["output"]
Cost Considerations
Building agents with Python means you pay for API tokens directly. Here's what to expect:
Scroll to see full table
| Agent Task | Model | Approx. Cost |
|---|---|---|
| Simple Q&A | GPT-4o | $0.01-0.05 |
| Research with search | GPT-4o | $0.05-0.15 |
| Multi-step workflow | GPT-4o | $0.10-0.30 |
| Long report generation | GPT-4o | $0.15-0.50 |
Pro tip: Use GPT-4o-mini for simpler tasks to cut costs by 90%. Use GPT-4o only when reasoning quality matters.
For a detailed breakdown, see our AI Agent Cost Calculator.
No-Code Alternative with Ivern
If writing Python isn't your priority, Ivern AI lets you build AI agent squads without code:
- No Python needed -- configure agents through a web interface
- Bring Your Own Key -- use your existing OpenAI or Anthropic API key with zero markup
- Multi-agent squads -- create researcher, writer, and reviewer agents that hand off work automatically
- Built-in tools -- web search, file operations, and more without writing tool functions
Getting started takes 2 minutes: Create a free account, add your API key, and pick a template.
Troubleshooting Common Issues
Agent Loops Infinitely
Set max_iterations on the AgentExecutor:
AgentExecutor(agent=agent, tools=tools, max_iterations=5)
Agent Doesn't Use Tools
Make your tool descriptions specific and include examples:
@tool
def search_web(query: str) -> str:
"""Search the web for current information.
Input: a specific search query like 'Python 3.13 release date'
Returns: list of relevant results with titles and URLs."""
Rate Limiting Errors
Add retry logic:
from langchain_core.runnables import RunnableConfig
config = RunnableConfig(max_concurrency=3)
result = agent_executor.invoke({"input": "..."}, config=config)
Next Steps
Now that you have a working Python agent, here's where to go:
- Add more tools -- file I/O, database queries, API calls
- Build multi-agent systems -- see our Multi-Agent Tutorial
- Add RAG -- connect your agent to a knowledge base with our AI Agent RAG Tutorial
- Deploy to production -- containerize with Docker and deploy on your preferred cloud
Ready to skip the code? Try Ivern AI free and build your first agent squad in 2 minutes.
Related guides: How to Build an AI Agent · AI Agent Framework Comparison · AI Agent Pricing Benchmarks
Related Articles
How to Build an AI Agent in 2026: Complete Guide (No Code Required)
A step-by-step guide to building your first AI agent in 2026. Covers three approaches: no-code tools (Ivern AI), Python frameworks (CrewAI, AutoGen), and custom API integrations. Includes real examples, cost estimates, and a decision framework.
AI Agent API Integration Tutorial: Connect Agents to Any External Service
Step-by-step tutorial for connecting AI agents to external APIs and services. Covers REST API integration, authentication, error handling, rate limiting, and building a tool layer that lets agents interact with any service.
AI Agent Collaboration Tutorial: How to Make Multiple Agents Work Together
Learn how to build collaborative AI agent systems where multiple specialized agents share context, hand off tasks, and produce results together. Covers communication patterns, context sharing, and real implementation examples.
Want to try multi-agent AI for free?
Generate a blog post, Twitter thread, LinkedIn post, and newsletter from one prompt. No signup required.
Try the Free DemoAI Content Factory -- Free to Start
One prompt generates blog posts, social media, and emails. Free tier, BYOK, zero markup.
No spam. Unsubscribe anytime.