
Learn how to build powerful, autonomous AI agents using LangGraph in 2026. This practical tutorial covers setup, tools, memory, multi-agent systems, and real deployment with code examples.
Artificial intelligence has evolved. We are no longer just prompting chatbots to write text. In 2026, developers are building autonomous agents capable of reasoning, using external tools, and collaborating in multi-agent teams.
If you've been overwhelmed by the hype around "agentic AI" but don't know where to start, this guide is for you. We'll build a real, functional AI agent using LangGraph (currently one of the most production-ready frameworks) from scratch.
By the end, you'll have a customizable agent that can reason, use tools, remember conversations, and even collaborate with other agents.
Traditional LLMs (like ChatGPT) are great at one-shot answers.
AI agents go further. They are autonomous systems that can:
2026 trends show agentic AI moving from experiments to real business impact:
LangGraph (from the LangChain ecosystem) stands out because it provides:
Alternatives like CrewAI, AutoGen, and OpenAI Agents SDK are great, but LangGraph offers the most flexibility for production systems.
You should have:
Create a new project:
mkdir my-first-agent
cd my-first-agent
python -m venv venv
# Linux / macOS
source venv/bin/activate
# Windows
venv\Scripts\activate
Install dependencies:
pip install \
langgraph \
langchain \
langchain-openai \
langchain-community \
langchain-core \
python-dotenv
Project structure:
my-first-agent/
│
├── agent.py
├── .env
└── requirements.txt
Create .env:
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxx
Most modern agents use the ReAct Pattern:
Reason
↓
Act (Tool Use)
↓
Observe
↓
Reason Again
↓
Final Answer
Example:
User:
What's the weather in Lagos?
Agent:
I need weather information.
→ Calls weather tool
Tool:
31°C, Cloudy
Agent:
The weather in Lagos is 31°C and cloudy.
LangGraph makes building this loop straightforward.
Create agent.py.
from typing import TypedDict, Annotated
from typing import List
import operator
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
# State object
class AgentState(TypedDict):
messages: Annotated[List, operator.add]
# LLM
llm = ChatOpenAI(
model="gpt-4o",
temperature=0
)
# Agent node
def agent_node(state: AgentState):
response = llm.invoke(state["messages"])
return {
"messages": [response]
}
# Build graph
workflow = StateGraph(AgentState)
workflow.add_node("agent", agent_node)
workflow.set_entry_point("agent")
workflow.add_edge("agent", END)
app = workflow.compile()
if __name__ == "__main__":
result = app.invoke(
{
"messages": [
HumanMessage(
content="Explain AI agents simply."
)
]
}
)
print(result["messages"][-1].content)
Run:
python agent.py
At this stage, the system is simply an LLM wrapped in LangGraph.
Agents become powerful when they can interact with external systems.
Let's create a simple search tool.
from langchain.tools import tool
@tool
def search_web(query: str) -> str:
"""
Search the web for information.
"""
return f"Search results for: {query}"
Register tools:
tools = [search_web]
Bind tools to the model:
llm_with_tools = llm.bind_tools(tools)
Update the agent node:
def agent_node(state: AgentState):
response = llm_with_tools.invoke(
state["messages"]
)
return {
"messages": [response]
}
Now the model can decide when to call tools.
The previous version can request tools, but it cannot execute them.
Let's add a tool execution node.
from langgraph.prebuilt import ToolNode
tool_node = ToolNode(tools)
Create a router:
def should_continue(state: AgentState):
last_message = state["messages"][-1]
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
return "tools"
return END
Build graph:
workflow = StateGraph(AgentState)
workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)
workflow.set_entry_point("agent")
workflow.add_conditional_edges(
"agent",
should_continue
)
workflow.add_edge(
"tools",
"agent"
)
The workflow now becomes:
User
↓
Agent
↓
Needs Tool?
↓
Tool
↓
Agent
↓
Answer
This is a true ReAct agent.
Replace the mock tool with Tavily.
Install:
pip install tavily-python
Add API key:
TAVILY_API_KEY=tvly-xxxxxxxx
Create tool:
from tavily import TavilyClient
from langchain.tools import tool
client = TavilyClient()
@tool
def search_web(query: str) -> str:
"""
Search the internet.
"""
results = client.search(
query=query,
max_results=5
)
return str(results)
Now your agent can access real-world information.
Without memory, agents forget previous messages.
Install checkpoint support:
pip install langgraph-checkpoint
Add memory:
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
Compile graph:
app = workflow.compile(
checkpointer=memory
)
Invoke using a thread ID:
config = {
"configurable": {
"thread_id": "user-1"
}
}
Run:
app.invoke(
{
"messages": [
HumanMessage(
content="My name is Mustapha."
)
]
},
config=config
)
app.invoke(
{
"messages": [
HumanMessage(
content="What's my name?"
)
]
},
config=config
)
The agent will remember the previous interaction.
Instead of one-off execution, create an interactive terminal chat.
config = {
"configurable": {
"thread_id": "terminal-chat"
}
}
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
result = app.invoke(
{
"messages": [
HumanMessage(content=user_input)
]
},
config=config
)
print(
"\nAgent:",
result["messages"][-1].content
)
Run:
python agent.py
Example:
You: My favorite language is Python
Agent: Great! I'll remember that.
You: What's my favorite language?
Agent: Your favorite language is Python.
Short-term memory only exists per conversation thread.
For production applications, store memory in a database.
Example using PostgreSQL:
CREATE TABLE memories (
id UUID PRIMARY KEY,
user_id TEXT,
memory TEXT,
created_at TIMESTAMP
);
Memory tool:
@tool
def save_memory(memory: str) -> str:
"""
Save important user memory.
"""
# Insert into database
return "Memory saved."
Now the agent can persist information indefinitely.
Many business workflows require approval before actions.
Example:
Agent:
I am about to send an email.
Pause.
Human:
Approve
Agent:
Email sent.
LangGraph supports human-in-the-loop workflows using interrupts.
from langgraph.types import interrupt
def approval_node(state):
approval = interrupt(
{
"question":
"Approve this action?"
}
)
return {
"approval": approval
}
This is critical for production systems involving payments, emails, or sensitive operations.
One of LangGraph's biggest strengths is agent collaboration.
Example architecture:
Supervisor Agent
│
┌──────┼──────┐
│ │ │
Research Coding Writing
Agent Agent Agent
Research Agent:
def researcher(state):
...
Coding Agent:
def programmer(state):
...
Writer Agent:
def writer(state):
...
Supervisor:
def supervisor(state):
...
Each agent specializes in a task, producing better results than a single monolithic agent.
Production agents should return validated data.
Install:
pip install pydantic
Define schema:
from pydantic import BaseModel
class ResearchReport(BaseModel):
title: str
summary: str
sources: list[str]
Use structured output:
structured_llm = llm.with_structured_output(
ResearchReport
)
result = structured_llm.invoke(
"Research AI agents."
)
Benefits:
As agents become complex, debugging becomes difficult.
Install:
pip install langsmith
Environment variables:
LANGCHAIN_TRACING_V2=true
LANGCHAIN_API_KEY=lsv2_xxxxx
LangSmith allows you to:
This is essential in production.
A real-world production setup often looks like:
User
│
▼
LangGraph Agent
│
┌─────────┼─────────┐
▼ ▼ ▼
Memory Tools LLM
│ │ │
▼ ▼ ▼
PostgreSQL APIs OpenAI
Search
Email
CRM
ERP
Bad:
50 tools
Good:
5-10 highly relevant tools
Only store information that will be useful later.
Bad:
User said hello.
Good:
User prefers Python.
Without tracing, debugging agent failures becomes extremely difficult.
Always use LangSmith in production.
Start with:
Single Agent
↓
Tools
↓
Memory
↓
Human Approval
↓
Multi-Agent
Most applications never need multiple agents.
Once you've built this foundation, explore:
LangGraph has emerged as one of the leading frameworks for building production-grade AI agents. While many tutorials stop at simple chatbot examples, real agents require tools, memory, persistence, observability, and carefully designed workflows.
The progression is simple:
LLM
↓
LLM + Tools
↓
Agent
↓
Agent + Memory
↓
Agent + Human Approval
↓
Multi-Agent System
Master each stage before moving to the next.
By following this guide, you've built a solid foundation that can evolve into research assistants, customer support agents, coding copilots, business automation systems, or even entire teams of collaborating AI agents.
0 comments
Loading comments...