Most agent demos are a loop: send messages to a model, run whatever tool it asks for, repeat. That works until the agent has to remember last week’s conversation, survive a deploy mid-task, or wait for a human to approve a refund. At that point you need state, and you need it to be explicit.
LangGraph is built for exactly this. Here is how I structure stateful agents with it, from the first graph to a production setup.
The examples use LangGraph 1.x and LangChain 1.x APIs. Check the current documentation for your installed versions.
The mental model: state, nodes, edges
A LangGraph agent has three parts:
- State: a typed schema shared by the whole graph. Every node reads it and returns updates.
- Nodes: plain Python functions that do one step of work, such as calling the model, running tools or asking for approval.
- Edges: the rules for what runs next. They can be fixed, or conditional on the current state.
Because routing lives in edges rather than in a prompt, you can read the agent’s control flow, test each node in isolation and change behaviour without rewriting prompts.
A tool-calling agent in about 40 lines
import os
from typing import Annotated
from typing_extensions import TypedDict
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
class State(TypedDict):
# add_messages appends new messages instead of overwriting the list
messages: Annotated[list, add_messages]
@tool
def get_order_status(order_id: str) -> str:
"""Look up the fulfilment status of an order by its public ID."""
order = Order.objects.filter(public_id=order_id).first() # your data layer
return order.status if order else "No order found with that ID."
tools = [get_order_status]
# e.g. CHAT_MODEL="openai:<model>" or "anthropic:<model>"
llm = init_chat_model(os.environ["CHAT_MODEL"]).bind_tools(tools)
def assistant(state: State) -> dict:
return {"messages": [llm.invoke(state["messages"])]}
builder = StateGraph(State)
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "assistant")
builder.add_conditional_edges("assistant", tools_condition) # tools or END
builder.add_edge("tools", "assistant")
graph = builder.compile(checkpointer=InMemorySaver())
What happens on each call:
assistantsends the conversation to the model, which either answers or requests a tool call.tools_conditionroutes totoolsif the last message contains tool calls, otherwise toEND.ToolNodeexecutes the requested tools and appends their results as tool messages.- Control returns to
assistant, which now sees the results and continues.
Memory comes from the checkpointer and the thread ID
The checkpointer saves a snapshot of the state after every step, keyed by a thread ID you supply:
config = {"configurable": {"thread_id": "customer-42"}}
graph.invoke(
{"messages": [{"role": "user", "content": "Where is order A-1001?"}]},
config,
)
reply = graph.invoke(
{"messages": [{"role": "user", "content": "And when was it shipped?"}]},
config,
)
print(reply["messages"][-1].content)
The second call knows which order “it” refers to because the thread’s state, including the earlier tool result, was restored from the checkpoint. Use a different thread ID and you get a fresh conversation. In a web app, the thread ID is usually your own conversation or ticket ID, scoped to the authenticated user.
Human-in-the-loop with interrupts
Some steps should never run on the model’s say-so. LangGraph’s interrupt() pauses the graph, saves its state and returns control to your application until a person decides:
from langgraph.types import Command, interrupt
def approve_refund(state: State) -> dict:
request = state["refund_request"]
decision = interrupt({"action": "refund", "order": request["order_id"], "amount": request["amount"]})
if decision != "approve":
return {"messages": [{"role": "assistant", "content": "The refund was not approved."}]}
issue_refund(request) # your backend enforces permissions and limits here too
return {"messages": [{"role": "assistant", "content": "Refund issued."}]}
# Later, after a staff member approves in your admin UI:
graph.invoke(Command(resume="approve"), config)
The pending decision can sit for minutes or days. Because the state is checkpointed, the graph resumes exactly where it stopped. (This example assumes a refund_request key in your state schema. Extend State with whatever structured fields your workflow needs.)
Production persistence
InMemorySaver is perfect for tests but disappears on restart and is not shared between processes. In production, use a database-backed checkpointer. With PostgreSQL:
from langgraph.checkpoint.postgres import PostgresSaver
with PostgresSaver.from_conn_string(os.environ["DATABASE_URL"]) as checkpointer:
checkpointer.setup() # creates the checkpoint tables once
graph = builder.compile(checkpointer=checkpointer)
Now any app server can continue any thread, and deploys no longer wipe conversations.
Streaming to the user
Agents can take several model and tool round-trips, so stream progress instead of making users wait:
for chunk in graph.stream(inputs, config, stream_mode="updates"):
print(chunk) # emit over Server-Sent Events or a WebSocket
For token-by-token output, use stream_mode="messages". In a Django or FastAPI backend, this is what feeds a WebSocket or Server-Sent Events response.
Production checklist
- Tools are narrow and validated. Inputs are typed, permissions are checked in the backend, and model output is treated as untrusted input.
- State is explicit. Anything the agent must remember lives in the state schema, not only in free text.
- Persistence is durable. A database checkpointer is used, with thread IDs scoped to users.
- Risky actions interrupt. Refunds, deletions and outbound messages wait for approval.
- Costs are measured. Log model calls and token usage per thread for limits and billing.
- Failures are planned for. Tool errors return useful messages and timeouts are bounded.
Stateful agents are mostly good backend engineering applied to a new kind of component. If you are planning one, take a look at my AI agent development service.