LangGraph Tutorial: Build a Stateful Agent in Python
Table of content
This langgraph tutorial shows how to build a stateful AI agent in Python by modeling execution as a graph of shared state, processing nodes, and routing edges. You compile this graph with a checkpointer so the runtime saves state snapshots at every execution boundary, enabling multi-turn memory, fault recovery, and human-in-the-loop interrupts.
Software engineers and technical leads evaluating agent architectures can use this guide to implement a working graph, configure database-backed persistence, and avoid common production security and operational pitfalls.
What is LangGraph and how does it differ from LangChain?
LangGraph is an open-source, MIT-licensed orchestration framework and runtime maintained by LangChain for building long-running, stateful AI agents without requiring LangChain’s higher-level abstractions. According to the LangGraph overview, the library is maintained under the langchain-ai GitHub organization and installs in Python via pip install -U langgraph or uv add langgraph.
While developers often pair LangGraph with LangChain components to integrate language models and tools, you do not need LangChain to use LangGraph. You can call model provider SDKs or custom Python functions directly inside your graph. When you want a prebuilt agent loop rather than a custom graph, note how the two libraries split responsibilities: in LangGraph v1, the prebuilt langgraph.prebuilt.create_react_agent helper was deprecated in favor of LangChain v1’s langchain.agents.create_agent, which runs on the LangGraph runtime and adds middleware customization.
For custom orchestration, LangGraph provides two primary APIs:
* The Graph API, which defines agents as a graph of nodes and edges using StateGraph.
* The Functional API, which defines agents inside a single function using @entrypoint and @task decorators.
How State, Nodes, and Edges work in the Graph API
In the LangGraph Graph API, agent behavior is modeled across discrete, Pregel-inspired super-steps using three core primitives: a shared State structure, Nodes that execute Python logic, and Edges that control routing. As detailed in the Graph API overview, the underlying execution algorithm is inspired by Google’s Pregel system and uses message passing across discrete super-steps. Nodes scheduled in parallel run inside the same super-step, whereas sequential nodes run in separate super-steps. Before you can execute a StateGraph, you must call .compile(), which performs structural validation (such as checking for orphaned nodes) and attaches runtime arguments like checkpointers and breakpoints.
The three Graph API components divide responsibilities cleanly: * State is a shared data structure representing the current snapshot of your application. * Nodes are functions that encode agent logic, taking the current state as input and returning state updates. * Edges are functions that inspect the state and determine which node executes next.
You can define your State schema using Python’s TypedDict, a dataclass when you need default values, or a Pydantic BaseModel when you require recursive data validation. Keep in mind that Pydantic is less performant than TypedDict or dataclass.
Each key in a LangGraph State has an independent reducer function that controls how updates from nodes are applied. If you do not specify a reducer via typing.Annotated, the default reducer overwrites the existing value with the latest node update. For conversation history, LangGraph includes a prebuilt add_messages reducer and a MessagesState class. These utilities append new messages to the state list while tracking message IDs so that existing messages are overwritten in place when updated.
Watch out for a common bug when using merging reducers such as operator.add: returning an empty list [] from a node merges that empty list into the existing list without clearing the field. To clear a field controlled by a merging reducer, you must wrap the replacement value in langgraph.types.Overwrite.
Step-by-step LangGraph agent example in Python
Building a stateful langgraph agent example in Python requires defining a typed state schema, writing node functions, connecting them in a StateGraph, and compiling the graph with a checkpointer.
Follow these steps to create and run a stateful workflow:
- Install the core library in your Python environment using
pip install -U langgraphoruv add langgraph. - Define the shared state schema using
TypedDictand attach theadd_messagesreducer viaAnnotatedso conversation history appends across turns. - Write pure Python node functions that accept the current state and return a dictionary containing only the updated keys.
- Define a conditional routing function that inspects the state snapshot and returns the name of the next node or
END. - Instantiate
StateGraph, register your nodes and edges, and compile the graph withInMemorySaver(fromlanggraph-checkpoint) for local testing. - Execute the compiled graph with a
thread_idinside the configuration dictionary so the checkpointer tracks the conversation across super-steps.
from typing import Annotated, Literal
from typing_extensions import TypedDict
from operator import add
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Overwrite
# 1. Define the State schema with independent reducers per key
class AgentState(TypedDict):
messages: Annotated[list, add_messages]
scratchpad: Annotated[list[str], add]
status: str
# 2. Define Nodes that take state and return updates
def triage_node(state: AgentState) -> dict:
last_message = state["messages"][-1].content.lower()
if "reset" in last_message:
# Use Overwrite to clear a field managed by operator.add
return {
"scratchpad": Overwrite([]),
"status": "cleared",
}
return {
"scratchpad": [f"triaged: {last_message}"],
"status": "ready",
}
def responder_node(state: AgentState) -> dict:
notes_count = len(state["scratchpad"])
reply = f"Status is '{state['status']}'. Scratchpad entries: {notes_count}."
return {"messages": [{"role": "assistant", "content": reply}]}
# 3. Define an Edge routing function
def route_after_triage(state: AgentState) -> Literal["responder", "__end__"]:
if state["status"] == "cleared":
return END
return "responder"
# 4. Build and compile the StateGraph with a checkpointer
builder = StateGraph(AgentState)
builder.add_node("triage", triage_node)
builder.add_node("responder", responder_node)
builder.add_edge(START, "triage")
builder.add_conditional_edges("triage", route_after_triage)
builder.add_edge("responder", END)
checkpointer = InMemorySaver()
graph = builder.compile(checkpointer=checkpointer)
# 5. Invoke the compiled graph on a specific thread
config = {"configurable": {"thread_id": "session-42"}}
result = graph.invoke(
{"messages": [{"role": "user", "content": "Check order status"}]},
config=config,
)
print(result["messages"][-1].content)
In this script, triage_node demonstrates how to handle merging reducers safely: when the user asks to reset, wrapping [] in Overwrite forces the scratchpad list to clear instead of merging an empty list via operator.add. Compiling the graph with InMemorySaver verifies the structure and saves a state snapshot after every super-step under thread_id "session-42".
Dynamic routing and human-in-the-loop interrupts with Command
The Command primitive from langgraph.types lets a node update graph state and dynamically route to the next node in a single return object, or resume execution after a human-in-the-loop interrupt. Instead of writing a separate conditional edge function, a node or tool can return Command(update={...}, goto="next_node") directly. When a graph pauses for human approval via interrupt(), you pass Command(resume=...) to continue execution.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt
class ApprovalState(TypedDict):
action: str
approved: bool
def review_node(state: ApprovalState) -> Command[Literal["execute", "__end__"]]:
# Pause execution and wait for human input via Command(resume=...)
decision = interrupt({"question": f"Approve action: {state['action']}?"})
if decision is True:
return Command(update={"approved": True}, goto="execute")
return Command(update={"approved": False}, goto=END)
def execute_node(state: ApprovalState) -> dict:
return {"action": f"completed: {state['action']}"}
builder = StateGraph(ApprovalState)
builder.add_node("review", review_node)
builder.add_node("execute", execute_node)
builder.add_edge(START, "review")
builder.add_edge("execute", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "approval-thread-1"}}
# Initial run pauses at interrupt() inside review_node
graph.invoke({"action": "delete_staging_db", "approved": False}, config=config)
# Resume the paused node by supplying the human decision
final_state = graph.invoke(Command(resume=True), config=config)
Three architectural rules govern Command and interrupt() in production:
* Do not mix static edges (add_edge) and Command(goto=...) routing on the same node. Command only adds dynamic edges, so if a static edge is also attached to that node, both the static destination and the dynamic destination will execute in parallel.
* Do not pass Command(update=...) alone as the input to invoke() or stream() to continue a multi-turn conversation. Passing Command(update=...) without a new starting input resumes from the latest checkpoint rather than START, which causes an already finished graph to appear stuck.
* Make any side effects placed before an interrupt() call idempotent. Because LangGraph saves checkpoints at super-step boundaries rather than mid-function inside a node, resuming a node after an interrupt or failure re-executes the node function from the beginning. If you call an external API or write to a database before calling interrupt(), that operation will run a second time when Command(resume=...) is invoked.
Memory and persistence: Checkpointers vs. Stores
LangGraph splits persistence into two complementary layers: Checkpointers that save state snapshots at every super-step for thread-scoped short-term memory, and Stores that persist application key-value data across threads for long-term memory. As documented in the LangGraph persistence guide, Checkpointers enable multi-turn conversations, human-in-the-loop interrupts, and time-travel debugging within a single thread_id, whereas Stores let your agent read and write user profiles, preferences, or shared facts that survive across separate conversation threads.
LangGraph maintains three official checkpointer families across separate packages:
| Criterion | InMemorySaver | SqliteSaver / AsyncSqliteSaver | PostgresSaver / AsyncPostgresSaver |
|---|---|---|---|
| Package name | langgraph-checkpoint |
langgraph-checkpoint-sqlite |
langgraph-checkpoint-postgres |
| Recommended environment | Testing and debugging | Local workflows | Production deployments |
| State durability across restarts | None; all state is lost when the Python process restarts | Persisted to a local SQLite file | Persisted to a PostgreSQL database |
| Concurrency & multi-instance support | Single process only | Local synchronous or asynchronous access | Production synchronous or asynchronous access |
| Known operational & security constraints | Unsuitable for production | Older versions affected by SQL injection via metadata filter keys (CVE-2025-67644, CVSS 7.3) | Requires periodic checkpoint pruning as checkpoint tables grow |
When you transition from local notebooks to a deployed service, replace InMemorySaver with PostgresSaver or AsyncPostgresSaver from langgraph-checkpoint-postgres.
Production limits, security hardening, and common pitfalls
Running a stateful LangGraph agent in production requires guarding against recursion limits, database key constraints, unredacted streaming channels, and deserialization or SQL injection vulnerabilities. Before deploying a compiled graph to user traffic, verify your configuration against four operational and security controls:
- Enforce super-step recursion bounds. In current LangGraph releases the default recursion limit is 10,007 super-steps per run (10,000 between versions 1.0.6 and 1.1.3). If an agent loop exceeds that limit, the runtime raises a
GraphRecursionErrorunless you override the ceiling by passingrecursion_limitas a top-level config key, setting theLANGGRAPH_DEFAULT_RECURSION_LIMITenvironment variable, or handle termination proactively inside your nodes usingRemainingSteps. - Validate
thread_idlengths and prune old checkpoints. You must also implement periodic checkpoint pruning so that historical super-step snapshots do not grow unboundedly in your database. - Restrict
output_keyswhen streaming private state schemas. In LangGraph, private state schemas constrain what an individual node reads and whatinvoke()returns at the end of a run. However, private schemas do not automatically redact private channels when you stream withstream_mode='values'unless you explicitly restrictoutput_keys. - Lock down checkpoint serialization and patch checkpointer packages. By default,
JsonPlusSerializerallows any Python type in checkpoint data. To prevent unsafe deserialization in new applications, the official documentation advises setting the environment variableLANGGRAPH_STRICT_MSGPACK=trueor passing an explicitallowed_msgpack_modulesallowlist. You should also keep all checkpoint packages patched and never pass untrusted user input into metadata filter keys; a disclosed vulnerability in the LangGraph SQLite checkpointer implementation (CVE-2025-67644, CVSS 7.3) allowed SQL injection via metadata filter keys.
Frequently asked questions
Here are direct answers to common architectural and operational questions when building stateful agents with LangGraph.
Is LangGraph free to use in production?
Yes, the open-source LangGraph library is distributed under the MIT License and is free to use in production. As of November 2026, while the open-source framework is free, managed observability and deployment via LangSmith are available across three pricing tiers: Developer ($0/seat per month), Plus ($39/seat per month), and Enterprise (custom pricing).
Do I need LangChain to use LangGraph?
No, you do not need to use LangChain to build or run agents with LangGraph. Although developers frequently pair LangGraph with LangChain components to connect language models and tools, LangGraph operates independently and can orchestrate raw Python functions and any third-party SDK.
Why was create_react_agent deprecated in LangGraph v1?
In LangGraph v1, langgraph.prebuilt.create_react_agent was deprecated in favor of LangChain v1’s langchain.agents.create_agent. The new create_agent implementation still runs on the LangGraph engine under the hood while adding support for middleware customization.
What is the difference between the Graph API and the Functional API in LangGraph?
The Graph API defines agents explicitly as a graph of nodes and edges using StateGraph, whereas the Functional API defines agents inside a single Python function using @entrypoint and @task decorators. Both APIs run on the same underlying persistence and checkpointing runtime.
Why do side effects repeat when resuming a paused LangGraph node?
Side effects repeat because LangGraph saves checkpoints at super-step boundaries rather than mid-function inside a node. When execution resumes after an interrupt or failure, the runtime re-executes the paused node function from the start, meaning any API calls or database writes placed before interrupt() must be idempotent.
Taking LangGraph agents to production
A working graph in a notebook is the easy part. Production agents also need durable checkpointing, idempotent side effects, approval steps, observability, and patched dependencies. If you are comparing LangGraph with other orchestrators, see our overview of multi-agent frameworks for software development. If you need help designing or shipping an agent system, our custom AI agent development team can help.