LangGraph Tutorial: Build Stateful AI Agents Step by Step
LangGraph tutorial: build a stateful AI agent step by step, from install and state design to tools, memory with a checkpointer, and a human approval step.
By Galactic News Editorial · Published 2026-11-17T04:35:28+00:00 · Updated 2026-11-17T04:35:28+00:00
This LangGraph tutorial builds a stateful AI agent from scratch, step by step. LangGraph is the graph-based framework from the LangChain team for agents that loop, branch, and remember. A plain chain runs once and forgets. A LangGraph agent keeps state across turns, retries a failed step, and pauses for a human decision. By the end of this tutorial you will have a working agent with tools, memory, and a human approval step.
What LangGraph is, and when to use it
LangGraph models an agent as a directed graph. The graph has three parts. State is a shared snapshot of the application, usually a typed schema. Nodes are functions that read state, do work, and return updates. Edges are fixed or conditional transitions that decide the next node. Nodes do the work. Edges decide what runs next.
Graphs can have cycles. Chains cannot. That is the whole point. An agent that calls a tool, reads the result, and decides whether to call another tool needs a loop. LangGraph gives you that loop as an explicit structure you can inspect, test, and debug.
Use LangGraph when the agent needs loops, branching, multi-turn memory, human-in-the-loop steps, or several agents working together. Use a plain chain or the high-level create_agent helper when the job is a single pass with one tool call. LangGraph is free and open source. What you pay for is the model usage behind it. LangChain also offers a paid hosted deployment option, LangGraph Platform, with built-in persistence and observability.
LangGraph tutorial step 1: install and set up
Install the framework and a model provider. This tutorial uses OpenAI, but LangGraph is model-agnostic. Switching providers is a one-line change to the model constructor.
pip install langgraph langchain-openai
pip install langgraph-checkpoint-sqlite # only if you want file-based memorySet your API key as an environment variable before you run anything.
export OPENAI_API_KEY="sk-your-key-here"Check the installed version. LangGraph reached version 1.0 in late 2025 and has shipped 1.x releases since. The core graph API of state, nodes, edges, and checkpointers is stable.
LangGraph tutorial step 2: define the state
State is the shared data that nodes read and update. Define it with a TypedDict. Each key is a channel. Channels hold values and define how updates merge. Most channels use last-write-wins. A channel with a reducer combines values instead, for example by appending to a list.
from typing import Annotated, TypedDict
from langgraph.graph.message import add_messages
from langchain_core.messages import BaseMessage
class AgentState(TypedDict):
messages: Annotated[list[BaseMessage], add_messages]
llm_calls: intThe add_messages reducer appends new messages and updates existing ones by ID. Plain list addition only appends, so it cannot update a message in place during human-in-the-loop edits. LangGraph also ships a prebuilt MessagesState with a single messages key using add_messages. Subclass it to add fields of your own.
LangGraph tutorial step 3: add nodes and edges
A node is a function that takes state and returns an update. The agent node below calls the model with the message history. The tools node runs whatever tools the model requested.
from langgraph.graph import StateGraph, START, END
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o-mini")
def agent(state: AgentState):
response = model.invoke(state["messages"])
return {"messages": [response], "llm_calls": state["llm_calls"] + 1}
def route(state: AgentState):
last = state["messages"][-1]
if last.tool_calls:
return "tools"
return ENDNow wire the graph. Add the nodes, connect START to the agent, and add a conditional edge that routes to the tools node when the model asks for a tool, or ends the run when it does not.
builder = StateGraph(AgentState)
builder.add_node("agent", agent)
builder.add_node("tools", tools_node)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", route)
builder.add_edge("tools", "agent")
app = builder.compile()Compilation checks the graph structure, for example for orphaned nodes. It is also where you attach runtime options such as checkpointers. You must compile the graph before you invoke or stream it. The edge from tools back to agent is the loop. The agent runs, calls a tool, reads the result, and decides again.
LangGraph tutorial step 4: run the agent
Invoke the compiled graph with an initial state. The input schema matches the full state by default.
from langchain_core.messages import HumanMessage
result = app.invoke({
"messages": [HumanMessage(content="What is the weather in Lahore?")],
"llm_calls": 0,
})Use stream instead of invoke when you want to watch the run. Streaming yields the state update after each node. That is useful for showing progress in a user interface. Each streamed chunk is keyed by node name, so you can tell which step produced it.
LangGraph tutorial step 5: add memory with a checkpointer
By default a LangGraph agent has no memory between runs. Each invocation starts fresh. A checkpointer gives the agent persistent memory. It saves a snapshot of the graph state, called a checkpoint, at the end of every super-step. A thread is the sequence of checkpoints that share one thread ID.
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
app = builder.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": "user-123"}}
result = app.invoke({"messages": [HumanMessage(content="Hi")]}, config)Call the agent again with the same thread ID and it remembers the conversation. The checkpointer loads the thread's saved history, the reducer appends the new input, and the model sees the whole list. InMemorySaver keeps state in memory. For file-based persistence, use SqliteSaver from the langgraph-checkpoint-sqlite package. For production, use PostgresSaver from langgraph-checkpoint-postgres. Switching checkpointer is a one-line change where the agent is built.
Checkpoints also make the agent resumable. After an interrupt or a retry, the affected node runs again from the start of its function. Completed work is restored from the checkpointer, so a resumed thread skips finished steps. Design node logic so re-execution is safe. Prefer idempotency keys, upserts, or read-before-write checks for side effects.
LangGraph tutorial step 6: pause for human approval
Real agents need a human checkpoint before risky actions. LangGraph's interrupt function pauses graph execution at a specific point and waits for external input before resuming. Put the interrupt inside the node that performs the risky action, or use the human-in-the-loop pattern with an approval node that routes on the answer.
A simple pattern is a conditional edge after the agent node. If the next action is on an approved list, continue. If it is not, route to a human review node that waits. The run resumes from the checkpoint when the human answers. Nothing re-runs. The state is exactly where it stopped.
Keep the approval surface small. Ask a human to approve the action, not the reasoning. A long reasoning trace is hard to review. A concrete action, such as sending an email or running a database write, is easy to approve or reject.
Common mistakes in a first LangGraph agent
Four mistakes show up in almost every first graph. Avoid them and the framework stays simple.
- Forgetting the checkpointer. Without one, every run starts fresh and the agent has no memory. Add the checkpointer at compile time, not later.
- Skipping the thread ID. A checkpointer without a thread ID cannot find the saved state. Pass the thread ID in the run config every time.
- Putting side effects before an interrupt. The node runs again from the start after a resume. A payment or an email sent before the interrupt would run twice. Make side effects idempotent.
- One giant node. A node is a checkpoint and retry boundary. Split work that needs different recovery behaviour into separate nodes.
There is also a fast path worth knowing. The create_agent helper in langchain.agents builds a standard tool-calling agent on top of LangGraph. It replaced the older create_react_agent helper as the recommended starting point. Use it when the standard agent pattern fits. Drop to StateGraph when you need custom routing, custom state, or human-in-the-loop steps.
Bottom line
This LangGraph tutorial built a stateful agent in six steps: install, define state, add nodes and edges, run it, add a checkpointer for memory, and pause for human approval. The mental model is small. State flows through the graph. Nodes do work. Edges decide what runs next. Checkpointers remember. Start with the fast path, create_agent, and move to StateGraph when the agent needs loops, memory, or a human in the loop. Then test it on your own tools before it touches anything real.