How to Build an AI Agent with LangGraph in 30 Minutes
Why LangGraph?
Most so-called AI agents are a loop: the model decides what to do, calls a tool, reads the result, and decides again. When that loop lives inside a black-box chain, a failure is hard to explain. LangGraph makes the loop explicit. Your agent becomes a graph of nodes (steps) and edges (transitions) with visible state, so you can inspect, resume, and debug every run.
One version note before we start: LangChain and LangGraph reached v1.0, and the old shortcut create_react_agent is deprecated in favor of LangChain's create_agent. Many tutorials still floating around use the old API, so this guide uses the current one — and then shows you the graph underneath, which is where LangGraph's real value lives.
What You Will Build
A small research assistant agent with two tools: a calculator and a placeholder web-search tool. You will run it two ways — first with the five-line shortcut, then by building the same loop by hand as a LangGraph state machine — and finish by giving it memory across turns.
Prerequisites
- Python 3.10 or newer
- An API key from a model provider (the examples use OpenAI)
- About 30 minutes and a terminal
Step 1: Install the Packages
pip install -U langchain langgraph langchain-openai langchain provides the high-level create_agent shortcut; langgraph provides the graph engine underneath it.
Step 2: Define Two Tools
A tool is a Python function plus a docstring the model can read. The docstring matters more than the code: it is how the model decides when to call the tool, so write it for the model, not for a maintainer.
from langchain_core.tools import tool
@tool
def calculator(expression: str) -> str:
"""Evaluate a math expression like '850 * 0.15'. Use for any arithmetic."""
try:
return str(eval(expression))
except Exception as e:
return f"Error: {e}"
@tool
def web_search(query: str) -> str:
"""Search the web for current facts. Use when you need information beyond training data."""
# Swap this stub for a real search API (for example Tavily) in production.
return f"Placeholder results for: {query}"
tools = [calculator, web_search] Keep the tool list short. Accuracy drops as tools pile up; when an agent needs dozens of tools, split the work across specialized sub-agents instead.
Step 3: The Five-Line Shortcut
from langchain.agents import create_agent
agent = create_agent(
model="openai:gpt-4o-mini",
tools=tools,
system_prompt="You are a precise research assistant. Use tools for facts and arithmetic.",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "What is 15% of 850?"}]}
)
print(result["messages"][-1].content) That is a working agent. The model sees the question, calls the calculator, reads the result, and answers. But if it misbehaves — calling the wrong tool, looping, ignoring a result — the shortcut gives you little to grab onto. That is why step 4 matters.
Source: LangChain docs — the core agent loop.
Step 4: Build the Same Loop by Hand in LangGraph
The hand-built version has exactly three moving parts:
- An agent node that calls the model with the current conversation.
- A tools node (
ToolNode) that executes whichever tools the model requested. - A router (
tools_condition) that sends the run to the tools node when the model made a tool call, and ends it otherwise.
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
model_with_tools = model.bind_tools(tools)
def call_model(state: MessagesState):
response = model_with_tools.invoke(state["messages"])
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)
builder.add_edge("tools", "agent")
graph = builder.compile() MessagesState is a ready-made state schema holding the conversation. The graph runs agent → tools → agent until the model stops calling tools, then ends. Run it like this:
result = graph.invoke(
{"messages": [{"role": "user", "content": "What is 15% of 850, and what is the capital of France?"}]}
)
print(result["messages"][-1].content) To watch the loop unfold step by step, use streaming instead of invoke:
for step in graph.stream(
{"messages": [{"role": "user", "content": "What is 15% of 850?"}]},
stream_mode="values",
):
print(step["messages"][-1].content) Step 5: Add Memory
By default the agent forgets everything between calls. A checkpointer persists the graph's state per conversation thread, so a follow-up question like "and what about 20%?" still has context.
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
graph = builder.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": "demo-1"}}
graph.invoke(
{"messages": [{"role": "user", "content": "What is 15% of 850?"}]},
config=config,
)
result = graph.invoke(
{"messages": [{"role": "user", "content": "And what about 20% of the same number?"}]},
config=config,
)
print(result["messages"][-1].content) InMemorySaver keeps memory for the current process. For persistence across restarts, swap it for a SQLite or PostgreSQL checkpointer — the same mechanism that powers pause-and-resume and human-approval workflows.
Step 6: Test It Like a Skeptic
Before trusting the agent, verify the mechanics:
- Ask a question that requires a tool, and check that the tool was actually called with the right arguments — a polished final answer can hide a wrong tool choice.
- Ask a follow-up that depends on the previous turn, and confirm memory works.
- Ask something the stub search cannot answer, and confirm the agent says so instead of inventing facts.
Troubleshooting
- The model answers without calling a tool. Strengthen the tool docstring and the system prompt. Tell the agent explicitly which tool to use for which job.
- The agent loops forever. The graph has a recursion limit that fails the run instead of burning tokens indefinitely. A loop usually means a tool returns something the model misreads — log the tool outputs and fix the tool, not the prompt.
- Old tutorials do not run. Code using
initialize_agent,AgentExecutor, orcreate_react_agenttargets deprecated APIs. Translate it tocreate_agentor theStateGraphpattern above. - API key errors. Set the key as an environment variable (
OPENAI_API_KEY) rather than hard-coding it in the script.
What to Build Next
This two-node loop is the foundation of every LangGraph agent. From here, the natural upgrades are: a human-in-the-loop approval step before any tool that writes or spends anything, a retrieval node that grounds answers in your own documents, and subgraphs that split a job across specialized agents. If you want retrieval first, see our guide to building a local RAG system with Ollama and Qdrant. When the agent outgrows one machine, our inference-engine comparison and hosted vs self-hosted cost comparison will help you decide where to run the model.
Closing
You now have a working tool-using agent, the graph behind it, and memory across turns — in one short session. The shortcut gets you running; the graph keeps you in control. Start from the hand-built loop whenever the agent will touch real data, real tools, or real users, because that is exactly when you will need to see what it is doing.


Comments
Post a Comment