A loop asks the model “what next?” on every turn. A graph writes down the moves that are allowed (nodes do the work, edges decide what runs next, one state object threads through both) and lets the model choose inside them. That turns “please get approval for refunds” from an instruction into a topology.
The first support agent I put in front of customers issued the same $80 refund twice. The run crashed after the refund call, the retry started from the top, re-read the ticket and paid again. There was no record of where it had got to, because there was no “where”: just a while loop, eight tools and a message history the retry threw away. Drawing it as the graph above closed two holes on its own. The third, a payout safe to replay, stayed my job (step 05).
Chain, loop, graph: who decides what runs next
| Shape | Who decides | Fails when |
|---|---|---|
| Chain | you, at write time | anything must branch, retry or wait |
| Loop | the model, every turn | you need a guarantee: approval, budget, order |
| Graph | you define the options; state or the model picks one | the task is really one straight line |
These are amounts of structure, not rival philosophies. Use as much as you know in advance. Open-ended research is a loop with good tools; a refund workflow is a graph. The guide builds one step by step in Why a Graph?
Three parts: state, nodes, edges
- State
- A typed dict every node reads and returns a patch to. The framework merges the patch, which is what makes a node replayable.
- Node
- A function. Some call a model; most should not. Lookups, validation and a Stripe call are plain code: cheap, fast and testable.
- Edge
- A fixed edge always goes to the same node. A conditional edge runs a function over state and returns the next node’s name.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
ticket: str
intent: str
reply: str
def classify(state: State) -> dict:
return {"intent": intent_of(state["ticket"])} # an LLM call, or a rule
def answer(state: State) -> dict:
return {"reply": draft(state["ticket"], state["intent"])}
builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("answer", answer)
builder.add_edge(START, "classify")
builder.add_edge("classify", "answer")
builder.add_edge("answer", END)
graph = builder.compile()
LangGraph 1.2 (current on PyPI, October 2026). graph.invoke({"ticket": "where is order A-91?"}) returns the state with intent and reply filled in.
That is still a chain. It becomes a graph the moment an edge makes a decision.
The engineering lives in the edges
def where_next(state: State) -> str:
# a pure function of state: no model call, no I/O, trivially testable
if state["intent"] == "refund": return "split"
if state["intent"] == "tracking": return "shipping"
return "escalate"
builder.add_conditional_edges(
"classify", # the node we are leaving
where_next, # what decides
["split", "shipping", "escalate"], # where it may go
)
Nodes are the easy part. What decides whether an agent is trustworthy is what may follow what. Routing is now a function you can run over 200 past tickets in a unit test with no model. A reviewer sees in a diff that escalate became the default. And a refund can no longer happen from anywhere: there is one path to it, and it goes through the gate.
When routing needs the model’s judgement, put the model in a node that writes its verdict into state, and let the edge read the field. Edges stay cheap; the decision becomes a value you can log, evaluate and replay.
Four patterns you will use again and again
The fan-out reducer is the one that bites. Three nodes writing one field at the same time need a merge rule, or the last writer silently wins:
import operator
from typing import Annotated, TypedDict
class State(TypedDict):
findings: Annotated[list[str], operator.add] # concatenates: parallel-safe
risk: str # no reducer: last write wins
for check in ("fraud", "stock", "policy"):
builder.add_edge("split", check) # all three start together
builder.add_edge(check, "decide") # decide runs once, after all three
A cycle without a counter is how you get a bill. The node that retries is the node that counts:
def draft(state: State) -> dict: # the node that retries counts
return {"reply": write(state), "attempts": state["attempts"] + 1}
def after_verify(state: State) -> str:
if state["passed"]: return "done"
if state["attempts"] >= 3: return "human" # give up honestly
return "retry"
builder.add_conditional_edges("verify", after_verify,
{"done": END, "retry": "draft", "human": "escalate"})
Durability falls out of knowing what a step is
from langgraph.types import interrupt, Command
from langgraph.checkpoint.postgres import PostgresSaver
def approval_gate(state: State) -> dict:
decision = interrupt({"action": "refund", "amount_usd": state["amount"]})
return {"approved": decision == "approve"}
with PostgresSaver.from_conn_string(DB_URL) as saver:
saver.setup() # creates tables, once
graph = builder.compile(checkpointer=saver)
config = {"configurable": {"thread_id": "ticket-8412"}}
graph.invoke({"ticket": "refund my order A-91", "amount": 80}, config)
graph.get_state(config).next # ('approval_gate',)
# hours later, any process, same thread_id:
graph.invoke(Command(resume="approve"), config)
Because the graph knows its steps, the framework can save state after every node, keyed by a thread_id you choose. Crash after refund and the retry resumes after it, not at the top. Pausing for a person is the same mechanism: a checkpoint nobody has resumed yet, which can wait two days and survive a deploy. More in Checkpointers, Threads & Store.
Checkpointing means a node can run twice after a crash. Charging a card, sending mail or writing a row needs an idempotency key derived from state. This is not a LangGraph quirk: Temporal also replays a workflow’s decisions while the activities they trigger are at-least-once. It is what “resumable” costs everywhere.
Worked example: loop versus graph for the same refund
- a 900-word system prompt asks it to please get approval over $50
- “why did it refund without asking?” is a guess about turn 14
- a crash mid-run starts over
- checks run one at a time: about 6 s at 2 s each
- over $50 cannot reach
executewithout the gate - “why did it escalate?” is one line of checkpoint history
- a crash resumes at the last finished node
- checks run in parallel: about 2 s, the slowest one
The difference: “the agent usually does the right thing” becomes “the agent cannot do the wrong thing”.
Check timings are illustrative. Human approval in production LangGraph is in Human-in-the-Loop; deployment, streaming and tests in Productionising LangGraph.
Draw your first one, and know when not to
- List decisionsEvery fork is an edge; what sits between two forks is a node.
- Write the stateFour or five fields. If you cannot name them, you lack the shape.
- Make steps plain codeSave model calls for judgement.
- Gate the irreversibleMoney, email, deletes: one node.
- Checkpoint on day oneYou will want the history at the first misroute.
Skip the graph when the work is genuinely a straight line (write the three calls), when the steps are unknowable (a loop with good tools), or while you are still finding the shape: prototype as a loop, watch where it goes, then draw what you saw. Nodes that only pass state along and conditional edges with one destination mean you drew an org chart, not a workflow.
The shape outlives the framework
| Where | Pieces | Explicit? |
|---|---|---|
| LangGraph | state, nodes, edges, checkpointer | fully: the graph is the artifact you review |
| Handoff SDKs (OpenAI Agents SDK) | agents and handoffs | control passes agent to agent; no typed state |
| Role frameworks (CrewAI) | agents with roles and goals | implied by descriptions; hard to audit |
| Durable execution (Temporal, Restate, DBOS) | workflows and steps | the checkpoint half without the model half |
Explicit states, allowed transitions, capped retries and a step that waits for a human are older than LLMs; Step Functions and BPMN engines had them first. What ports is three questions: what are the nodes, what may follow what, and where does a run park when it must wait? Choosing between libraries is its own decision: see LangChain vs LlamaIndex vs LangGraph.
Given a workflow, name the nodes and edges out loud, say where the checkpoint goes, which node needs an idempotency key and where the human gate sits. Then say when you would not use a graph. “When would you not use an agent framework?” is the same question from the other side.
A run crashes right after execute charged the card, before its checkpoint was written. It resumes. What happens, and what fixes it?
The framework replays execute, because its step never completed. Without an idempotency key derived from state (say, the ticket id plus the attempt), the card is charged twice. Checkpointing makes a node resumable; only you can make it safe to run twice.
Three parallel checks each return {"findings": [...]}, but decide sees only one finding. Why?
The findings field has no reducer, so the last writer wins. Annotate it with Annotated[list[str], operator.add] and the three updates are concatenated.
Every conditional edge in your graph calls the model to choose the next node. Is it a graph?
It is a loop wearing a costume, and a slower one. Keep the model inside a node that writes its verdict into state; let the edge read that field. Then routing is testable without a model, and the decision is a value you can log and replay.
- A graph is nodes that work, edges that decide, and one state object threaded through both.
- The engineering is in the edges: pure routing functions you can test, diff and point at.
- Four patterns cover most graphs: router, fan-out and join with a reducer, guarded cycle, human checkpoint.
- Checkpoint after every node for resume and pause; add idempotency keys, because resumable is not idempotent.
- Skip it for straight lines and unknowable steps; the shape outlives whichever framework you pick.