08F.10 LangGraph Fundamentals

Agents & multimodalLesson 10 of 1722,597 words15 parts
Module 08F · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17

Lesson 08F.7 ended on a rule of thumb: a short, fixed, stateless pipeline is a chain, and anything with loops, shared state, approvals or recovery after a crash is a graph. This lesson is where the graph starts. LangGraph is a low-level library for writing a workflow as a set of nodes (ordinary Python functions), the edges between them, and one shared state that the nodes read and update. You draw the control flow in code, LangGraph runs it, and because the control flow is data rather than hidden inside if statements and while loops, the same program can be drawn, streamed step by step, paused, resumed, retried and inspected. It is also the runtime underneath LangChain's create_agent (08F.8), so everything in this lesson explains what an agent really is when you open it up.

This lesson teaches the core of the Graph API properly and completely: why a graph, how a run actually executes (super-steps), how to define state and the reducers that merge updates, how to write nodes, edges and conditional edges, how Command combines an update with a jump, how Send fans one node out over a list that is only known at run time, how input, output and private schemas work, how run-time context differs from state, how recursion limits protect you from endless loops, how to run and draw a graph, and how to write the agent loop by hand with the prebuilt ToolNode. Nearly every sample runs on your machine with no API key: the nodes are plain Python and the "model" is a fake one, and the outputs shown are what those runs printed. Persistence, human approval, subgraphs, the Functional API and deployment each get their own lesson and are only previewed here.

What you'll learn

  • Why a workflow outgrows a function, what a graph adds, and how to decide whether you need one (versus a chain, create_agent, or plain Python)
  • How LangGraph executes a graph: channels, super-steps, the plan, execute and update phases, and why two parallel nodes cannot see each other's work
  • StateGraph, START and END, compile(), invoke, and what compile() does and does not check
  • State schemas (TypedDict, dataclass, Pydantic), partial updates, the overwrite default, reducers (operator.add, custom reducers, add_messages, MessagesState, RemoveMessage, Overwrite)
  • Nodes: the signature, the three things a node may return, injected parameters (config, runtime, writer, store), async nodes, add_sequence, node options, and the re-execution rule that makes idempotent nodes essential
  • Edges: normal, conditional, entry and finish points, loops, fan-out and fan-in (three ways to join, and which one to use), defer=True, and the "do not mix static edges and Command" rule
  • Command (update plus goto), Command[Literal[...]] annotations, Command.PARENT, why Command as an input is a trap, and when to prefer conditional edges
  • Send and map-reduce: the worker's own input, reducers for the results, concurrency caps, failure behaviour and the empty-list case
  • Input, output and private schemas, and the surprise that schemas do not hide keys from stream
  • Run-time context (context_schema, Runtime) versus config["configurable"] versus state
  • Recursion limits: what counts as a step, the 10,007 default, GraphRecursionError, RemainingSteps, and max_concurrency
  • invoke, stream, batch and their async forms, the default-mode difference between invoke and stream, version="v2", and drawing a graph as Mermaid, ASCII or PNG
  • The agent loop written by hand: a model node, ToolNode, tools_condition
  • How to design a graph ("thinking in graphs"), a complete worked example, which changes are safe when threads already exist, the legacy names you will meet in old tutorials, and a pitfalls checklist with the real error messages

What you don't need

  • An API key. Every sample runs without a provider (plain-Python nodes, a fake chat model, an in-memory checkpointer where one appears), and the outputs shown are the real output of those runs. The only exceptions are two samples that call a real provider, in 7.3 and 12.3, which are labelled illustrative.
  • Checkpointers, threads, time travel and the Store. 08F.11 owns them. A checkpointer appears three times here (6.4, Part 9 and 15.1), each only to demonstrate one trap.
  • interrupt and human approval, retry policies, node caching and timeouts. 08F.12 owns them; 4.6 only names the options.
  • Subgraphs and multi-agent systems. 08F.13 owns them; 6.3 shows Command.PARENT in one small sample.
  • The Functional API (@entrypoint, @task) and the details of every stream mode. 08F.14 owns them; Part 10 shows only the first look.
  • Chat models, tools and create_agent in depth. 08F.5 and 08F.8 own them.
  • The agent loop from scratch. 08A.2 built it; Part 12 shows the same loop as a graph.

Setup

You need Python 3.11 or newer and uv; see 08F.4, Part 5 for the full project setup. langgraph alone runs on Python 3.10, but the langchain packages used in Parts 5 and 12 and in the examples need 3.11, so this course uses 3.11 or newer throughout.

bash
uv init langgraph-lab --bare --python 3.13 && cd langgraph-lab   # first time only
uv add langgraph langchain
uv add grandalf                                                  # optional: ASCII drawings of graphs (Part 10)
uv add python-dotenv langchain-openai                             # only for the two illustrative samples (7.3, 12.3)
# or: pip install langgraph langchain grandalf python-dotenv langchain-openai

No .env file is needed for the runnable samples. The two illustrative samples use the same provider keys as the earlier lessons; none of them is required to follow the lesson. Run each sample with uv run python file.py.

Versions (current at time of writing, read from PyPI on 14 November 2026; langgraph ships a patch release roughly every week, so treat these as a snapshot, and see 08F.4, 5.10 for upgrading on purpose): langgraph 1.2.22, langgraph-prebuilt 1.1.2, langgraph-checkpoint 4.3.2, langchain 1.5.0, langchain-core 1.8.0, pydantic 2.14.3 and grandalf 0.8. Every sample marked "run" in this lesson was executed on 14 November 2026 with Python 3.13.14 and the versions listed (a re-run on 18 November 2026 resolved langchain-core 1.8.2, and the outputs were unchanged), using uv run --no-project --python 3.13 --with langgraph --with langchain --with grandalf python -I sample.py. The output blocks are the real output of those runs. The docs and the package source were checked on the same day.


What you must be able to do after this lesson#

  • Build a StateGraph with nodes and edges and run it
  • Define state with reducers and explain the overwrite default
  • Write conditional edges and loops
  • Use Command to update state and jump in one return
  • Write the agent loop by hand as a graph
  • Set a recursion limit to stop runaway loops

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Why would I use a graph instead of just writing a function?" Part 1
"What is a super-step?" 1.3
"Why did my list get overwritten instead of appended?" 3.2 and 3.3
"Why does a node get a messages list and return a list of one?" 3.4
"My join node ran twice." 5.4
"My conditional edge went to a node that does not exist and nothing happened." 5.2 and 15.2
"When do I use Command and when a conditional edge?" Part 6, especially 6.5
"How do I process a list of documents in parallel?" Part 7
"What is the difference between input, output and private state?" Part 8
"Where do I put the model name or the tenant id for a run?" Part 9
"GraphRecursionError: recursion limit reached." Part 11
"How do I see what my graph looks like?" 10.4
"How is create_agent built?" Part 12
"How should I design a graph in the first place?" Part 13
"Can I change a graph that is already running in production?" 14.1
"This tutorial uses MessageGraph or config_schema." 14.2

Part 1: Why graphs, and what LangGraph is#

1.1 What breaks when a workflow outgrows a function#

Take a support workflow that a team might build in a week: read a customer's message, find the order id, look the order up, draft a reply, check the draft against a rule, redraft if it fails, and hand the case to a person after two failed drafts. In plain Python this is a function with a while loop and a few if statements, and for a first version that is exactly right. 08A.9 said so, and 08A.10, Part 8 built the smallest honest state machine for it.

The trouble starts when the requirements grow in the ways that real LLM systems do:

  • The run takes minutes or days because a person must approve a refund, and the process must survive a deploy while it waits.
  • A step fails halfway through and you want to resume from that step, not from the top, without charging the customer twice.
  • Product wants a live view of "what is it doing now", token by token and step by step.
  • Three documents must be summarized in parallel and merged, and the number of documents is only known at run time.
  • Someone asks "which path did this ticket take, and what was in memory at each step?" and the answer lives in a call stack that no longer exists.

A function can do each of these, with enough infrastructure code. A graph runtime gives them to you because of one design decision: the program is split into named steps that read and write one explicit shared state, and the runtime, not your code, moves between the steps. Once control flow is data, the runtime can draw it, stream it, checkpoint it, pause it, retry one step of it and replay it.

Concern Plain Python function A LangGraph graph
Shared data between steps Local variables, easy to lose One typed state object with a merge rule per key
Control flow if and while in code Edges and routing functions the runtime can draw and trace
Seeing progress print and logging you wrote Built-in streaming of updates, values, tokens and custom events (08F.14)
Parallel steps ThreadPoolExecutor and your own merge code Several edges out of a node; reducers merge the results
Pause for a human, resume later You build it (08A.9, Part 6) interrupt plus a checkpointer (08F.11, 08F.12)
Resume after a crash You build it Checkpoints at step boundaries
Testing one step Call the function Call the node function directly; it takes a dict and returns a dict
Cost None A new vocabulary, a runtime dependency, and a state schema to keep honest

The last row matters. LangGraph is the most code-heavy of the mainstream agent options, as 08F.1, 3.4 noted: you write the nodes, so you own their bugs. It earns its keep when at least one row above is a real requirement, and it is overkill for a two-tool FAQ bot.

1.2 What LangGraph is, and where it sits#

The official overview describes LangGraph as "a low-level orchestration framework and runtime for long-running, stateful agents". Three words in that sentence do the work:

  • Low-level. It does not give you an agent, a memory, a prompt or a model. It gives you the machinery to wire your own steps into a durable, inspectable program. Higher-level products are built on it: LangChain's create_agent (08F.8) returns a compiled LangGraph graph, and Deep Agents (surveyed in 08F.4, Part 6) sits on LangChain, which sits on LangGraph.
  • Runtime. A compiled graph is not a diagram, it is an executor. It runs your nodes, applies state updates, decides what runs next, and exposes invoke, stream, batch and their async forms.
  • Stateful and long-running. State is a first-class object, and with a checkpointer a run can outlive the process that started it.

Two clarifications prevent common confusions:

  1. LangGraph does not require LangChain. Its own docs say so, even though the examples use LangChain chat models and tools because they are convenient. A node is any Python function. You can call the OpenAI SDK, the Anthropic SDK or requests inside one. The langgraph package depends on langchain-core (for the Runnable interface and message types), but not on langchain. This lesson imports langchain only for messages and tools in Part 12.
  2. A compiled graph is a Runnable. The interface from 08F.7 applies: invoke, ainvoke, stream, astream, batch, abatch. It can be a step in a pipe, and an LCEL chain can be a node (08F.7, 10.4 ran both directions).

The packages, as 08F.4, Part 3 listed them: langgraph (the StateGraph builder and the runtime; this lesson), langgraph-prebuilt (ToolNode, tools_condition; arrives with langgraph), langgraph-checkpoint (checkpointer base classes and the in-memory saver; arrives with langgraph; 08F.11) and langgraph-sdk (the client for Agent Server, 11A.5). The licence is MIT. LangGraph 1.0 shipped on 17 October 2025 with an explicit policy of stability: the 1.0 release notes say the core graph APIs and execution model were kept unchanged, and custom StateGraph graphs, checkpointers, interrupt, Command and Send continued to work as before. The 1.1 and 1.2 minors (March and May 2026) added features, some of which appear below with their version.

1.3 How a run executes: channels and super-steps#

Before writing any code, one mental model pays for itself many times over. LangGraph runs a graph by message passing in the style of Google's Pregel system for large-scale graph processing. You never need to read that paper; what matters is the shape of the execution.

  • State lives in channels, one per state key. A channel stores a value and has an update rule: by default, the last value written wins; with a reducer, writes are combined (Part 3).
  • Execution advances in discrete super-steps. Each super-step has three phases, as the runtime docs describe them. Plan: decide which nodes run, namely the nodes triggered by channels that changed in the previous step (in the first step, the nodes fed by START). Execute: run all of those nodes in parallel, each on a snapshot of the state, until they all finish. Their writes are invisible to each other until the next step. Update: apply every node's writes to the channels, through each channel's update rule.
  • The run ends when a plan finds no node to run (every node is inactive and no messages remain), or when the recursion limit is reached (Part 11).
flowchart TD
    inp(["input written to state channels"]) --> plan1["Plan: which nodes are triggered by changed channels?"]
    plan1 -->|"none"| done(["run ends: return output"])
    plan1 -->|"some"| exec["Execute all of them in parallel, each on a snapshot of state"]
    exec --> upd["Update: apply every node's writes through the channels' reducers, all at once"]
    upd --> plan1

Nodes that run one after another are in different super-steps; nodes that run in parallel share one. A tiny graph makes this concrete. Each node reads its own step number from its config (4.3 explains how), and plan fans out to two searches that join in a merge node:

flowchart LR
    subgraph s1 ["Super-step 1"]
        plan["plan"]
    end
    subgraph s2 ["Super-step 2 (parallel)"]
        web["search_web"]
        docs["search_docs"]
    end
    subgraph s3 ["Super-step 3"]
        merge["merge"]
    end
    subgraph s4 ["Super-step 4"]
        answer["answer"]
    end
    plan --> web
    plan --> docs
    web --> merge
    docs --> merge
    merge --> answer
python
# g22_supersteps.py: which nodes share a super-step? Print the step counter from inside each node
import operator
from typing import Annotated

from langchain_core.runnables import RunnableConfig
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    steps: Annotated[list[str], operator.add]


def make(name):
    def node(state: State, config: RunnableConfig):
        step = config["metadata"]["langgraph_step"]
        return {"steps": [f"step {step}: {name}"]}
    node.__name__ = name
    return node


g = StateGraph(State)
for name in ["plan", "search_web", "search_docs", "merge", "answer"]:
    g.add_node(name, make(name))
g.add_edge(START, "plan")
g.add_edge("plan", "search_web")        # two outgoing edges from plan: both targets run in the NEXT super-step
g.add_edge("plan", "search_docs")
g.add_edge(["search_web", "search_docs"], "merge")   # wait for both
g.add_edge("merge", "answer")
g.add_edge("answer", END)

for line in sorted(g.compile().invoke({"steps": []})["steps"]):
    print(line)
Output5 lines
step 1: plan
step 2: search_docs
step 2: search_web
step 3: merge
step 4: answer

search_web and search_docs both ran in super-step 2 (the lines are sorted for display, because the order inside one super-step is not guaranteed). merge waited for both because of the list-form edge add_edge(["search_web", "search_docs"], "merge") (5.4). Four consequences of this model recur through the whole lesson:

  1. Parallel nodes do not see each other. Two nodes in the same super-step both read the state as it was before the step. Neither can use the other's result. If you need that, put them in sequence.
  2. Writes are applied together, through reducers. Two parallel nodes that write the same key need a reducer, or the run fails (3.3).
  3. A super-step is transactional. If one node in a step raises, none of that step's updates are applied. With a checkpointer, the writes of the siblings that succeeded are saved as pending writes and are not re-run on resume (08F.11).
  4. Checkpoints sit at super-step boundaries, not inside a node. This is why a node that is interrupted or retried starts again from the top of its function (4.7).

1.4 The whole API in one page#

Every LangGraph program uses the same small set of nouns. Part 2 builds a graph from them; the rest of the lesson takes each in turn.

Noun What it is Part
State The shared data: a schema (TypedDict, dataclass or Pydantic model) whose keys become channels 3
Reducer A function (current, update) -> new that says how writes to one key combine 3
Node A function that reads the state and returns a partial update (or a Command) 4
Edge A fixed transition from one node to another 5
Conditional edge A function that looks at the state and chooses the next node (or nodes) 5
START and END The virtual entry and exit nodes 2, 5
Command A return value that carries a state update and a goto together 6
Send A message that runs a node with its own input, once per item 7
Context Immutable per-run configuration (model name, tenant id) 9
compile() Turns the builder into a runnable graph 2

1.5 Do you need a graph? A decision in four questions#

08F.7, 10.2 gave the full decision diagram for chains, create_agent and graphs. This is the short version for the graph side, and 08F.1, Part 7 holds the cross-framework one.

Question If yes
Does the workflow have a loop with a condition, or a fork whose branch depends on the data? A graph (or create_agent if the model itself chooses tools)
Must the run pause for a human, survive restarts, or resume from a failed step? A graph with a checkpointer (08F.11, 08F.12)
Do several steps share and update data that you need to inspect step by step? A graph: typed state with reducers beats a dict you thread by hand
Is it one model call, or a fixed line of steps with no loop? Not a graph: use a function or an LCEL chain

Part 2: Your first graph#

2.1 Build, compile, invoke#

The minimum viable graph has a state schema, one or more nodes, edges from START and to END, and a compile() call. This one runs two steps in a row:

python
# g01_minimal.py: the smallest StateGraph
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    text: str


def node_a(state: State):
    return {"text": state["text"] + "a"}


def node_b(state: State):
    return {"text": state["text"] + "b"}


builder = StateGraph(State)
builder.add_node("node_a", node_a)
builder.add_node("node_b", node_b)
builder.add_edge(START, "node_a")
builder.add_edge("node_a", "node_b")
builder.add_edge("node_b", END)
graph = builder.compile()

print(graph.invoke({"text": ""}))
print(type(builder).__name__, "->", type(graph).__name__)
print(START, END)
# the builder is reusable: compile twice, get two independent graphs
print(builder.compile() is graph)
Output4 lines
{'text': 'ab'}
StateGraph -> CompiledStateGraph
__start__ __end__
False

Line by line:

  • from langgraph.graph import END, START, StateGraph. These three names are the front door. START and END are plain strings ("__start__" and "__end__", printed above): virtual nodes that mark where a run begins and where it ends.
  • class State(TypedDict). The state schema. Each key becomes a channel. Here there is one key, text.
  • A node is a function from state to a partial update. node_a receives the whole state (a dict) and returns a dict containing only the keys it changes. It does not mutate state, and it does not return the whole state. LangGraph applies the update.
  • StateGraph(State) creates a builder. Nothing runs yet. add_node("node_a", node_a) registers a node under a name; add_edge(START, "node_a") says the first node to run is node_a; add_edge("node_a", "node_b") and add_edge("node_b", END) finish the line.
  • .compile() validates the structure and returns a CompiledStateGraph, the thing you run. The builder and the compiled graph are different objects (StateGraph -> CompiledStateGraph above), and compiling twice gives two independent graphs (False on the last line). Calling builder.invoke(...) is a common beginner error; it raises AttributeError: 'StateGraph' object has no attribute 'invoke' (15.1).
  • graph.invoke({"text": ""}) runs the graph to completion and returns the final state: {'text': 'ab'}.

Every builder method returns the builder, so the whole definition can be chained, which is how the official docs often write it:

python
graph = (
    StateGraph(State)
    .add_node("node_a", node_a)
    .add_node("node_b", node_b)
    .add_edge(START, "node_a")
    .add_edge("node_a", "node_b")
    .add_edge("node_b", END)
    .compile()
)

That fragment is the same graph, written as one expression.

2.2 What compile() does, and its signature#

compile() is where the builder becomes a runtime object. The signature, read from the source of 1.2.22, with the options that later lessons teach:

text
compile(
    checkpointer=None,        # persistence: 08F.11
    *,
    cache=None,               # node caching: 08F.12
    store=None,               # cross-thread memory: 08F.11
    interrupt_before=None,    # static breakpoints: 08F.12
    interrupt_after=None,
    debug=False,
    name=None,                # the graph's name; default "LangGraph"
    transformers=None,        # event-stream transformers: 08F.14
) -> CompiledStateGraph

Three facts to carry:

  • You must compile before you run. The builder has no invoke.
  • name becomes the graph's name in traces and in the drawing. When one graph is a node of another, or several agents cooperate, give each a unique, meaningful name (08F.13). Part 13's sample passes name="support_triage".
  • A compiled graph is a Runnable (1.2): invoke, ainvoke, stream, astream, batch, abatch, get_graph() and the rest. It is also a Pregel instance, the runtime class from 1.3.

2.3 What compile() rejects, and what it lets through#

add_node, add_edge and compile() check the structure, but less than you might expect. This sample tries eight mistakes and prints what each does:

python
# g02_compile_errors.py: what add_node, add_edge and compile() reject, and what they let through
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    text: str


def a(state: State):
    return {"text": "a"}


def b(state: State):
    return {"text": "b"}


def attempt(label, fn):
    try:
        result = fn()
        print(f"{label}: OK ->", result)
    except Exception as e:  # noqa: BLE001
        print(f"{label}: {type(e).__name__}: {str(e).splitlines()[0]}")


# 1. no edge from START
def no_entry():
    return StateGraph(State).add_node("a", a).compile()


# 2. an edge to a node that does not exist
def unknown_target():
    return StateGraph(State).add_node("a", a).add_edge(START, "a").add_edge("a", "ghost").compile()


# 3. duplicate node name
def duplicate():
    return StateGraph(State).add_node("a", a).add_node("a", b)


# 4. reserved and forbidden names
def reserved():
    return StateGraph(State).add_node("__start__", a)


def colon():
    return StateGraph(State).add_node("step:one", a)


def pipe():
    return StateGraph(State).add_node("step|one", a)


# 5. a node that is not connected to anything: does compile() notice?
def orphan():
    g = StateGraph(State).add_node("a", a).add_node("lonely", b)
    g.add_edge(START, "a").add_edge("a", END)
    graph = g.compile()
    return graph.invoke({"text": ""})


# 6. a graph with no path to END: compiles, and just stops when no node is active
def no_end():
    g = StateGraph(State).add_node("a", a).add_edge(START, "a")
    return g.compile().invoke({"text": ""})


for label, fn in [
    ("no edge from START", no_entry),
    ("edge to unknown node", unknown_target),
    ("duplicate name", duplicate),
    ("reserved name", reserved),
    ("colon in name", colon),
    ("pipe in name", pipe),
    ("orphan node", orphan),
    ("no path to END", no_end),
]:
    attempt(label, fn)
Output8 lines
no edge from START: ValueError: Graph must have an entrypoint: add at least one edge from START to another node
edge to unknown node: ValueError: Found edge ending at unknown node `ghost`
duplicate name: ValueError: Node `a` already present.
reserved name: ValueError: Node `__start__` is reserved.
colon in name: ValueError: ':' is a reserved character and is not allowed in the node names.
pipe in name: ValueError: '|' is a reserved character and is not allowed in the node names.
orphan node: OK -> {'text': 'a'}
no path to END: OK -> {'text': 'a'}
Mistake What happens
No edge from START compile() raises ValueError: Graph must have an entrypoint...
An edge to or from a node that does not exist compile() raises ValueError: Found edge ending at unknown node ...
Registering a node name twice add_node raises ValueError: Node ... already present.
A node named __start__ or __end__ add_node raises ValueError: ... is reserved.
A : or ` ` in a node name
A node with no edges at all (an orphan) Nothing. It compiles and the node simply never runs
No path to END Nothing. The run ends when no node is active; END is optional

A related, easy-to-miss rule: every node name you reference in an edge must have been added, and the check happens at compile(), not at add_edge, so the order in which you call builder methods does not matter. You can add edges before the nodes they point to, as long as everything exists by the time you compile.


Part 3: State, channels and reducers#

State is the heart of a graph. Every node reads it, every node writes it, and the rules for how writes combine decide whether your graph is correct. This part is the one to read slowly.

3.1 Three kinds of schema#

The state schema is the first argument of StateGraph. It can be a TypedDict, a dataclass or a Pydantic BaseModel. The run below uses all three with the same node shape and shows what each one does with input:

python
# g03_state_types.py: TypedDict, dataclass and Pydantic state, and what each does with bad input
from dataclasses import dataclass, field

from pydantic import BaseModel
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


def build(schema, node):
    return (
        StateGraph(schema)
        .add_node("work", node)
        .add_edge(START, "work")
        .add_edge("work", END)
        .compile()
    )


# TypedDict: no validation, no defaults, plain dicts in and out
class TD(TypedDict):
    count: int


def td_node(state: TD):
    return {"count": state["count"]}  # echo, so wrong types are visible


td = build(TD, td_node)
print("TypedDict   :", td.invoke({"count": 1}))
print("TypedDict   : wrong type passes silently ->", td.invoke({"count": "not a number"}))
print("TypedDict   : unknown input key ->", td.invoke({"count": 1, "extra": True}))


# dataclass: defaults, attribute access in nodes
@dataclass
class DC:
    count: int = 0
    notes: list[str] = field(default_factory=list)


def dc_node(state: DC):
    return {"count": state.count + 1}


def dc_instance_node(state: DC):
    return DC(count=state.count + 1)  # returning an instance of the state class


dc = build(DC, dc_node)
print("dataclass   : returns an instance ->", build(DC, dc_instance_node).invoke({"count": 1}))
print("dataclass   :", dc.invoke({"count": 1}))
print("dataclass   : default used ->", dc.invoke({}))


# Pydantic: validation (and coercion) on the input of the first node
class PD(BaseModel):
    count: int


def pd_node(state: PD):
    print("   node sees", type(state).__name__, repr(state))
    return {"count": state.count + 1}


pd = build(PD, pd_node)
out = pd.invoke({"count": 1})
print("pydantic    : output type ->", type(out).__name__, out)
print("pydantic    : '42' is coerced ->", pd.invoke({"count": "42"}))
try:
    pd.invoke({"count": "forty-two"})
except Exception as e:  # noqa: BLE001
    print("pydantic    :", type(e).__name__, "-", str(e).splitlines()[0])

# version="v2" gives back the model instead of a dict
out2 = pd.invoke({"count": 1}, version="v2")
print("pydantic v2 :", type(out2).__name__, "| value type:", type(out2.value).__name__)
Output13 lines
TypedDict   : {'count': 1}
TypedDict   : wrong type passes silently -> {'count': 'not a number'}
TypedDict   : unknown input key -> {'count': 1}
dataclass   : returns an instance -> {'count': 2, 'notes': []}
dataclass   : {'count': 2}
dataclass   : default used -> {'count': 1}
   node sees PD PD(count=1)
pydantic    : output type -> dict {'count': 2}
   node sees PD PD(count=42)
pydantic    : '42' is coerced -> {'count': 43}
pydantic    : ValidationError - 1 validation error for PD
   node sees PD PD(count=1)
pydantic v2 : GraphOutput | value type: PD
TypedDict dataclass Pydantic BaseModel
A node receives A plain dict (state["count"]) A dataclass instance (state.count) A model instance (state.count)
Defaults None: a key nobody wrote is simply absent Yes (count: int = 0, field(default_factory=list)) Yes
Validation of input None: "not a number" passed straight through None by LangGraph Yes, on the input to the first node only; "42" was coerced to 42, "forty-two" raised ValidationError
What invoke returns A dict A dict A dict by default (pydantic: output type -> dict); with version="v2", a GraphOutput whose .value is the model
Speed Fastest Fast Slower (recursive validation)

The docs' advice is to prefer TypedDict or dataclass for performance and to reach for Pydantic only when you need validation of untrusted input. Know the limits of the Pydantic path before you choose it, because they surprise people:

  • Validation runs on the graph input only. A node that returns a wrongly typed update is not validated on its way into state.
  • The validation error traceback does not say which node was involved.
  • Pydantic coerces ("42" becomes 42), which can hide bugs; use strict types if you want rejection.
  • In message fields, annotate list[AnyMessage], not list[BaseMessage], so messages deserialize to the right classes.
  • create_agent state schemas must be TypedDict; Pydantic and dataclass state are not supported there (08F.8).

Two more schema facts, both seen in the run above. Unknown input keys are ignored by a TypedDict graph ({"count": 1, "extra": True} returned just count). And a key that is declared but never written is absent, not None; a node that reads state["note"] for a key nobody set gets a KeyError (15.1). Declare optional keys with NotRequired[...] and read them with state.get("note"). NotRequired is also the right way to add a key to a schema later without breaking saved threads (14.1).

3.2 Partial updates and the overwrite default#

A node returns only the keys it changes. LangGraph applies each returned key to its channel using that key's update rule. With no reducer, the rule is last write wins: the new value replaces the old one.

python
class State(TypedDict):
    plan: str                  # no reducer: overwritten by every write
    log: list[str]             # no reducer either: ALSO overwritten, not appended

def step(state: State):
    return {"log": ["step ran"]}   # replaces the whole list, wiping earlier entries

This is the single most common state bug for newcomers: a node returns {"log": ["step ran"]} and the history disappears, because a list without a reducer is just a value. To accumulate, you need a reducer.

3.3 Reducers: how concurrent and repeated writes merge#

A reducer is a binary function reducer(current_value, update) -> new_value. You attach it to a key with typing.Annotated. Each key has its own reducer, and keys without one overwrite.

The next sample defines four kinds of key in one state: an overwrite key, an appending list (operator.add), a custom dict-merging reducer and a custom max reducer. It then makes two parallel nodes write the same key, and shows how to clear a reduced list:

python
# g04_reducers.py: overwrite vs reducers, custom reducers, parallel writes, Overwrite
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.errors import InvalidUpdateError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Overwrite


# --- a custom reducer: merge dicts, newer keys win ------------------------
def merge_dicts(left: dict, right: dict) -> dict:
    return {**left, **right}


# --- a numeric reducer: the channel starts at int() == 0, so max works from step one --
def keep_max(left: int, right: int) -> int:
    return max(left, right)


class State(TypedDict):
    plain: str                                   # no reducer: last write wins
    log: Annotated[list[str], operator.add]      # append
    facts: Annotated[dict, merge_dicts]          # merge
    best: Annotated[int, keep_max]               # maximum so far


def first(state: State):
    return {"plain": "one", "log": ["first ran"], "facts": {"a": 1}, "best": 3}


def second(state: State):
    return {"plain": "two", "log": ["second ran"], "facts": {"b": 2, "a": 9}, "best": 2}


g = StateGraph(State)
g.add_node("first", first)
g.add_node("second", second)
g.add_edge(START, "first")
g.add_edge("first", "second")
g.add_edge("second", END)
graph = g.compile()
print(graph.invoke({"plain": "", "log": [], "facts": {}, "best": 0}))
# the input is a write too: it goes through the reducer, and omitted keys are fine
print(graph.invoke({"log": ["from input"], "facts": {"z": 0}}))


# --- two parallel nodes write the same key ---------------------------------
class Clash(TypedDict):
    answer: str


def left(state: Clash):
    return {"answer": "left"}


def right(state: Clash):
    return {"answer": "right"}


c = StateGraph(Clash)
c.add_node("left", left)
c.add_node("right", right)
c.add_edge(START, "left")
c.add_edge(START, "right")
c.add_edge("left", END)
c.add_edge("right", END)
try:
    c.compile().invoke({"answer": ""})
except InvalidUpdateError as e:
    print("InvalidUpdateError:", str(e).splitlines()[0])


# --- clearing a reduced field ---------------------------------------------
class Errs(TypedDict):
    errors: Annotated[list[str], operator.add]


def add_error(state: Errs):
    return {"errors": ["boom"]}


def try_clear(state: Errs):
    return {"errors": []}          # merges: [boom] + [] = [boom]


def really_clear(state: Errs):
    return {"errors": Overwrite([])}


for clearer in (try_clear, really_clear):
    e = StateGraph(Errs)
    e.add_node("add_error", add_error)
    e.add_node("clearer", clearer)
    e.add_edge(START, "add_error")
    e.add_edge("add_error", "clearer")
    e.add_edge("clearer", END)
    print(clearer.__name__, "->", e.compile().invoke({"errors": []}))
Output5 lines
{'plain': 'two', 'log': ['first ran', 'second ran'], 'facts': {'a': 9, 'b': 2}, 'best': 3}
{'plain': 'two', 'log': ['from input', 'first ran', 'second ran'], 'facts': {'z': 0, 'a': 9, 'b': 2}, 'best': 3}
InvalidUpdateError: At key 'answer': Can receive only one value per step. Use an Annotated key to handle multiple values.
try_clear -> {'errors': ['boom']}
really_clear -> {'errors': []}

Read the output in order:

  1. First line. plain is 'two' (the second node overwrote the first). log has both entries (operator.add concatenates lists). facts merged to {'a': 9, 'b': 2}: the second node's a won because {**left, **right} puts the right-hand dict last. best is 3 because max(3, 2).
  2. Second line. The input is a write too. {"log": ["from input"], "facts": {"z": 0}} went through the reducers, so from input came first and z merged in. Keys omitted from the input are fine; the int channel started at 0 (the type's default), which is why keep_max(left, right) needed no special first-call case.
  3. InvalidUpdateError. Two nodes in one super-step wrote the same un-reduced key answer. LangGraph cannot pick a winner and raises At key 'answer': Can receive only one value per step. Use an Annotated key to handle multiple values. The fix is exactly what the message says: give the key a reducer. This is the error you meet when you add a second parallel branch to a graph that was working.
  4. Clearing a reduced list. Returning {"errors": []} from a node did not clear the list: [] merged into ['boom'] gave ['boom']. Wrapping the value in Overwrite([]) bypassed the reducer and gave [].

The shape of a good reducer:

Requirement Why
Takes (left, right) and returns a value of the same type The runtime calls it once per write, left to right
Does not mutate left Return a new object (left + right, {**left, **right}), or checkpoints and parallel branches will share mutable state
Works when several writes arrive in one super-step The runtime applies them one after another, in an order that is not guaranteed; prefer reducers that do not care about order (sum, set union, max), or sort afterwards (7.2)
Fast It runs on every write; a reducer that deduplicates a growing list is quadratic

The built-in reducers you will use constantly:

Reducer What it does Typical key
operator.add Concatenates lists (and adds numbers) log, results, errors, documents
add_messages Appends messages, replaces same-id messages, honours RemoveMessage (3.4) messages
A function you write Anything: merge dicts, keep the max, keep the top five, dedupe by id facts, best_score, candidates

3.4 Messages: add_messages, MessagesState and RemoveMessage#

Chat-style graphs need a key that holds the conversation. A plain operator.add would append, which is almost right, but the conversation has two extra needs: replacing a message (a human edits what the model wrote) and deleting messages (trimming history). add_messages is the reducer designed for this:

python
from typing import Annotated
from langchain.messages import AnyMessage
from langgraph.graph.message import add_messages

class State(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]

Because this exact declaration is needed by nearly every agent graph, LangGraph ships it prebuilt as MessagesState; you extend it with your own keys by subclassing. The sample calls add_messages directly (it is an ordinary function) to show each rule, then uses MessagesState in a graph, and finally trims history with RemoveMessage:

python
# g05_messages.py: add_messages, MessagesState, same-id replacement, RemoveMessage
from langchain.messages import AIMessage, HumanMessage, RemoveMessage
from langgraph.graph import END, START, MessagesState, StateGraph, add_messages
from langgraph.graph.message import REMOVE_ALL_MESSAGES

# 1. add_messages is an ordinary function: call it directly to see the rules
history = [HumanMessage(content="Hi", id="m1"), AIMessage(content="Hello!", id="m2")]

appended = add_messages(history, [HumanMessage(content="Where is my order?", id="m3")])
print("append       :", [(m.type, m.content) for m in appended])

replaced = add_messages(history, [HumanMessage(content="Hi there", id="m1")])  # same id
print("same id      :", [(m.id, m.content) for m in replaced])

removed = add_messages(history, [RemoveMessage(id="m1")])
print("RemoveMessage:", [(m.id, m.content) for m in removed])

cleared = add_messages(history, [RemoveMessage(id=REMOVE_ALL_MESSAGES), HumanMessage(content="Fresh start", id="n1")])
print("remove all   :", [(m.id, m.content) for m in cleared])

shorthand = add_messages([], [{"role": "user", "content": "dict shorthand"}, ("ai", "tuple shorthand"), "plain string"])
print("shorthand    :", [(type(m).__name__, m.content, bool(m.id)) for m in shorthand])


# 2. MessagesState, extended with one more key
class State(MessagesState):
    ticket_id: str


def reply(state: State):
    last = state["messages"][-1].content
    return {"messages": [AIMessage(content=f"Looking into: {last}")]}  # a list of ONE new message: it is appended


graph = (
    StateGraph(State)
    .add_node("reply", reply)
    .add_edge(START, "reply")
    .add_edge("reply", END)
    .compile()
)
result = graph.invoke({"messages": [{"role": "user", "content": "Order A-1042 is late"}], "ticket_id": "T-7"})
print("graph result :", [(m.type, m.content) for m in result["messages"]], result["ticket_id"])
print("types        :", [type(m).__name__ for m in result["messages"]])


# 3. a node that trims old messages by returning RemoveMessage objects
def trim(state: MessagesState):
    old = state["messages"][:-2]
    return {"messages": [RemoveMessage(id=m.id) for m in old]}


trimmer = StateGraph(MessagesState).add_node("trim", trim).add_edge(START, "trim").add_edge("trim", END).compile()
msgs = [HumanMessage(content=f"turn {i}", id=f"id{i}") for i in range(5)]
print("after trim   :", [m.content for m in trimmer.invoke({"messages": msgs})["messages"]])
Output8 lines
append       : [('human', 'Hi'), ('ai', 'Hello!'), ('human', 'Where is my order?')]
same id      : [('m1', 'Hi there'), ('m2', 'Hello!')]
RemoveMessage: [('m2', 'Hello!')]
remove all   : [('n1', 'Fresh start')]
shorthand    : [('HumanMessage', 'dict shorthand', True), ('AIMessage', 'tuple shorthand', True), ('HumanMessage', 'plain string', True)]
graph result : [('human', 'Order A-1042 is late'), ('ai', 'Looking into: Order A-1042 is late')] T-7
types        : ['HumanMessage', 'AIMessage']
after trim   : ['turn 3', 'turn 4']

The rules, from the output:

  • Append. New messages with new ids are added to the end.
  • Same id replaces. HumanMessage(content="Hi there", id="m1") replaced the earlier m1 in place. This is what lets a human-in-the-loop edit update a message instead of duplicating it (08F.12).
  • RemoveMessage(id=...) deletes that message. RemoveMessage(id=REMOVE_ALL_MESSAGES) (import the constant from langgraph.graph.message) clears the list, and messages after it in the same update are kept (Fresh start).
  • Shorthands are accepted and converted. A dict {"role": "user", "content": "..."}, a tuple ("ai", "...") and a bare string all became HumanMessage or AIMessage objects, and every message got an id (the True column), generated if you did not supply one. The types line of the graph run shows the same conversion for the input.
  • A node returns a list with only its new messages, and they are appended: {"messages": [AIMessage(...)]}. A node that returned the whole history would duplicate it (the ids match, so replacement semantics usually save you, but do not rely on it).

Importing: add_messages and MessagesState come from langgraph.graph; the message classes and RemoveMessage come from langchain.messages (from langchain.messages import AIMessage, HumanMessage, RemoveMessage), as 08F.5, Part 3 showed.

3.5 Overwrite and resetting a field#

When a key has a merging reducer, you sometimes need to replace the value rather than merge into it: clear an error list after recovery, reset a counter, swap a whole message history. Wrap the new value in Overwrite:

python
from langgraph.types import Overwrite

def clear_errors(state):
    return {"errors": Overwrite([])}

The rules, from the docs: Overwrite bypasses the reducer for that write; a JSON form {"__overwrite__": [...]} also works (useful where a node's output is serialized); only one node may Overwrite a given key in a single super-step (otherwise InvalidUpdateError); and an Overwrite discards the other nodes' regular updates to that key in the same step. In the run above, Overwrite([]) cleared the list where [] could not.

3.6 Which schema, which reducer#

You need Use
A short workflow with a few typed fields and no validation TypedDict, overwrite keys
Defaults, and attribute access in nodes dataclass
Validation of what callers send in Pydantic for the input schema (Part 8), TypedDict for the internal state
A list that grows over the run (log, results, errors, documents) Annotated[list[T], operator.add]
A conversation MessagesState, or your own key with add_messages
Several parallel nodes writing one key A reducer that does not depend on order (sum, union, max), or write to separate keys and combine in the join node
The "best so far" of something A custom reducer (max, or a function that compares)
A value you may need to reset A reducer plus Overwrite where you reset it

Part 4: Nodes#

4.1 What a node is#

A node is a function that takes the state and returns an update. LangGraph wraps it as a RunnableLambda (08F.7, 3.3), so it is traced, can be sync or async, and can be a function, a method, a lambda, any Runnable (an LCEL chain) or a compiled graph (a subgraph, 08F.13). Because it is just a function, you can unit-test a node by calling it with a dict and checking the dict it returns, with no graph and no model involved. That property is one of LangGraph's best qualities for testing (11A.5).

Adding a node, in the two forms:

python
builder.add_node("classify", classify)     # explicit name
builder.add_node(classify)                 # the function's __name__ becomes the node name

The name is how you refer to the node in edges, in Command(goto=...), in Send, in streams ({'classify': {...}}) and in traces, so choose names you can read in a trace at two in the morning. Names must be unique, cannot be __start__ or __end__, and cannot contain : or | (2.3).

4.2 What a node may return#

The next sample runs six different return values through the same one-node graph, then shows how config and runtime are injected, what happens with a wrong annotation, how a node gets its default name, how async nodes work and how add_sequence wires a chain of steps:

python
# g06_nodes.py: node signatures, return types, injected parameters, async nodes, add_sequence
import asyncio
import warnings

from langchain_core.runnables import RunnableConfig
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime


class State(TypedDict, total=False):
    n: int
    seen: str


def attempt(label, fn):
    try:
        print(f"{label}: OK ->", fn())
    except Exception as e:  # noqa: BLE001
        print(f"{label}: {type(e).__name__}: {str(e).splitlines()[0]}")


def run(node, init=None):
    g = StateGraph(State).add_node("node", node).add_edge(START, "node").add_edge("node", END)
    return g.compile().invoke(init or {"n": 1})


# --- what a node may return -----------------------------------------------
attempt("returns a dict   ", lambda: run(lambda s: {"n": s["n"] + 1}))
attempt("returns None     ", lambda: run(lambda s: None))
attempt("returns {} ", lambda: run(lambda s: {}))
attempt("returns a string ", lambda: run(lambda s: "done"))
attempt("returns a list   ", lambda: run(lambda s: [1, 2]))
attempt("unknown key      ", lambda: run(lambda s: {"nope": 1}))


# --- injected parameters: by NAME and annotation -------------------------------
def with_config(state: State, config: RunnableConfig):
    md = config["metadata"]
    return {"seen": f"node={md['langgraph_node']} step={md['langgraph_step']}"}


def with_runtime(state: State, runtime: Runtime):
    return {"seen": f"runtime has: {sorted(a for a in ('context', 'store', 'stream_writer', 'execution_info') if hasattr(runtime, a))}"}


attempt("config injected  ", lambda: run(with_config))
attempt("runtime injected ", lambda: run(with_runtime))


def wrong_annotation(state: State, config: dict):     # not RunnableConfig: not injected
    return {"seen": "ran"}


with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    attempt("config: dict     ", lambda: run(wrong_annotation))
print("  warnings:", [str(w.message)[:90] for w in caught])


# --- node names: default to the function name --------------------------------
def classify(state: State):
    return {"n": 10}


g = StateGraph(State).add_node(classify).add_edge(START, "classify").add_edge("classify", END)
print("auto-named node:", sorted(g.compile().get_graph().nodes))

# --- async nodes -------------------------------------------------------------------
async def fetch(state: State):
    await asyncio.sleep(0)
    return {"n": state["n"] + 100}


ag = StateGraph(State).add_node("fetch", fetch).add_edge(START, "fetch").add_edge("fetch", END).compile()
print("ainvoke        :", asyncio.run(ag.ainvoke({"n": 1})))
try:
    ag.invoke({"n": 1})
except Exception as e:  # noqa: BLE001
    print("invoke on async node:", type(e).__name__, "-", str(e)[:100])


# --- add_sequence --------------------------------------------------------------------
def step_1(state: State):
    return {"n": state["n"] + 1}


def step_2(state: State):
    return {"n": state["n"] * 10}


def step_3(state: State):
    return {"n": state["n"] - 5}


b = StateGraph(State).add_sequence([step_1, step_2, step_3])
b.add_edge(START, "step_1")       # add_sequence does not add the entry edge
b.add_edge("step_3", END)         # nor the exit edge
print("add_sequence   :", b.compile().invoke({"n": 1}))
Output15 lines
returns a dict   : OK -> {'n': 2}
returns None     : OK -> {'n': 1}
returns {} : OK -> {'n': 1}
returns a string : InvalidUpdateError: Expected dict, got done
returns a list   : InvalidUpdateError: Expected dict, got [1, 2]
unknown key      : OK -> {'n': 1}
config injected  : OK -> {'n': 1, 'seen': 'node=node step=1'}
runtime injected : OK -> {'n': 1, 'seen': "runtime has: ['context', 'execution_info', 'store', 'stream_writer']"}
config: dict     : TypeError: wrong_annotation() missing 1 required positional argument: 'config'
  warnings: ["The 'config' parameter should be typed as 'RunnableConfig' or 'RunnableConfig | None', not"]
auto-named node: ['__end__', '__start__', 'classify']
ainvoke        : {'n': 101}
invoke on async node: TypeError - No synchronous function provided to "fetch".
Either initialize with a synchronous function or invoke
add_sequence   : {'n': 15}
A node returns Result
A dict of updates Each key is applied through its channel
None (or {}) No update; the state is unchanged. Use this for nodes that only have side effects or only log
A Command An update and/or a jump (Part 6)
An instance of the state class Accepted when the schema is a dataclass (the returns an instance line in the 3.1 sample: the result was {'count': 2, 'notes': []}); the docs describe this for typed state generally
A string, a list or anything else InvalidUpdateError: Expected dict, got done
A dict with a key that is not in the schema Silently ignored (the unknown key line: the graph returned {'n': 1} with no error)

Return updates, never mutate. The docs say a node should return updates "directly, instead of mutating the state". 15.1 shows what in-place mutation does: part of it appears to work (a list that two places share), part is silently lost, and none of it appears in the stream. With a checkpointer the returned value and the saved state even disagree (the short check after the table in 15.1, a preview of 08F.11).

4.3 Injected parameters: config, runtime, writer, store#

The first positional parameter of a node is always the state. A node may declare more parameters, and LangGraph injects them by name and annotation:

Parameter name Annotation that works What you get
config RunnableConfig (or RunnableConfig | None, or none) The call's config: tags, metadata, configurable (thread_id lives here), recursion_limit
runtime Anything (usually Runtime[ContextSchema]) A Runtime: context, store, stream writer, execution info (Part 9)
writer StreamWriter A function that emits custom stream events (08F.14)
store BaseStore (or optional) The long-term memory store passed to compile(store=...) (08F.11)
previous Functional API only
error NodeError Error handlers only (08F.12)

The sample showed the two you use most. config["metadata"] carries langgraph_node and langgraph_step (the super-step number, used in 1.3 and Part 11), plus langgraph_triggers, langgraph_path and langgraph_checkpoint_ns. And the parameters must be positional-or-keyword or keyword-only.

4.4 Async nodes#

Write a node as async def when it awaits I/O, and run the graph with ainvoke or astream. LangGraph awaits the node. The sample shows the two traps:

  • An async def node works under ainvoke ({'n': 101}).
  • The same graph under invoke fails: TypeError: No synchronous function provided to "fetch". A graph with async nodes must be run asynchronously (or give the node a sync twin by passing a RunnableLambda(func, afunc=...)).

Mixed graphs, with some sync and some async nodes, are fine under ainvoke: sync nodes run in a worker thread. Python 3.11 or newer is required for token streaming and get_stream_writer() in async code (a detail of 08F.14).

4.5 add_sequence#

A straight line of steps is common enough to have a shortcut. add_sequence([a, b, c]) adds the nodes and the edges between them, in order, named after the functions (or as (name, function) pairs). It does not add the edge from START, so you still write add_edge(START, first_name). The last line of the sample ran it: step_1 (n + 1), step_2 (n * 10) and step_3 (n - 5) took 1 to 15. The method was added in langgraph 0.2.46 and is still current.

4.6 Node options, previewed#

add_node accepts more than a name and a function. The signature, read from the source of 1.2.22:

text
add_node(
    node, action=None, *,
    defer=False,                # run this node only when no other work is pending: 5.4
    metadata=None,              # extra metadata for tracing
    input_schema=None,          # a narrower input type for this node: Part 8
    retry_policy=None,          # retry on exceptions: 08F.12
    cache_policy=None,          # cache the node's result: 08F.12
    error_handler=None,         # a handler node for failures (langgraph >= 1.2): 08F.12
    destinations=None,          # drawing only: names a node may jump to: 6.1
    timeout=None,               # seconds or a TimeoutPolicy; async nodes only (langgraph >= 1.2): 08F.12
    trace_policy=None,
)

The deprecated spellings retry= and input= still work with a warning (14.2). timeout and error_handler are Python-only features of the 1.2 line (the release notes say retry policies work in the JavaScript package too, but timeouts and error handlers do not). Everything on this list except defer, input_schema and destinations is the subject of 08F.12, and the lesson does not teach it here.

4.7 Re-execution and idempotency: the rule behind every durable node#

With a checkpointer, LangGraph saves a checkpoint at each super-step boundary, not in the middle of a node. So if a node is interrupted (for human approval) or retried (after an exception), it runs again from the first line of its function, and any side effect before the pause runs again. This is the central design rule for production nodes, and it is the same rule as 08A.9, 6.2 and 03.8: make the work idempotent.

python
def issue_refund(state):
    # BAD: if this node is retried after the API call succeeded, the customer is refunded twice
    payments.refund(state["order_id"], state["amount"])
    return {"refunded": True}

def issue_refund_safely(state):
    # GOOD: an idempotency key makes the second call a no-op
    payments.refund(state["order_id"], state["amount"], idempotency_key=f"refund-{state['order_id']}")
    return {"refunded": True}

The Graph API docs give a table for choosing the right unit of work, which is worth knowing even before you meet persistence:

Unit Own checkpoint? On resume or retry Choose it when
A plain function called inside a node No, it runs inside the node's super-step Re-runs whenever the node re-runs No routing fork follows, and repeating it is harmless
A task (Functional API, 08F.14) No new graph checkpoint; the result is stored with the parent's The enclosing node replays, and completed tasks return their stored result The step has side effects or is expensive and must not repeat
A subgraph (08F.13) Yes, in stateful modes Resumes inside the subgraph at the failed node The unit has its own routing or state schema, or several graphs reuse it
A graph node Yes: a checkpoint follows its super-step Resume starts at that node; earlier nodes do not re-run A routing fork follows the step, or you need an interrupt, resume or time-travel boundary

The practical reading: make a side effect its own node if it is irreversible (send the email, charge the card) and put the decision before it. Then the checkpoint after the decision protects you from deciding twice, and the effect node, if retried, uses an idempotency key. 08F.12 builds this out with approvals.

4.8 Nodes that call chains, models and other graphs#

The typical node in an LLM graph is three lines: read the state, call a model or a chain, return the update. The chain from 08F.7 fits naturally (draft_chain.invoke({...}) inside the node, as Part 13 does), and 08F.7's s28_node_with_chain.py showed how to pass the node's config into the chain call so the traces link. As a rule: nodes are for steps that change state or choose a route, and chains are for the language work inside a step. A node that is only "call the model with these messages" is the loop in Part 12.


Part 5: Edges and control flow#

Edges say what runs next. There are three ways to express that: a normal edge (always go there), a conditional edge (a function chooses) and a Command (the node itself chooses, Part 6). Fan-out, fan-in and loops are built from these.

5.1 Normal edges, entry points and END#

python
builder.add_edge("a", "b")                  # after a, run b
builder.add_edge(START, "a")                # entry point: a runs first
builder.add_edge("b", END)                  # b is a last node (END is optional, see 2.3)
builder.add_edge(["b", "c"], "d")           # d waits for BOTH b and c (5.4)

The three set_* helpers are plain aliases that you will see in older code and that are not deprecated:

Helper Equals
set_entry_point("a") add_edge(START, "a")
set_conditional_entry_point(path, path_map) add_conditional_edges(START, path, path_map)
set_finish_point("b") add_edge("b", END)

A graph can have several edges out of START, in which case those nodes start together in super-step 1, and several edges out of any node: "A node can have multiple outgoing edges. Destinations on those edges run in parallel in the next super-step." (docs; 5.4 below). A conditional entry point (add_conditional_edges(START, route)) lets the very first decision depend on the input, which is how a router graph begins and how the Send sample in Part 7 starts.

5.2 Conditional edges#

add_conditional_edges(source, path, path_map=None) attaches a routing function to a node. After source finishes, LangGraph calls path(state) and goes where the return value says. The sample runs five cases: a ticket router with a Literal return type, one with a path_map dict, a router that returns a list, a bad return value and a loop:

python
# g08_conditional.py: conditional edges: Literal paths, path_map, fan-out lists, END, loops
import operator
from typing import Annotated, Literal

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class Ticket(TypedDict):
    text: str
    category: str
    handled_by: Annotated[list[str], operator.add]


def classify(state: Ticket):
    text = state["text"].lower()
    if "refund" in text:
        return {"category": "billing"}
    if "crash" in text or "error" in text:
        return {"category": "technical"}
    return {"category": "other"}


def billing(state: Ticket):
    return {"handled_by": ["billing"]}


def technical(state: Ticket):
    return {"handled_by": ["technical"]}


def human(state: Ticket):
    return {"handled_by": ["human"]}


# 1. the routing function returns a node NAME; Literal documents (and draws) the possible targets
def route(state: Ticket) -> Literal["billing", "technical", "human"]:
    return {"billing": "billing", "technical": "technical"}.get(state["category"], "human")


g = StateGraph(Ticket)
for fn in (classify, billing, technical, human):
    g.add_node(fn)
g.add_edge(START, "classify")
g.add_conditional_edges("classify", route)
for name in ("billing", "technical", "human"):
    g.add_edge(name, END)
graph = g.compile()
for text in ["I want a refund", "The app shows an error", "Hello"]:
    print(f"{text!r:28} ->", graph.invoke({"text": text})["handled_by"])


# 2. a path_map decouples the router's labels from node names
def label(state: Ticket) -> str:
    return state["category"]


g2 = StateGraph(Ticket)
for fn in (classify, billing, technical, human):
    g2.add_node(fn)
g2.add_edge(START, "classify")
g2.add_conditional_edges("classify", label, {"billing": "billing", "technical": "technical", "other": "human"})
for name in ("billing", "technical", "human"):
    g2.add_edge(name, END)
print("path_map    :", g2.compile().invoke({"text": "Hello"})["handled_by"])
print("path_map edges:", sorted((e.source, e.target, e.conditional) for e in g2.compile().get_graph().edges if e.source == "classify"))


# 3. a router may return a LIST: every named node runs in the next super-step
def both(state: Ticket) -> list[str]:
    return ["billing", "technical"]


g3 = StateGraph(Ticket)
for fn in (classify, billing, technical):
    g3.add_node(fn)
g3.add_edge(START, "classify")
g3.add_conditional_edges("classify", both, ["billing", "technical"])
g3.add_edge("billing", END)
g3.add_edge("technical", END)
print("fan-out list:", sorted(g3.compile().invoke({"text": "x"})["handled_by"]))


# 4. an unknown return value
def bad(state: Ticket):
    return "nowhere"


g4 = StateGraph(Ticket)
g4.add_node(classify)
g4.add_edge(START, "classify")
g4.add_conditional_edges("classify", bad)
import logging

logging.basicConfig(level=logging.WARNING, format="LOG %(levelname)s %(name)s: %(message)s")
print("unknown name:", g4.compile().invoke({"text": "x"}))  # no exception: the run just ends


# 5. a loop: route back until a condition holds
class Draft(TypedDict):
    attempts: int
    text: str


def write(state: Draft):
    n = state["attempts"] + 1
    return {"attempts": n, "text": "x" * n}


def should_continue(state: Draft) -> Literal["write", "__end__"]:
    return END if len(state["text"]) >= 3 else "write"


lg = StateGraph(Draft).add_node(write).add_edge(START, "write")
lg.add_conditional_edges("write", should_continue)
print("loop        :", lg.compile().invoke({"attempts": 0, "text": ""}))
Output8 lines
'I want a refund'            -> ['billing']
'The app shows an error'     -> ['technical']
'Hello'                      -> ['human']
path_map    : ['human']
path_map edges: [('classify', 'billing', True), ('classify', 'human', True), ('classify', 'technical', True)]
fan-out list: ['billing', 'technical']
unknown name: {'text': 'x', 'category': 'other', 'handled_by': []}
loop        : {'attempts': 3, 'text': 'xxx'}

What the five cases show:

  1. Return a node name. route returns "billing", "technical" or "human", and the graph follows. The Literal[...] return annotation does not change execution, it tells LangGraph (and the drawing) which nodes the function can reach. Without it, the drawing shows the router leading straight to END and your diagram lies (the sample in 10.4 prints it).
  2. A path_map decouples labels from node names. The router returns "other", the map sends it to human. path_map can also be a plain list of possible destinations, which tells the drawing where the router can go (Part 7's sample passes ["summarize"]). The path_map edges line shows the edges the graph recorded; the True means conditional.
  3. Return a list to fan out. both returned two names, and both nodes ran in the next super-step.
  4. An unknown destination can fail silently. bad returned "nowhere". The run did not fail: it ended, with a warning in the log (wrote to unknown channel branch:to:nowhere, ignoring it), and the final state shows nothing was handled. Whether you get a silent end or a loud error depends on how the router was declared, as the next sample shows.
  5. A loop is a conditional edge that points back. should_continue returns END or "write", and the run repeated until three characters were written.

The routing function should be a pure function of the state: it reads, it does not write, it does not call a model unless you really mean to. If a decision needs an LLM call, do the call in a node, write the decision to state, and route on that key (the classify node and route pair above). That keeps the decision visible in the stream and in a trace, replayable, and testable. 08A.9, 3.2 described routing as a workflow pattern; this is how you write it.

What happens when a router returns a name that is not a destination. The sample declares the same bad router four ways:

python
# g28_unknown_route.py: a router returns a name that is not a destination: what happens depends on how it was declared
import logging
from typing import Literal

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph

logging.basicConfig(level=logging.WARNING, format="   LOG %(message)s")


class State(TypedDict):
    handled_by: str


def node(name):
    def fn(state: State):
        return {"handled_by": name}
    fn.__name__ = name
    return fn


def build(router, path_map=None):
    g = StateGraph(State)
    g.add_node(node("first"))
    g.add_node(node("billing"))
    g.add_node(node("human"))
    g.add_edge(START, "first")
    g.add_conditional_edges("first", router, path_map)
    g.add_edge("billing", END)
    g.add_edge("human", END)
    return g.compile()


def bad_plain(state: State):
    return "nowhere"


def bad_literal(state: State) -> Literal["billing", "human"]:
    return "nowhere"  # type: ignore[return-value]


cases = [
    ("no annotation, no path_map", build(bad_plain)),
    ("Literal annotation", build(bad_literal)),
    ("path_map dict", build(bad_plain, {"billing": "billing", "other": "human"})),
    ("path_map list", build(bad_plain, ["billing", "human"])),
]
for label, graph in cases:
    try:
        print(f"{label:28s}: returned", graph.invoke({"handled_by": ""}))
    except Exception as e:  # noqa: BLE001
        print(f"{label:28s}: {type(e).__name__}: {e}")
Output4 lines
no annotation, no path_map  : returned {'handled_by': 'first'}
Literal annotation          : KeyError: 'nowhere'
path_map dict               : KeyError: 'nowhere'
path_map list               : KeyError: 'nowhere'
How the router is declared Return value "nowhere"
No Literal return annotation, no path_map Silent: the run ends, with only a log warning
Literal[...] return annotation KeyError: 'nowhere' at run time
path_map dict, with the value missing from it KeyError
path_map list KeyError

So the annotation does two jobs: it draws the right edges, and it turns "return a wrong name" from a silent end into an immediate error. That is one more reason to annotate every router, and to run a test for every branch: only the unannotated form fails quietly. (If a KeyError appears from deep inside LangGraph naming your route, this is the cause.)

5.3 Loops#

A loop in LangGraph is nothing special: it is an edge that points to an earlier node, with a conditional edge to END to stop it. The agent loop, a draft-and-check loop and a retry loop are all this shape:

flowchart LR
    s(["START"]) --> write["write"]
    write --> check{"good enough?"}
    check -- "no, attempts left" --> write
    check -- "yes" --> e(["END"])
    check -- "no, out of attempts" --> human["escalate"]
    human --> e

Two rules make loops safe. First, put the stop condition in state: an attempts counter, a done flag, a score. Never rely on the model to "know when to stop". Second, bound the loop independently of your logic, because a bug in the stop condition otherwise runs for 10,007 super-steps (Part 11). The graph in Part 13 does both: a counter in state and max_attempts from the run's context.

5.4 Fan-out and fan-in: three ways to join#

Several edges out of one node run their targets in parallel. Joining them again is where graphs get subtle, because there are three different ways to write the join and they behave differently when the branches are not the same length. The sample builds one graph with a long branch (b1 -> b2) and a short one (c), joins them at d three ways, and then shows what a list-form join does when a branch is never taken:

python
# g07_fan_in.py: three ways to join branches of unequal length, and a join whose branch is skipped
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    trace: Annotated[list[str], operator.add]


def make(name):
    def node(state: State):
        return {"trace": [name]}
    node.__name__ = name
    return node


def build(join_style):
    g = StateGraph(State)
    for name in ["a", "b1", "b2", "c", "d"]:
        g.add_node(name, make(name), defer=(join_style == "defer" and name == "d"))
    g.add_edge(START, "a")
    g.add_edge("a", "b1")       # long branch: b1 -> b2
    g.add_edge("b1", "b2")
    g.add_edge("a", "c")        # short branch: c
    if join_style == "list":
        g.add_edge(["b2", "c"], "d")
    else:
        g.add_edge("b2", "d")
        g.add_edge("c", "d")
    g.add_edge("d", END)
    return g.compile()


for style in ("separate", "list", "defer"):
    result = build(style).invoke({"trace": []})
    print(f"{style:9s}: d ran {result['trace'].count('d')} time(s) ->", result["trace"])


# a list-form join whose branch is never taken: d silently never runs
class S2(TypedDict):
    trace: Annotated[list[str], operator.add]
    take_c: bool


def a(state: S2):
    return {"trace": ["a"]}


def b(state: S2):
    return {"trace": ["b"]}


def c(state: S2):
    return {"trace": ["c"]}


def d(state: S2):
    return {"trace": ["d"]}


def route(state: S2):
    return ["b", "c"] if state["take_c"] else ["b"]


g = StateGraph(S2)
for name, fn in [("a", a), ("b", b), ("c", c), ("d", d)]:
    g.add_node(name, fn)
g.add_edge(START, "a")
g.add_conditional_edges("a", route, ["b", "c"])
g.add_edge(["b", "c"], "d")
g.add_edge("d", END)
graph = g.compile()
print("c taken    :", graph.invoke({"trace": [], "take_c": True})["trace"])
print("c skipped  :", graph.invoke({"trace": [], "take_c": False})["trace"])
Output5 lines
separate : d ran 2 time(s) -> ['a', 'b1', 'c', 'b2', 'd', 'd']
list     : d ran 1 time(s) -> ['a', 'b1', 'c', 'b2', 'd']
defer    : d ran 1 time(s) -> ['a', 'b1', 'c', 'b2', 'd']
c taken    : ['a', 'b', 'c', 'd']
c skipped  : ['a', 'b']
Join style Code Behaviour
Separate edges add_edge("b2", "d") and add_edge("c", "d") d runs once per super-step in which any incoming branch completes. With branches of unequal length, d ran twice (['a', 'b1', 'c', 'b2', 'd', 'd']).
List-form edge add_edge(["b2", "c"], "d") d runs once, after all listed nodes have completed. But if one listed node never runs because a conditional branch skipped it, d never runs, and there is no error (the c skipped line).
Separate edges plus defer=True add_node("d", d, defer=True) d runs once, when the graph has no other pending work, regardless of which branches were taken.

Choosing:

  • Branches are unconditional and you need both: the list form is the clearest.
  • Branches are conditional (a router may skip one), or the number of branches is dynamic (a Send fan-out): use defer=True, which waits for "everything that was scheduled" instead of "this exact set".
  • Never use separate edges into a join unless you want the join to run per arrival.

defer=True means "run this node when the run is about to end", so a Send addressed to a deferred node still invokes it separately. A deferred node is also a good place for a final "reduce" step (Part 7).

Order and failure inside a super-step. Parallel updates "may not be ordered consistently" (docs), so if you need a stable order, have each branch write its result with an ordering key to its own field or to a reduced list, and sort in the join node (7.2 does). The super-step is transactional (1.3): if one branch raises, none of the step's updates are applied, and the exception propagates (the run in 7.4 shows it). To cap how many branches execute at once, pass max_concurrency as a top-level config key, never under configurable: graph.invoke(inputs, {"max_concurrency": 10}).

5.5 Fan-out inside a graph versus RunnableParallel#

08F.7, 3.4 showed RunnableParallel for independent calls inside a chain. In a graph, use parallel edges when each branch is a meaningful step you want to see, stream and checkpoint separately; use a RunnableParallel inside a single node when the parallelism is an implementation detail of one step (two retrievers feeding one prompt, say). The first is visible and durable, the second is compact.

5.6 Do not mix static edges and dynamic routing from the same node#


Part 6: Command: an update and a jump in one return value#

Deep-dive

6.1 Update plus goto#

Sometimes a node must both change state and decide where to go next, and the decision depends on the work it just did. With conditional edges you split that in two: the node writes its result, and a separate routing function re-reads the state to decide. Command lets the node do both in one return value. The class lives in langgraph.types:

python
from langgraph.types import Command

Command(
    graph=None,      # None: the current graph; Command.PARENT: the closest parent graph (6.3)
    update=None,     # the state update, same shape as a normal node return
    resume=None,     # a human's answer to an interrupt (08F.12); not for node returns
    goto=(),         # a node name, a list of names, a Send, or a list of Sends
)

The sample has four cases: a triage node that updates state and routes (no conditional edge, no router function), a goto list, the mixing trap, and Command used as an input (6.4):

python
# g09_command.py: Command (update + goto), the annotation, mixing with static edges, Command as input
import operator
from typing import Annotated, Literal

from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command


class State(TypedDict):
    amount: float
    route: str
    log: Annotated[list[str], operator.add]


# 1. one node decides AND updates: no conditional edge, no router function
def triage(state: State) -> Command[Literal["auto_approve", "manager_review"]]:
    if state["amount"] <= 100:
        return Command(update={"route": "auto", "log": ["triage: small"]}, goto="auto_approve")
    return Command(update={"route": "review", "log": ["triage: large"]}, goto="manager_review")


def auto_approve(state: State):
    return {"log": ["auto_approve"]}


def manager_review(state: State):
    return {"log": ["manager_review"]}


g = StateGraph(State)
g.add_node(triage)
g.add_node(auto_approve)
g.add_node(manager_review)
g.add_edge(START, "triage")
# note: NO edge out of triage. Its Command(goto=...) is the edge.
g.add_edge("auto_approve", END)
g.add_edge("manager_review", END)
graph = g.compile()
for amount in (40.0, 900.0):
    print(amount, "->", graph.invoke({"amount": amount, "log": []}))

print("edges drawn:", sorted((e.source, e.target) for e in graph.get_graph().edges))


# 2. Command(goto=[...]) fans out to several nodes
def fan(state: State) -> Command[Literal["auto_approve", "manager_review"]]:
    return Command(goto=["auto_approve", "manager_review"])


f = StateGraph(State).add_node(fan).add_node(auto_approve).add_node(manager_review)
f.add_edge(START, "fan")
print("goto list    :", sorted(f.compile().invoke({"amount": 1.0, "log": []})["log"]))


# 3. the mixing trap: a static edge AND a Command(goto) from the same node run BOTH
def decide(state: State) -> Command[Literal["manager_review"]]:
    return Command(update={"log": ["decide"]}, goto="manager_review")


m = StateGraph(State).add_node(decide).add_node(auto_approve).add_node(manager_review)
m.add_edge(START, "decide")
m.add_edge("decide", "auto_approve")      # static edge from the same node
print("static+goto  :", m.compile().invoke({"amount": 1.0, "log": []})["log"])


# 4. Command as INPUT: it resumes from the latest checkpoint
saver = InMemorySaver()
chat = StateGraph(State).add_node(auto_approve).add_edge(START, "auto_approve").add_edge("auto_approve", END)
app = chat.compile(checkpointer=saver)
cfg = {"configurable": {"thread_id": "t1"}}
print("turn 1       :", app.invoke({"amount": 1.0, "log": ["turn 1"]}, cfg)["log"])
print("Command input:", app.invoke(Command(update={"log": ["turn 2 via Command"]}), cfg)["log"])
print("plain dict   :", app.invoke({"log": ["turn 2 via dict"]}, cfg)["log"])
Output8 lines
40.0 -> {'amount': 40.0, 'route': 'auto', 'log': ['triage: small', 'auto_approve']}
900.0 -> {'amount': 900.0, 'route': 'review', 'log': ['triage: large', 'manager_review']}
edges drawn: [('__start__', 'triage'), ('auto_approve', '__end__'), ('manager_review', '__end__'), ('triage', 'auto_approve'), ('triage', 'manager_review')]
goto list    : ['auto_approve', 'manager_review']
static+goto  : ['decide', 'auto_approve', 'manager_review']
turn 1       : ['turn 1', 'auto_approve']
Command input: ['turn 1', 'auto_approve', 'turn 2 via Command']
plain dict   : ['turn 1', 'auto_approve', 'turn 2 via Command', 'turn 2 via dict', 'auto_approve']

Case 1: triage returned Command(update=..., goto="auto_approve") for the small amount and goto="manager_review" for the large one, and each run took only the branch it chose. The graph has no edge out of triage: the Command is the edge. The edges drawn line shows triage -> auto_approve and triage -> manager_review anyway, because of the return annotation Command[Literal["auto_approve", "manager_review"]].

Case 2: Command(goto=["auto_approve", "manager_review"]) fans out; both nodes ran.

Case 3, the trap:

6.2 Command goto with Send#

goto also accepts Send objects, alone or in a list, so a node can both update state and fan out to workers in one return: Command(update={"phase": "mapping"}, goto=[Send("worker", {"item": i}) for i in items]). Part 7 uses this form in 7.4.

6.3 Command.PARENT: routing out of a subgraph#

When a graph is used as a node of another graph (a subgraph, 08F.13), a node inside it can send control to a node of the closest parent graph with graph=Command.PARENT. This is the mechanism behind agent handoffs. The sample is small:

python
# g10_parent.py: Command.PARENT: a node inside a subgraph routes in the PARENT graph
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Command


class State(TypedDict):
    log: Annotated[list[str], operator.add]    # the PARENT must define a reducer for a shared key


def check(state: State):
    # runs inside the subgraph, but jumps to a node of the closest parent graph
    return Command(update={"log": ["check: escalate"]}, goto="escalate", graph=Command.PARENT)


def never(state: State):
    return {"log": ["never runs"]}


sub = StateGraph(State).add_node("check", check).add_node("never", never)
sub.add_edge(START, "check")
sub.add_edge("check", "never")           # skipped: the Command leaves the subgraph
sub_graph = sub.compile()


def escalate(state: State):
    return {"log": ["escalate"]}


parent = StateGraph(State)
parent.add_node("sub", sub_graph)
parent.add_node("escalate", escalate)
parent.add_edge(START, "sub")
parent.add_edge("escalate", END)
print(parent.compile().invoke({"log": ["start"]}))
Output1 line
{'log': ['start', 'check: escalate', 'escalate']}

The check node ran inside the subgraph, but its Command jumped to escalate in the parent; the subgraph's own never node was skipped. One rule is easy to miss: if the update touches a key that both schemas have, the parent graph must define a reducer for that key (here log is Annotated[list[str], operator.add] in the shared schema). Subgraph state, shared and private keys and the handoff pattern are 08F.13's subject.

6.4 Command as an input is a trap#

Command has three legitimate places to appear:

Where Use
Returned from a node update, goto, graph: this Part
Passed as the input to invoke or stream Only Command(resume=...) (optionally with update), to answer an interrupt (08F.12)
Returned from a tool Update state or route from a tool; the update must include a ToolMessage for the tool call, and the prebuilt ToolNode propagates it (08F.8)

Case 4 of the sample shows why only the second row is safe. A graph with a checkpointer finished turn 1. Passing Command(update={"log": [...]}) as the input applied the update (turn 2 via Command appears in the log) but ran no node: the thread resumes from its latest checkpoint, which was already at the end. The next call, with a plain dict, started a fresh turn and ran auto_approve again. The docs' warning, in one line: "Any Command as input resumes from the latest checkpoint, not from START, so a finished thread can look stuck. Pass a plain dict to start a new turn."

python
# wrong: looks like "add a message and run", but runs nothing on a finished thread
graph.invoke(Command(update={"messages": [("user", "hello again")]}), config)

# right: a plain dict is a new turn
graph.invoke({"messages": [("user", "hello again")]}, config)

(This was the only place in the lesson where a checkpointer appeared; InMemorySaver and thread_id are explained in 08F.11.)

6.5 Command versus conditional edges versus Send#

The docs' rule: use Command "when one step must both update state and choose the next node, since the route depends on work done in that same function. For routing alone, prefer conditional edges." And Send when the same node must run once per item, "each with its own input, and the item count is known only at runtime".

You want Use Why
Always go from A to B add_edge Fixed topology is the clearest and the cheapest
Choose the next node from state that already exists add_conditional_edges with a pure routing function The decision is visible, testable and separate from the work
Do work and route on its result in one step Command(update=..., goto=...) Avoids writing a "decision" key just so a router can read it back
Run one node for each item in a list known only at run time Send (Part 7), from a conditional edge or a Command The topology is fixed at build time; Send creates the tasks at run time
Jump out of a subgraph to its parent Command(graph=Command.PARENT, ...) The only way to address the parent
A tool changes graph state or routes Command returned from the tool The tool is the one that knows
flowchart TD
    q1{"Is the next node always the same?"} -- yes --> edge["add_edge"]
    q1 -- no --> q2{"One node per item of a runtime list?"}
    q2 -- yes --> send["Send"]
    q2 -- no --> q3{"Does the node also change state in the same step, and the route depends on that work?"}
    q3 -- yes --> cmd["Command(update, goto)"]
    q3 -- no --> cond["add_conditional_edges"]

Part 7: Send and map-reduce#

Deep-dive

7.1 The problem edges cannot solve#

Edges are fixed when you build the graph: "after plan, run write_a and write_b". But many workflows have a number of parallel tasks that is only known at run time: summarize every document in a batch, check every clause in a contract, call a tool for each of the ten search results, write each section a planner chose. You cannot draw a node per item in advance. Send solves this.

text
from langgraph.types import Send

Send(node, arg, *, timeout=None)

A Send("summarize", {"doc_id": 3, "text": "..."}) is a message that says "run the node called summarize with this dictionary as its input". Return a list of Send objects from a conditional edge (or inside a Command(goto=[...])) and LangGraph schedules one task per item, all in the next super-step. This is map-reduce: the map step is the fan-out of tasks, and the reduce step is whatever merges their results, which in LangGraph is a reducer on a shared key followed by a join node. 08A.9, 3.6 described the pattern framework-free; this is the LangGraph form.

The timeout argument (langgraph 1.2 and later) overrides the target node's timeout for that one task (08F.12).

7.2 A complete map-reduce#

The sample summarizes a list of documents with one worker node, then reduces to a report. The "summary" is the first five words, standing in for a model call, so it runs with no key. Five points are worth reading in it, and they are explained below:

python
# g11_send.py: Send and map-reduce: summarize every document with one worker node, then reduce
import operator
import time
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Send


class OverallState(TypedDict):
    documents: list[str]                       # known only at run time
    summaries: Annotated[list[tuple[int, str]], operator.add]   # (doc_id, summary): an ordering key travels with the text
    report: str


class WorkerState(TypedDict):                  # the worker's input is NOT the graph state
    doc_id: int
    text: str


def summarize(state: WorkerState):
    # a stand-in for a model call: first five words
    time.sleep(0.3 - 0.1 * state["doc_id"])        # make earlier documents finish later, to force out-of-order arrival
    short = " ".join(state["text"].split()[:5])
    return {"summaries": [(state["doc_id"], short)]}


def fan_out(state: OverallState):
    return [Send("summarize", {"doc_id": i, "text": t}) for i, t in enumerate(state["documents"])]


def reduce_(state: OverallState):
    ordered = sorted(state["summaries"])           # parallel order is not guaranteed: sort by the key
    return {"report": "\n".join(f"[{i}] {text}" for i, text in ordered)}


g = StateGraph(OverallState)
g.add_node("summarize", summarize)
g.add_node("reduce", reduce_)
g.add_conditional_edges(START, fan_out, ["summarize"])
g.add_edge("summarize", "reduce")
g.add_edge("reduce", END)
graph = g.compile()

docs = [
    "The refund policy allows returns within thirty days of delivery.",
    "Shipping to Canada takes between five and nine working days.",
    "Passwords must be at least twelve characters long.",
]
for chunk in graph.stream({"documents": docs}, stream_mode="updates"):
    print(chunk)
print("---")
print(graph.invoke({"documents": docs})["report"])
print("--- zero documents:")
print(graph.invoke({"documents": []}))
Output10 lines
{'summarize': {'summaries': [(2, 'Passwords must be at least')]}}
{'summarize': {'summaries': [(1, 'Shipping to Canada takes between')]}}
{'summarize': {'summaries': [(0, 'The refund policy allows returns')]}}
{'reduce': {'report': '[0] The refund policy allows returns\n[1] Shipping to Canada takes between\n[2] Passwords must be at least'}}
---
[0] The refund policy allows returns
[1] Shipping to Canada takes between
[2] Passwords must be at least
--- zero documents:
{'documents': [], 'summaries': []}
  1. The worker has its own input type. WorkerState is not the graph state: it is whatever the Send carries ({"doc_id": ..., "text": ...}). The worker is registered like any node and its function takes the worker dict. This is how each task gets its own input without the others being able to see it.
  2. Workers write to a key with a reducer. summaries is Annotated[list[tuple[int, str]], operator.add], so three parallel writes merge instead of raising InvalidUpdateError (3.3). Every worker returns a list of one item (a (doc_id, summary) pair), which operator.add concatenates.
  3. The router returns Send objects, and path_map says where. add_conditional_edges(START, fan_out, ["summarize"]) makes the fan-out the first step; the list tells the drawing which node the Sends go to.
  4. Parallel order is not guaranteed. The three worker updates arrive in whatever order the tasks finish (the docs say parallel updates "may not be ordered consistently"). The sample makes this visible: each worker sleeps longer for an earlier document, so the updates stream shows documents 2, 1, 0 in reverse order, yet the report is still correct. The reduce_ node therefore sorts by the doc_id that travels with each summary before building the report. If the order of results matters, carry an ordering key and sort in the reducing node; never rely on arrival order, and never sort the text itself ("[10]" sorts before "[2]").
  5. The edge from the worker to the next node is a normal edge. add_edge("summarize", "reduce") fires once per super-step in which workers finish; because all workers share one super-step here, reduce ran once. For fan-outs with workers of different depth, mark the reduce node defer=True (5.4).

7.3 Orchestrator-worker with a planner model#

The most common real use of Send is the orchestrator-worker pattern (08A.9, 3.4): a model decides how to split a task, workers do the parts in parallel, and a synthesizer assembles the result. The number and content of the sub-tasks are decided by the model, which is exactly why a static graph cannot express it. This sample uses structured output (08F.6) for the plan and Send for the fan-out. It needs langchain-openai (or another provider package, 08F.4) and python-dotenv:

python
# g24_orchestrator_worker.py: orchestrator-worker with a planner model and Send (illustrative: needs a provider key)
import operator
from typing import Annotated

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Send

load_dotenv()

# One line to change provider (keys from .env; see 08F.5 for the prefixes):
#   "openai:gpt-6-luna" | "anthropic:claude-haiku-5-5" | "google_genai:gemini-3.8-flash" (optional)
model = init_chat_model("openai:gpt-6-luna")


class Section(BaseModel):
    title: str = Field(description="Section heading")
    brief: str = Field(description="One sentence saying what the section must cover")


class Plan(BaseModel):
    sections: list[Section] = Field(description="Between 3 and 6 sections, in reading order")


planner = model.with_structured_output(Plan)


class State(TypedDict):
    topic: str
    sections: list[Section]                                  # known only after the planner runs
    drafts: Annotated[list[tuple[int, str]], operator.add]   # (position, text) from each worker
    report: str


class WorkerState(TypedDict):                                # the worker's whole input
    position: int
    section: Section


def plan(state: State):
    result = planner.invoke(f"Plan a short internal explainer about: {state['topic']}")
    return {"sections": result.sections}


def assign(state: State):
    # one worker per planned section; how many is decided by the model at run time
    return [Send("write_section", {"position": i, "section": s}) for i, s in enumerate(state["sections"])]


def write_section(state: WorkerState):
    s = state["section"]
    text = model.invoke(f"Write the section '{s.title}'. {s.brief} Use at most 120 words.").text
    return {"drafts": [(state["position"], f"## {s.title}\n{text}")]}


def synthesize(state: State):
    ordered = [text for _, text in sorted(state["drafts"])]    # parallel order is not guaranteed: sort
    return {"report": "\n\n".join(ordered)}


builder = StateGraph(State)
builder.add_node("plan", plan)
builder.add_node("write_section", write_section)
builder.add_node("synthesize", synthesize)
builder.add_edge(START, "plan")
builder.add_conditional_edges("plan", assign, ["write_section"])
builder.add_edge("write_section", "synthesize")
builder.add_edge("synthesize", END)
graph = builder.compile(name="explainer")

result = graph.invoke({"topic": "how our refund approval flow works"}, {"max_concurrency": 4})
print(result["report"][:400])
Example output · illustrative5 lines
## What the refund flow is
Customers request a refund from their order page. The request is checked against the return window and ...

## Who approves what
Refunds under the auto-approval limit are approved by the system. Larger amounts are routed to a ...

This sample is illustrative: it needs a provider key, and the plan and the text depend on the model. What does not depend on the model is the graph: the planner's list decides how many write_section tasks exist, each task has its own WorkerState, the drafts reducer collects (position, text) pairs, and synthesize sorts them before joining. For the same pattern with a pure-Python plan you can run today, replace planner.invoke(...) with a function that returns a fixed Plan.

7.4 Command(goto=[Send(...)]), concurrency and failures#

A node can combine state update and fan-out by returning a Command whose goto is a list of Sends. This sample also measures how many workers run at once, caps that with max_concurrency, and shows what one failing worker does to the whole step:

python
# g12_send_failures.py: Command(goto=[Send...]), concurrency cap, and what one failing worker does
import operator
import threading
import time
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, Send


class State(TypedDict):
    items: list[int]
    results: Annotated[list[int], operator.add]


class Worker(TypedDict):
    item: int


active = 0
peak = 0
lock = threading.Lock()


def work(state: Worker):
    global active, peak
    with lock:
        active += 1
        peak = max(peak, active)
    time.sleep(0.05)
    with lock:
        active -= 1
    if state["item"] == 3:
        raise ValueError("item 3 is poison")
    return {"results": [state["item"] * 10]}


def plan(state: State) -> Command:
    return Command(goto=[Send("work", {"item": i}) for i in state["items"]])


g = StateGraph(State)
g.add_node("plan", plan, destinations=("work",))   # destinations: only for drawing, since plan returns a Command
g.add_node("work", work)
g.add_edge(START, "plan")
g.add_edge("work", END)
graph = g.compile()

print("ok run       :", graph.invoke({"items": [1, 2, 4, 5]}))
print("peak parallel:", peak)
peak = 0
graph.invoke({"items": [1, 2, 4, 5, 6, 7]}, {"max_concurrency": 2})
print("peak with max_concurrency=2:", peak)

try:
    graph.invoke({"items": [1, 2, 3, 4]})
except ValueError as e:
    print("one worker failed ->", type(e).__name__, e, "(no partial results are returned)")
Output4 lines
ok run       : {'items': [1, 2, 4, 5], 'results': [10, 20, 40, 50]}
peak parallel: 4
peak with max_concurrency=2: 2
one worker failed -> ValueError item 3 is poison (no partial results are returned)
  • destinations=("work",) on the plan node tells the drawing where its Command can go (render-only, 6.1).
  • All four workers ran at once (peak parallel: 4). With {"max_concurrency": 2} at the top level of the config, never more than two ran at a time (peak with max_concurrency=2: 2). Set it whenever the workers call a rate-limited API (03.9). A fan-out of 500 items with no cap would send 500 simultaneous requests.
  • One poisoned item failed the whole step. Worker 3 raised, the exception reached the caller, and the successful workers' results were not returned. That is the transactional super-step (1.3): the step either applies completely or not at all. With a checkpointer, the other workers' writes are kept as pending writes and not re-run on resume (08F.11). For per-item fault tolerance, catch exceptions inside the worker and return an error record ({"results": [{"item": 3, "error": "..."}]}), or use a retry policy on the worker node (08F.12).

7.5 The other workflow patterns, in one table#

The docs' "Workflows and agents" page builds five workflow patterns plus an agent loop from the primitives above. Each maps to something you have now seen (08A.9, Part 3 described the patterns themselves):

Pattern Built from
Prompt chaining A line of nodes (4.5)
Parallelization Several edges out of one node, a reducer, a join (5.4)
Routing A classifier node and a conditional edge (5.2)
Orchestrator-worker A planner node and Send (7.3)
Evaluator-optimizer A generator node, a checker node and a loop edge (Part 13 builds one)
Agent A model node, a tool node and a loop (Part 12)

Part 8: Input, output and private schemas#

Deep-dive

By default a graph has one schema: callers send that shape in, the nodes share it, and callers get that shape back. That is the wrong default for anything that faces other code. A support-ticket graph should accept {"question": ...}, return {"answer": ...}, and keep its retrieved documents, drafts and counters to itself. StateGraph takes two extra arguments for this:

python
StateGraph(OverallState, input_schema=InputState, output_schema=OutputState)
  • input_schema describes what invoke and stream accept. It defaults to the overall schema.
  • output_schema describes what invoke returns. It defaults to the overall schema.
  • The overall schema (the first argument) is the union of everything the nodes share. It is the real state.
  • The older spellings input= and output= still work with a deprecation warning (14.2).

A third idea, private state, completes the picture: a node may return keys that are in no public schema (declare them in the node's return annotation) and a downstream node may declare a narrower input type to receive only what it needs. Private data flows between nodes without ever being part of the graph's public contract. The sample uses all three:

python
# g13_schemas.py: input, output and private schemas, and what streaming still shows
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class InputState(TypedDict):
    question: str


class OutputState(TypedDict):
    answer: str


class OverallState(InputState, OutputState):
    retrieved: list[str]          # internal: in neither the input nor the output schema


class Scratch(TypedDict):          # private: only ever declared on a node
    draft: str


def retrieve(state: InputState):
    return {"retrieved": ["policy: 30-day returns"]}


def draft(state: OverallState) -> Scratch:        # the return annotation declares a private key
    return {"draft": f"Per {state['retrieved'][0]}"}


def finish(state: Scratch):                        # a narrower view: this node sees only 'draft'
    return {"answer": state["draft"] + "; you can return it."}


builder = StateGraph(OverallState, input_schema=InputState, output_schema=OutputState)
builder.add_node(retrieve)
builder.add_node(draft)
builder.add_node(finish)
builder.add_edge(START, "retrieve")
builder.add_edge("retrieve", "draft")
builder.add_edge("draft", "finish")
builder.add_edge("finish", END)
graph = builder.compile()

print("invoke               :", graph.invoke({"question": "Can I return this?"}))
print("input schema keys    :", sorted(graph.get_input_jsonschema()["properties"]))
print("output schema keys   :", sorted(graph.get_output_jsonschema()["properties"]))

print("stream 'values' (last):", list(graph.stream({"question": "Can I return this?"}, stream_mode="values"))[-1])
print("stream 'values', output_keys:",
      list(graph.stream({"question": "Can I return this?"}, stream_mode="values", output_keys=["answer"]))[-1])
for chunk in graph.stream({"question": "Can I return this?"}, stream_mode="updates"):
    print("update               :", chunk)
Output8 lines
invoke               : {'answer': 'Per policy: 30-day returns; you can return it.'}
input schema keys    : ['question']
output schema keys   : ['answer']
stream 'values' (last): {'question': 'Can I return this?', 'answer': 'Per policy: 30-day returns; you can return it.', 'retrieved': ['policy: 30-day returns'], 'draft': 'Per policy: 30-day returns'}
stream 'values', output_keys: {'answer': 'Per policy: 30-day returns; you can return it.'}
update               : {'retrieve': {'retrieved': ['policy: 30-day returns']}}
update               : {'draft': {'draft': 'Per policy: 30-day returns'}}
update               : {'finish': {'answer': 'Per policy: 30-day returns; you can return it.'}}

What each line shows:

  • invoke returned only answer: the output schema filtered the result. retrieved and draft stayed inside.
  • The JSON schemas (get_input_jsonschema() and get_output_jsonschema()) list exactly one key each. Use them to document or validate a graph's contract; a deployed graph exposes them to clients (11A.5).
  • draft returns Scratch. The return annotation declares draft as a private key. finish takes Scratch, so it sees only draft: a node with a narrow input type cannot accidentally depend on other state. (add_node(..., input_schema=...) does the same thing when you cannot annotate the function.)

When to use which:

Situation Do
The graph is called by other code or exposed as an API Define input_schema and output_schema, so callers cannot depend on internals
Intermediate data is bulky (retrieved documents, drafts) and callers do not need it Keep it in the overall schema only; it will not be returned
Callers send untrusted input Make the input schema a Pydantic model so it is validated at the door (3.1), and keep the internal state a TypedDict
A node should not be able to see most of the state Give it a narrower input_schema
A key is truly secret Do not put it in state at all: pass it through context (Part 9), where it is not part of the streamed state

Initial values for internal keys deserve a note. Because callers can only send the input schema, an internal key such as an attempts counter has no value until a node writes it. Part 13's sample reads it with state.get("attempts", 0) for that reason, and keys with reducers start from the type's default ([] for lists, 0 for ints, which is why keep_max in 3.3 needed no first-call special case).


Part 9: Run-time context: Runtime versus state versus config#

Deep-dive

Not everything a node needs is state. The model name to use, the tenant id, a feature flag, a database handle, the user's locale: these are fixed for a run, they are inputs to the run, not results of it, and nodes should not be able to change them. LangGraph gives them their own channel: the runtime context.

You declare the shape with context_schema, pass a value as the context= argument of invoke or stream, and read it in a node through the runtime parameter:

python
# g14_context.py: runtime context (per-run, immutable) vs state vs config["configurable"]
from dataclasses import dataclass

from langchain_core.runnables import RunnableConfig
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime, get_runtime


class State(TypedDict):
    question: str
    answer: str


@dataclass
class Context:
    model_name: str = "small-model"
    tenant: str = "acme"


def answer(state: State, runtime: Runtime[Context]):
    ctx = runtime.context
    return {"answer": f"[{ctx.tenant}/{ctx.model_name}] {state['question']}"}


graph = (
    StateGraph(State, context_schema=Context)
    .add_node(answer)
    .add_edge(START, "answer")
    .add_edge("answer", END)
    .compile()
)

print("defaults      :", graph.invoke({"question": "hi"}, context=Context()))
print("dict -> dataclass:", graph.invoke({"question": "hi"}, context={"tenant": "globex", "model_name": "large-model"}))


# TypedDict context: stays a dict
class Ctx2(TypedDict):
    tenant: str


def answer2(state: State, runtime: Runtime[Ctx2]):
    return {"answer": "tenant=" + runtime.context["tenant"]}


g2 = StateGraph(State, context_schema=Ctx2).add_node(answer2).add_edge(START, "answer2").add_edge("answer2", END).compile()
print("TypedDict ctx :", g2.invoke({"question": "x"}, context={"tenant": "initech"}))


# the older way: config["configurable"], still supported
def answer3(state: State, config: RunnableConfig):
    return {"answer": "configurable=" + str(config["configurable"].get("tenant"))}


g3 = StateGraph(State).add_node(answer3).add_edge(START, "answer3").add_edge("answer3", END).compile()
print("configurable  :", g3.invoke({"question": "x"}, {"configurable": {"tenant": "umbrella"}}))


# what Runtime carries, and execution info without a checkpointer
def inspect(state: State, runtime: Runtime[Context]):
    info = runtime.execution_info
    rt2 = get_runtime(Context)         # also reachable from helper code called inside a node
    return {"answer": f"thread_id={info.thread_id} node_attempt={info.node_attempt} same_ctx={rt2.context == runtime.context} store={runtime.store}"}


g4 = StateGraph(State, context_schema=Context).add_node(inspect).add_edge(START, "inspect").add_edge("inspect", END).compile()
print("runtime       :", g4.invoke({"question": "x"})["answer"])
import dataclasses

print("Runtime fields:", [f.name for f in dataclasses.fields(Runtime)])


# no context passed at all: what does the node see?
def peek(state: State, runtime: Runtime[Context]):
    return {"answer": repr(runtime.context)}


g5 = StateGraph(State, context_schema=Context).add_node(peek).add_edge(START, "peek").add_edge("peek", END).compile()
print("no context    :", g5.invoke({"question": "x"})["answer"])
Output7 lines
defaults      : {'question': 'hi', 'answer': '[acme/small-model] hi'}
dict -> dataclass: {'question': 'hi', 'answer': '[globex/large-model] hi'}
TypedDict ctx : {'question': 'x', 'answer': 'tenant=initech'}
configurable  : {'question': 'x', 'answer': 'configurable=umbrella'}
runtime       : thread_id=None node_attempt=1 same_ctx=True store=None
Runtime fields: ['context', 'store', 'stream_writer', 'heartbeat', 'previous', 'execution_info', 'server_info', 'control']
no context    : None
  • context_schema is the second argument of StateGraph. A dataclass is the usual choice (it gives defaults), and Runtime[Context] in the node signature types runtime.context.
  • Dict coercion. Passing a dict (context={"tenant": "globex", ...}) to a graph whose context_schema is a dataclass or Pydantic model is converted to an instance (Context(**dict)). With a TypedDict schema the context stays a dict, and you read runtime.context["tenant"].
  • config["configurable"] still works. It is the older way to pass per-run values, and the docs say it still works for backward compatibility but recommend context. Keys with infrastructure meaning (thread_id, checkpoint_id, checkpoint_ns) still travel in configurable.
  • Runtime fields. From the source: context, store, stream_writer, heartbeat, previous, execution_info, server_info, control. It has no config: ask for it with a config: RunnableConfig parameter, or call langgraph.config.get_config(). get_runtime(Context) (from langgraph.runtime) fetches the current runtime from inside helper code called by a node, which saves threading the parameter through every function.
  • Execution info. runtime.execution_info carries thread_id (None here, because the graph had no checkpointer), node_attempt (1 on a first attempt) and more (4.7). server_info is only populated when running on Agent Server (11A.5).

The three homes for data, side by side. Choosing the right one is half of designing a graph:

State Runtime context Store (08F.11)
Lifetime One run, or one thread with a checkpointer One run only Across threads and conversations
Who changes it Nodes, by returning updates Nobody: it is immutable for the run Nodes and tools, through put
Typical contents Messages, intermediate results, counters, the answer Model name, tenant id, user id, locale, feature flags, clients User preferences, learned facts, long-term memory
Visible in the stream Yes (it is the state) No No
Saved in checkpoints Yes No: pass it again on every call In the store itself
python
# g25_context_resume.py: runtime context is NOT saved in checkpoints: pass it again when you resume
from dataclasses import dataclass
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from langgraph.types import Command, interrupt

@dataclass
class Ctx:
    tenant: str = "default"
class S(TypedDict):
    out: str
def ask(state: S, runtime: Runtime[Ctx]):
    before = repr(runtime.context)
    answer = interrupt("approve?")
    return {"out": f"before={before} after={runtime.context!r} answer={answer}"}
g = StateGraph(S, context_schema=Ctx).add_node(ask).add_edge(START,"ask").add_edge("ask",END).compile(checkpointer=InMemorySaver())
cfg={"configurable":{"thread_id":"1"}}
g.invoke({"out":""}, cfg, context=Ctx(tenant="acme"))
print("resume WITHOUT context:", g.invoke(Command(resume="yes"), cfg))
cfg2={"configurable":{"thread_id":"2"}}
g.invoke({"out":""}, cfg2, context=Ctx(tenant="acme"))
print("resume WITH context   :", g.invoke(Command(resume="yes"), cfg2, context=Ctx(tenant="acme")))
Output2 lines
resume WITHOUT context: {'out': 'before=None after=None answer=yes'}
resume WITH context   : {'out': "before=Ctx(tenant='acme') after=Ctx(tenant='acme') answer=yes"}

The thread's state came back from the checkpoint, the context did not. (InMemorySaver, thread_id, interrupt and Command(resume=...) are previews of 08F.11 and 08F.12; here they only make the point.) The docs' context overview draws the same split between static runtime context, dynamic state and the cross-conversation store.


Part 10: Running a graph, and drawing it#

10.1 The run methods#

A compiled graph is a Runnable (08F.7), so it has the whole interface. The signatures, from the 1.2.22 source (the options added by later lessons are marked):

text
graph.invoke(input, config=None, *, context=None, stream_mode="values", print_mode=(),
             output_keys=None, interrupt_before=None, interrupt_after=None,
             durability=None, control=None, version="v1")

graph.stream(input, config=None, *, context=None, stream_mode=None, print_mode=(),
             output_keys=None, interrupt_before=None, interrupt_after=None,
             durability=None, control=None, subgraphs=False, debug=None, version="v1")
Method Use
invoke / ainvoke Run to completion and return the final state (filtered by the output schema)
stream / astream Run and yield chunks while it runs
batch / abatch Run several inputs concurrently, results in input order
stream_events / astream_events The event streams (08F.7, 7.3; 08F.14 for the v3 event streams of graphs)
get_graph() / aget_graph() The drawable structure (10.4)
get_state(), get_state_history(), update_state() State inspection and time travel (08F.11)

The input can be a state dict, a Command (only Command(resume=...), 6.4), or None (continue from the latest checkpoint). config carries thread_id (inside configurable), recursion_limit and max_concurrency (top-level), tags, metadata and callbacks. context is the runtime context from Part 9. durability and control are persistence and shutdown options (08F.11, 08F.12). version selects the output format (10.3).

10.2 invoke versus stream: a first look#

Streaming is 08F.14's subject, in full. Here is the minimum you need to debug a graph today. The sample runs a two-node graph every way:

python
# g16_run_modes.py: invoke, stream (default mode), explicit stream modes, batch, ainvoke, version="v2"
import asyncio
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    n: int
    trace: Annotated[list[str], operator.add]


def double(state: State):
    return {"n": state["n"] * 2, "trace": ["double"]}


def add_one(state: State):
    return {"n": state["n"] + 1, "trace": ["add_one"]}


graph = (
    StateGraph(State)
    .add_node(double)
    .add_node(add_one)
    .add_edge(START, "double")
    .add_edge("double", "add_one")
    .add_edge("add_one", END)
    .compile()
)
x = {"n": 3, "trace": []}

print("invoke                :", graph.invoke(x))
print("stream (no mode)      :", list(graph.stream(x)))
print("stream 'updates'      :", list(graph.stream(x, stream_mode="updates")))
print("stream 'values'       :")
for snap in graph.stream(x, stream_mode="values"):
    print("   ", snap)
print("stream ['updates','values'] (tuples of (mode, chunk)):")
for item in graph.stream(x, stream_mode=["updates", "values"]):
    print("   ", item)

print("batch                 :", graph.batch([{"n": 1, "trace": []}, {"n": 10, "trace": []}]))
print("ainvoke               :", asyncio.run(graph.ainvoke(x)))


async def consume():
    return [c async for c in graph.astream(x, stream_mode="updates")]


print("astream 'updates'     :", asyncio.run(consume()))

out = graph.invoke(x, version="v2")
print("invoke version='v2'   :", type(out).__name__, out.value, out.interrupts)
print("stream v2 first part  :", next(iter(graph.stream(x, stream_mode="updates", version="v2"))))
Output18 lines
invoke                : {'n': 7, 'trace': ['double', 'add_one']}
stream (no mode)      : [{'double': {'n': 6, 'trace': ['double']}}, {'add_one': {'n': 7, 'trace': ['add_one']}}]
stream 'updates'      : [{'double': {'n': 6, 'trace': ['double']}}, {'add_one': {'n': 7, 'trace': ['add_one']}}]
stream 'values'       :
    {'n': 3, 'trace': []}
    {'n': 6, 'trace': ['double']}
    {'n': 7, 'trace': ['double', 'add_one']}
stream ['updates','values'] (tuples of (mode, chunk)):
    ('values', {'n': 3, 'trace': []})
    ('updates', {'double': {'n': 6, 'trace': ['double']}})
    ('values', {'n': 6, 'trace': ['double']})
    ('updates', {'add_one': {'n': 7, 'trace': ['add_one']}})
    ('values', {'n': 7, 'trace': ['double', 'add_one']})
batch                 : [{'n': 3, 'trace': ['double', 'add_one']}, {'n': 21, 'trace': ['double', 'add_one']}]
ainvoke               : {'n': 7, 'trace': ['double', 'add_one']}
astream 'updates'     : [{'double': {'n': 6, 'trace': ['double']}}, {'add_one': {'n': 7, 'trace': ['add_one']}}]
invoke version='v2'   : GraphOutput {'n': 7, 'trace': ['double', 'add_one']} ()
stream v2 first part  : {'type': 'updates', 'ns': (), 'data': {'double': {'n': 6, 'trace': ['double']}}}
  • invoke returns the final state, once.
  • stream with no stream_mode yields updates, one dict per node, keyed by node name ({'double': {...}}): what each node returned. That is the default for a graph that came from StateGraph.compile().
  • stream_mode="values" yields the whole state after each super-step, including the input as the first snapshot. Use it to watch the state evolve.
  • A list of modes (["updates", "values"]) yields (mode, chunk) tuples, so one stream carries both.
  • batch ran two inputs independently. ainvoke and astream are the async twins.
  • version="v2": invoke returned a GraphOutput with .value (the state dict) and .interrupts (a tuple, empty here), and stream yielded typed parts {'type': 'updates', 'ns': (), 'data': {...}} where ns is the subgraph namespace. In the default v1 format, a run that paused on an interrupt returns a plain dict containing an __interrupt__ key (08F.12).

The full set of modes, previewed: values, updates, messages (LLM tokens), custom (your own events), checkpoints, tasks and debug. 08F.14 teaches each and the version="v2" format.

10.3 invoke and the two formats#

version="v1" is the default in 1.2.22 and returns plain dicts; version="v2" returns typed objects (GraphOutput for invoke, StreamPart dicts for stream) and, for Pydantic or dataclass state, coerces the output back to the model (3.1). New code that wants interrupts as a proper field, or typed stream parts, should opt in to v2. Existing code and most tutorials use v1. Check the docs for the current default before assuming either.

10.4 Drawing a graph#

A graph that you cannot see is a graph you cannot review. graph.get_graph() returns a drawable structure with several renderers:

Method Returns Needs
draw_mermaid() Mermaid text Nothing (local, no network)
draw_mermaid_png() PNG bytes A network call to the Mermaid.ink web service by default; offline options: Pyppeteer (pip install pyppeteer) or Graphviz
draw_ascii() A text drawing The optional grandalf package
draw_png() PNG bytes pygraphviz and the Graphviz system binary

The sample draws a small ticket graph with a conditional edge, a Command node and a final node:

python
# g17_draw.py: draw a compiled graph as Mermaid text and as ASCII (no network needed for either)
from typing import Literal

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Command


class State(TypedDict):
    text: str
    category: str


def classify(state: State):
    return {"category": "billing" if "refund" in state["text"] else "other"}


def billing(state: State):
    return {"text": state["text"] + " [billing]"}


def human(state: State):
    return {"text": state["text"] + " [human]"}


def route(state: State) -> Literal["billing", "human"]:
    return "billing" if state["category"] == "billing" else "human"


def escalate(state: State) -> Command[Literal["human", "__end__"]]:
    return Command(goto="human")


g = StateGraph(State)
g.add_node(classify)
g.add_node(billing)
g.add_node(human)
g.add_node(escalate)
g.add_edge(START, "classify")
g.add_conditional_edges("classify", route)
g.add_edge("billing", "escalate")
g.add_edge("human", END)
graph = g.compile()

print(graph.get_graph().draw_mermaid())
print(graph.get_graph().draw_ascii())
print("nodes:", sorted(graph.get_graph().nodes))
print("edges:", sorted((e.source, e.target, e.conditional) for e in graph.get_graph().edges))
Output58 lines
---
config:
  flowchart:
    curve: linear
---
graph TD;
	__start__([<p>__start__</p>]):::first
	classify(classify)
	billing(billing)
	human(human)
	escalate(escalate)
	__end__([<p>__end__</p>]):::last
	__start__ --> classify;
	billing --> escalate;
	classify -.-> billing;
	classify -.-> human;
	escalate -.-> __end__;
	escalate -.-> human;
	human --> __end__;
	classDef default fill:#f2f0ff,line-height:1.2
	classDef first fill-opacity:0
	classDef last fill:#bfb6fc

          +-----------+
          | __start__ |
          +-----------+
                *
                *
                *
          +----------+
          | classify |
          +----------+
           ..        ..
         ..            ..
        .                ..
+---------+                .
| billing |                .
+---------+                .
      *                    .
      *                    .
      *                    .
+----------+               .
| escalate |               .
+----------+....           .
      .         ...        .
      .            ....    .
      .                ..  .
      .               +-------+
       ..             | human |
         ..           +-------+
           ..        **
             ..    **
               .  *
           +---------+
           | __end__ |
           +---------+
nodes: ['__end__', '__start__', 'billing', 'classify', 'escalate', 'human']
edges: [('__start__', 'classify', False), ('billing', 'escalate', False), ('classify', 'billing', True), ('classify', 'human', True), ('escalate', '__end__', True), ('escalate', 'human', True), ('human', '__end__', False)]

The Mermaid text above renders like this (it is the output verbatim; conditional edges are dashed, as the docs describe):

---
config:
  flowchart:
    curve: linear
---
graph TD;
	__start__([<p>__start__</p>]):::first
	classify(classify)
	billing(billing)
	human(human)
	escalate(escalate)
	__end__([<p>__end__</p>]):::last
	__start__ --> classify;
	billing --> escalate;
	classify -.-> billing;
	classify -.-> human;
	escalate -.-> __end__;
	escalate -.-> human;
	human --> __end__;
	classDef default fill:#f2f0ff,line-height:1.2
	classDef first fill-opacity:0
	classDef last fill:#bfb6fc

Reading the drawing is a skill. In this one, classify can go to billing or human (dashed: a conditional edge, from the Literal["billing", "human"] annotation), billing always goes to escalate (solid), and escalate has two dashed edges because of its Command[Literal["human", "__end__"]] annotation. The get_graph().nodes and .edges lines give the same facts as data (conditional is the third field), which is what you assert on in a test.

How annotations change the picture, and only the picture, is the next sample's point. It draws the same routing six ways and prints the edges from node a, and what the graph returns when run:

python
# g23_draw_annotations.py: routing annotations change the DRAWING, not the behaviour
from typing import Literal

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Command


class State(TypedDict):
    text: str


def node(name):
    def fn(state: State):
        return {"text": name}
    fn.__name__ = name
    return fn


def edges_from_a(graph):
    return sorted((e.source, e.target) for e in graph.get_graph().edges if e.source == "a")


def conditional(router, path_map=None):
    g = StateGraph(State)
    for n in ("a", "b", "c"):
        g.add_node(node(n))
    g.add_edge(START, "a")
    g.add_conditional_edges("a", router, path_map)
    g.add_edge("b", END)
    g.add_edge("c", END)
    return g.compile()


def with_command(fn, **kwargs):
    g = StateGraph(State)
    g.add_node("a", fn, **kwargs)
    g.add_node(node("b"))
    g.add_node(node("c"))
    g.add_edge(START, "a")
    return g.compile()


def route_plain(state: State):
    return "b"


def route_literal(state: State) -> Literal["b", "c"]:
    return "b"


def cmd_plain(state: State):
    return Command(goto="b")


def cmd_literal(state: State) -> Command[Literal["b", "c"]]:
    return Command(goto="b")


rows = [
    ("router, no annotation", conditional(route_plain)),
    ("router, Literal return type", conditional(route_literal)),
    ("router, path_map list", conditional(route_plain, ["b", "c"])),
    ("Command, no annotation", with_command(cmd_plain)),
    ("Command[Literal[...]]", with_command(cmd_literal)),
    ("Command + destinations=", with_command(cmd_plain, destinations=("b", "c"))),
]
for label, graph in rows:
    print(f"{label:30s} drawn edges from a: {edges_from_a(graph)}  runs ->", graph.invoke({"text": ""}))
Output6 lines
router, no annotation          drawn edges from a: [('a', '__end__')]  runs -> {'text': 'b'}
router, Literal return type    drawn edges from a: [('a', 'b'), ('a', 'c')]  runs -> {'text': 'b'}
router, path_map list          drawn edges from a: [('a', 'b'), ('a', 'c')]  runs -> {'text': 'b'}
Command, no annotation         drawn edges from a: [('a', '__end__')]  runs -> {'text': 'b'}
Command[Literal[...]]          drawn edges from a: [('a', 'b'), ('a', 'c')]  runs -> {'text': 'b'}
Command + destinations=        drawn edges from a: [('a', 'b'), ('a', 'c')]  runs -> {'text': 'b'}

Every row runs identically ({'text': 'b'}), but the unannotated router and the unannotated Command are drawn with a single edge from a to __end__, hiding both real destinations. A Literal return type, a path_map list or destinations=(...) restores them. Make a drawing part of code review, and a test that asserts the expected edges, so a refactor cannot silently change the topology.

Two more options: get_graph(xray=True) also expands subgraphs (08F.13), and LangSmith Studio draws and runs your graph interactively against a local server (11A.5). Further draw_mermaid_png parameters (curve_style, node_colors, output_file_path, draw_method and others) are in the docs' "Visualize your graph" page; check there for the current list.


Part 11: Recursion limits and loop safety#

Deep-dive

11.1 What the limit counts#

"The recursion limit caps how many super-steps one run may execute. When the limit is exceeded, LangGraph raises GraphRecursionError." (Graph API docs)

A super-step is one round of the plan, execute and update cycle (1.3). A node that runs once is one step. Ten parallel nodes in one round are one step. A loop of two nodes that repeats five times is ten steps. The limit is not "how deep is the call stack": it is "how many rounds".

The sample runs the two-node loop from the docs. Node a routes to b until seven items are in the list, b routes back to a, and each node prints its super-step number from config["metadata"]["langgraph_step"]. The limit is first set to 4, then to 100, and then the sample uses RemainingSteps to stop gracefully before the wall:

python
# g15_recursion.py: super-steps, the recursion limit, GraphRecursionError, RemainingSteps
import operator
from typing import Annotated

from langchain_core.runnables import RunnableConfig
from typing_extensions import TypedDict

from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
from langgraph.managed.is_last_step import RemainingSteps


class State(TypedDict):
    aggregate: Annotated[list[str], operator.add]


def node_a(state: State, config: RunnableConfig):
    print(f"  A runs in super-step {config['metadata']['langgraph_step']}, sees {state['aggregate']}")
    return {"aggregate": ["A"]}


def node_b(state: State, config: RunnableConfig):
    print(f"  B runs in super-step {config['metadata']['langgraph_step']}, sees {state['aggregate']}")
    return {"aggregate": ["B"]}


def route(state: State):
    return END if len(state["aggregate"]) >= 7 else "b"


g = StateGraph(State)
g.add_node("a", node_a)
g.add_node("b", node_b)
g.add_edge(START, "a")
g.add_conditional_edges("a", route)
g.add_edge("b", "a")
graph = g.compile()

print("limit 4:")
try:
    graph.invoke({"aggregate": []}, {"recursion_limit": 4})
except GraphRecursionError as e:
    print("GraphRecursionError:", str(e).splitlines()[0])
    print("is a RecursionError:", isinstance(e, RecursionError))

print("limit 100 (loop ends by itself):")
print(graph.invoke({"aggregate": []}, {"recursion_limit": 100})["aggregate"])


# Proactive: stop gracefully before the wall, using RemainingSteps
class Loop(TypedDict):
    notes: Annotated[list[str], operator.add]
    remaining_steps: RemainingSteps


def work(state: Loop):
    return {"notes": [f"work (remaining {state['remaining_steps']})"]}


def wrap_up(state: Loop):
    return {"notes": ["wrap_up: out of budget, returning a partial answer"]}


def more(state: Loop):
    return "wrap_up" if state["remaining_steps"] <= 2 else "work"


lg = StateGraph(Loop)
lg.add_node(work)
lg.add_node(wrap_up)
lg.add_edge(START, "work")
lg.add_conditional_edges("work", more)
lg.add_edge("wrap_up", END)
print("RemainingSteps with limit 6:")
for note in lg.compile().invoke({"notes": []}, {"recursion_limit": 6})["notes"]:
    print(" ", note)
Output22 lines
limit 4:
  A runs in super-step 1, sees []
  B runs in super-step 2, sees ['A']
  A runs in super-step 3, sees ['A', 'B']
  B runs in super-step 4, sees ['A', 'B', 'A']
GraphRecursionError: Recursion limit of 4 reached without hitting a stop condition. You can increase the limit by setting the `recursion_limit` config key.
is a RecursionError: True
limit 100 (loop ends by itself):
  A runs in super-step 1, sees []
  B runs in super-step 2, sees ['A']
  A runs in super-step 3, sees ['A', 'B']
  B runs in super-step 4, sees ['A', 'B', 'A']
  A runs in super-step 5, sees ['A', 'B', 'A', 'B']
  B runs in super-step 6, sees ['A', 'B', 'A', 'B', 'A']
  A runs in super-step 7, sees ['A', 'B', 'A', 'B', 'A', 'B']
['A', 'B', 'A', 'B', 'A', 'B', 'A']
RemainingSteps with limit 6:
  work (remaining 5)
  work (remaining 4)
  work (remaining 3)
  work (remaining 2)
  wrap_up: out of budget, returning a partial answer
  • With recursion_limit 4, four super-steps ran (A, B, A, B) and then GraphRecursionError was raised with a message that tells you the fix: increase the recursion_limit config key. The exception is a subclass of Python's RecursionError, so a broad except RecursionError catches it.
  • With 100, the loop ended by itself after seven steps, when its own stop condition held.
  • RemainingSteps is a managed value you declare in your state; LangGraph fills it with stop - step, so 5 on the first step with a limit of 6. A routing function that checks remaining_steps <= 2 sends the run to wrap_up while there is still room to do something useful, which is much better than an exception: the caller gets a partial answer instead of a stack trace. The proactive form (in-graph, RemainingSteps) and the reactive form (try/except GraphRecursionError outside the graph) are complementary. Use the first for graceful degradation and the second as the last line of defence.

RemainingSteps lives in langgraph.managed.is_last_step, a module name that looks internal; the docs document that import path, but it is worth checking the docs when you upgrade. A companion IsLastStep (a boolean that is true on the last allowed step) exists in the same module.

11.2 The default, and how to change it#

Two ways to change it:

python
graph.invoke(inputs, {"recursion_limit": 25})        # per call: a TOP-LEVEL config key
bash
LANGGRAPH_DEFAULT_RECURSION_LIMIT=200 uv run python app.py   # a new default for the process

The environment variable is read when langgraph is imported, so set it before the import (in your process manager, or at the very top of the entry script). The next sample sets it to 20 in code to show an infinite loop stopping at the new default:

python
# g15b_default_limit.py: the default limit is read from the environment when langgraph is imported
import os

os.environ["LANGGRAPH_DEFAULT_RECURSION_LIMIT"] = "20"      # must be set BEFORE importing langgraph

from typing_extensions import TypedDict  # noqa: E402

from langgraph.errors import GraphRecursionError  # noqa: E402
from langgraph.graph import START, StateGraph  # noqa: E402


class State(TypedDict):
    n: int


def tick(state: State):
    return {"n": state["n"] + 1}


# an infinite loop: tick routes to itself forever
g = StateGraph(State).add_node(tick).add_edge(START, "tick").add_edge("tick", "tick")
graph = g.compile()
try:
    graph.invoke({"n": 0})
except GraphRecursionError as e:
    print(str(e).splitlines()[0])
Output1 line
Recursion limit of 20 reached without hitting a stop condition. You can increase the limit by setting the `recursion_limit` config key.

An explicit recursion_limit equal to the default is honoured since langgraph 1.2.17 (a fix in the release notes), which only matters if you compare against the default in a wrapper.

11.3 Choosing a limit#

The graph A sensible limit
A fixed line of N nodes N plus a small margin; a loop means a bug
A draft-and-check loop with up to k attempts About 2k + (number of fixed nodes) + 2 (each attempt is two nodes), and an explicit counter in state as the real stop
An agent loop Each model call plus tool round is two steps; 2 * max_tool_rounds + 2; the middleware limits are the primary control
A Send fan-out The fan-out is one step, regardless of the number of workers
A loop whose length you cannot estimate A generous limit as the safety net, a counter or budget in state as the real stop, and an alert when the limit is ever reached

Part 12: The agent loop, written by hand#

08A.2 built the tool loop as a while loop around provider calls. As a graph it is three nodes and a cycle, and writing it once by hand is the fastest way to understand what create_agent (08F.8) does for you. The shape:

flowchart TD
    s(["START"]) --> model["model: call the chat model with the messages"]
    model --> cond{"tools_condition: does the last AIMessage have tool_calls?"}
    cond -- "yes" --> tools["tools: ToolNode runs each call, appends ToolMessages"]
    cond -- "no" --> e(["END"])
    tools --> model

12.1 The loop in 30 lines#

The two prebuilt pieces come from langgraph.prebuilt:

python
from langgraph.prebuilt import ToolNode, tools_condition
  • ToolNode(tools, *, name="tools", tags=None, handle_tool_errors=..., messages_key="messages", wrap_tool_call=None, awrap_tool_call=None) is a node that reads the tool_calls of the last AIMessage, runs each tool and appends one ToolMessage per call to messages.
  • tools_condition(state, messages_key="messages") is a routing function that returns "tools" if the last message has tool calls and "__end__" otherwise, so add_conditional_edges("model", tools_condition) works when your tool node is named "tools".

The sample uses a fake chat model with a scripted tool call, so it runs with no key. GenericFakeChatModel raises NotImplementedError when tools are bound, as 08F.7, 9.1 found, so the sample uses the same three-line subclass:

python
# g18_agent_loop.py: the agent loop written by hand as a graph: model node, ToolNode, tools_condition
from langchain.messages import AIMessage
from langchain.tools import tool
from langchain_core.language_models import GenericFakeChatModel
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition


class ToolFakeChatModel(GenericFakeChatModel):
    """GenericFakeChatModel raises NotImplementedError in bind_tools; this subclass accepts it."""

    def bind_tools(self, tools, **kwargs):
        return self  # the scripted replies already say which tool to call


@tool
def order_status(order_id: str) -> str:
    """Look up the shipping status of an order."""
    return f"order {order_id}: shipped on 2026-11-10"


tools = [order_status]

# the script: first the model asks for the tool, then it answers
script = iter([
    AIMessage(content="", tool_calls=[{"name": "order_status", "args": {"order_id": "A-1042"}, "id": "call_1"}]),
    AIMessage(content="Order A-1042 shipped on 10 November."),
])
model = ToolFakeChatModel(messages=script).bind_tools(tools)


def call_model(state: MessagesState):
    return {"messages": [model.invoke(state["messages"])]}


builder = StateGraph(MessagesState)
builder.add_node("model", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "model")
builder.add_conditional_edges("model", tools_condition)      # "tools" if the last AIMessage has tool calls, else END
builder.add_edge("tools", "model")                           # the loop
agent = builder.compile()

for chunk in agent.stream({"messages": [{"role": "user", "content": "Where is A-1042?"}]}, stream_mode="updates"):
    for node, update in chunk.items():
        for m in update["messages"]:
            print(f"{node:6s} -> {m.type:5s} tool_calls={len(getattr(m, 'tool_calls', []) or [])} content={m.content!r}")

print(agent.get_graph().draw_mermaid().split("graph TD;")[1].split("classDef")[0])
Output12 lines
model  -> ai    tool_calls=1 content=''
tools  -> tool  tool_calls=0 content='order A-1042: shipped on 2026-11-10'
model  -> ai    tool_calls=0 content='Order A-1042 shipped on 10 November.'

	__start__([<p>__start__</p>]):::first
	model(model)
	tools(tools<hr/><small><em>__tools = order_status</em></small>)
	__end__([<p>__end__</p>]):::last
	__start__ --> model;
	model -.-> __end__;
	model -.-> tools;
	tools --> model;

The stream shows the loop as it happens: the model node produced an AIMessage with one tool call, the tools node produced the ToolMessage with the order's status, and the model node ran again and produced the final text, with no tool calls, so tools_condition routed to END. The get_graph() Mermaid excerpt at the bottom (the node lines and edges only) shows the graph LangGraph built: model has two conditional edges (to tools and to the end), and tools always goes back to model. The ToolNode is labelled with the tools it can run.

Four details that matter in real code:

  1. The model must have the tools bound (model.bind_tools(tools), 08F.5, 9.1), or it will never emit a tool call. The ToolNode only runs tools; it does not tell the model about them.
  2. The state is MessagesState. The add_messages reducer (3.4) is what makes {"messages": [response]} append instead of replace, and what lets ToolNode's ToolMessages land in the right place. A hand-written agent state that uses plain operator.add for messages works for this loop but cannot edit or trim history.
  3. Import ToolNode from langgraph.prebuilt. One docstring in the package (for tools_condition) shows from langchain.tools import ToolNode; in langchain 1.5.0 that import does not work (langchain.tools no longer exports ToolNode). The docs' tutorials and this lesson use langgraph.prebuilt.
  4. Node names. The names "model" and "tools" are the ones create_agent uses (v0's "agent" was renamed to "model"). If you keep them, traces, drawings and middleware names read the same as for a create_agent agent.

12.2 What ToolNode does when a tool fails#

The default behaviour is a design decision you must know, because it decides whether one bad tool call ends your run. The sample runs ToolNode against four calls (wrapped in a one-node graph, because a ToolNode reads the runtime and cannot be invoked bare):

python
# g27_toolnode_errors.py: what ToolNode does with a bad call and with a tool that raises
from langchain.messages import AIMessage
from langchain.tools import tool
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode


@tool
def order_status(order_id: str) -> str:
    """Look up the shipping status of an order."""
    if order_id == "BOOM":
        raise RuntimeError("order database is down")
    return f"order {order_id}: shipped"


def run_tool_node(node, msg):
    # a ToolNode needs a graph around it (it reads the runtime), so wrap it in a one-node graph
    g = StateGraph(MessagesState).add_node("tools", node).add_edge(START, "tools").compile()
    return g.invoke({"messages": [msg]})["messages"][-1]


def call(tool_name, args):
    msg = AIMessage(content="", tool_calls=[{"name": tool_name, "args": args, "id": "call_1"}])
    return run_tool_node(ToolNode([order_status]), msg)


ok = call("order_status", {"order_id": "A-1"})
print("valid call     :", ok.status, "|", ok.content)

bad_args = call("order_status", {"wrong_name": 1})
print("invalid args   :", bad_args.status, "|", bad_args.content.splitlines()[0][:90])

unknown = call("no_such_tool", {})
print("unknown tool   :", unknown.status, "|", unknown.content[:90])

try:
    call("order_status", {"order_id": "BOOM"})
except Exception as e:  # noqa: BLE001
    print("tool raises    :", type(e).__name__, "-", e, "(the exception escapes the graph)")

# handle_tool_errors=True turns every exception into a ToolMessage the model can read
msg = AIMessage(content="", tool_calls=[{"name": "order_status", "args": {"order_id": "BOOM"}, "id": "call_2"}])
safe = run_tool_node(ToolNode([order_status], handle_tool_errors=True), msg)
print("handle=True    :", safe.status, "|", " ".join(safe.content.split()))

# the other accepted forms of handle_tool_errors
boom = AIMessage(content="", tool_calls=[{"name": "order_status", "args": {"order_id": "BOOM"}, "id": "call_3"}])
fixed = run_tool_node(ToolNode([order_status], handle_tool_errors="Order lookup failed, tell the user."), boom)
print("handle=str     :", fixed.status, "|", fixed.content)

custom = run_tool_node(ToolNode([order_status], handle_tool_errors=lambda e: f"{type(e).__name__}: {e}"), boom)
print("handle=callable:", custom.status, "|", custom.content)

only_runtime = run_tool_node(ToolNode([order_status], handle_tool_errors=RuntimeError), boom)
print("handle=RuntimeError:", only_runtime.status, "|", only_runtime.content)

try:
    run_tool_node(ToolNode([order_status], handle_tool_errors=ValueError), boom)
except Exception as e:  # noqa: BLE001
    print("handle=ValueError  :", type(e).__name__, "-", e, "(a RuntimeError is not handled, so it escapes)")

try:
    run_tool_node(ToolNode([order_status], handle_tool_errors=False), AIMessage(content="", tool_calls=[{"name": "order_status", "args": {"wrong_name": 1}, "id": "call_4"}]))
except Exception as e:  # noqa: BLE001
    print("handle=False   :", type(e).__name__, "-", str(e).splitlines()[0][:70])

# a bare ToolNode, with no graph around it
try:
    ToolNode([order_status]).invoke({"messages": [msg]})
except Exception as e:  # noqa: BLE001
    print("bare ToolNode  :", type(e).__name__, "-", e)
Output12 lines
valid call     : success | order A-1: shipped
invalid args   : error | Error invoking tool 'order_status' with kwargs {'wrong_name': 1} with error:
unknown tool   : error | Error: no_such_tool is not a valid tool, try one of [order_status].
tool raises    : RuntimeError - order database is down (the exception escapes the graph)
handle=True    : error | Error: RuntimeError('order database is down') Please fix your mistakes.
handle=str     : error | Order lookup failed, tell the user.
handle=callable: error | RuntimeError: order database is down
handle=RuntimeError: error | Error: RuntimeError('order database is down')
 Please fix your mistakes.
handle=ValueError  : RuntimeError - order database is down (a RuntimeError is not handled, so it escapes)
handle=False   : ToolInvocationError - Error invoking tool 'order_status' with kwargs {'wrong_name': 1} with 
bare ToolNode  : ValueError - Missing required config key 'N/A' for 'tools'.
Situation Default ToolNode behaviour
A valid call A ToolMessage with status="success"
Arguments that fail the tool's schema A ToolMessage with status="error" describing the validation failure, so the model can correct itself
A tool name that does not exist A ToolMessage with status="error" listing the valid names
An exception raised inside the tool The exception is re-raised and the run stops
Calling a ToolNode on its own, outside any graph ValueError: Missing required config key 'N/A' for 'tools'. (the last line of output). To unit-test a ToolNode, wrap it in a one-node graph as the sample's run_tool_node does

That last row surprises people: the default handles the model's mistakes (wrong arguments, wrong name) but not your tool's bugs or outages. handle_tool_errors=True converts every exception into an error ToolMessage (the handle=True line of output). The installed signature is handle_tool_errors: bool | str | Callable[..., str] | type[Exception] | tuple[type[Exception], ...], and the sample ran each form:

Value Effect Line of output
the default (a function) Converts only the tool-invocation error (bad arguments) into an error ToolMessage; everything else is re-raised invalid args, tool raises
True Catches every exception and sends a template message that includes the exception handle=True
a str Catches every exception and sends that fixed string to the model handle=str
a callable Catches every exception, calls the function with it, and sends the string it returns handle=callable
an exception class or a tuple of classes Handles only those types with the template message and re-raises any other handle=RuntimeError and handle=ValueError
False Re-raises everything, including bad arguments handle=False

The create_agent equivalents are ToolErrorMiddleware and ToolRetryMiddleware (08F.8, Part 4). Whether a failing tool should stop the run or be shown to the model is a policy decision: a transient outage the model can do nothing about probably should be retried by the tool or surfaced to your code (08F.12 covers retry policies), while "no such order" is information the model should see (08A.6). create_agent exposes the same choices (08F.8).

ToolNode also propagates a Command returned by a tool, which is how a tool updates state or routes, and it wraps tool calls with wrap_tool_call hooks, which middleware builds on.

12.3 With a real model#

The same graph with a provider's model replaces only the model line. This sample is illustrative (it needs a key and the matching langchain-* package, 08F.4):

python
# g26_agent_real.py: the same hand-written loop with a real model (illustrative: needs a provider key)
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition

load_dotenv()


@tool
def order_status(order_id: str) -> str:
    """Look up the shipping status of an order."""
    return f"order {order_id}: shipped on 2026-11-10"


tools = [order_status]

# "openai:gpt-6-luna" | "anthropic:claude-haiku-5-5" | "google_genai:gemini-3.8-flash" (optional)
model = init_chat_model("openai:gpt-6-luna").bind_tools(tools)


def call_model(state: MessagesState):
    return {"messages": [model.invoke(state["messages"])]}


builder = StateGraph(MessagesState)
builder.add_node("model", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "model")
builder.add_conditional_edges("model", tools_condition)
builder.add_edge("tools", "model")
agent = builder.compile(name="support_agent")

# the recursion limit is a safety net here; the real budget belongs in middleware (08F.8)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Where is order A-1042?"}]},
    {"recursion_limit": 12},
)
print(result["messages"][-1].text)
Example output · illustrative1 line
Order A-1042 shipped on 10 November 2026.

Notice what the sample deliberately does not have. There is no cap on model calls except recursion_limit, no retry on the provider, no summarization of long histories, no approval step and no guardrail. A production agent needs all of them, and the point of create_agent and its middleware is that someone has already built and tested them. Write the loop by hand to understand it, to teach it or to customize it in a way create_agent cannot; reach for create_agent for everything else.


Part 13: Designing a graph: thinking in graphs#

Deep-dive

Knowing the API is the easy half. The docs' "Thinking in the Graph API" page teaches a design method that this part condenses and then applies to a complete, runnable example.

13.1 A five-step method#

  1. Write the process as a flowchart, in words, before you write code. Each box is a candidate node, each arrow a candidate edge. If you cannot draw it, you do not understand it yet.

  2. Classify every box. The docs sort steps into four kinds, and the kind tells you how to build and protect the node:

    Kind Examples Build it as Protect it with
    LLM step Classify, extract, draft, grade, plan A node that calls a chain or model (08F.7) Structured output (08F.6), a check node, retries on transient errors
    Data step Look up an order, search a vector store, read a file A node that calls your code Idempotent reads, timeouts, caching (08F.12)
    Action step Send an email, issue a refund, write to a database Its own node, after the decision Idempotency keys (4.7), approval gates (08F.12)
    User-input step Ask a clarifying question, get an approval A node that pauses interrupt() and a checkpointer (08F.12)
  3. Design the state around raw facts, not prompts. Store the order id, the order record, the customer's message and the model's structured decision, not a pre-formatted prompt string. Build prompts inside the node from the facts (the write node in 13.2 does). Raw state can be reused by any node, inspected in a trace and tested without a model; a prompt string baked into state cannot.

  4. Decide the error policy per kind of failure. The docs' table is worth keeping next to your design:

    Kind of failure Handle it by Example
    Transient (network, rate limit) A retry policy on the node (08F.12) A search API times out
    The model can fix it Put the error in state and route back to the model A tool call with bad arguments (ToolNode's default, 12.2)
    A person can fix it interrupt() to ask An ambiguous order id
    Fixable after retries run out An error_handler node (langgraph 1.2 and later, 08F.12) Fall back to a cheaper path
    Unexpected Let it propagate and fail loudly A bug in your node
  5. Bound every loop, and write the stop condition in state. An attempts counter, a done flag, a score threshold (5.3, Part 11).

13.2 A complete example: a support-reply workflow#

This sample puts the lesson together. A customer message goes in, a reply (and a "needs a human" flag) comes out. The workflow: extract an order id, look the order up, draft a reply with a model, check that the reply mentions the order, redraft up to a limit, and hand the case to a person when anything fails. The diagram is the plan from step 1:

flowchart TD
    s(["START"]) --> extract["extract: find the order id"]
    extract -->|"found"| lookup["lookup: read the order"]
    extract -->|"not found"| escalate["escalate: hand to a person"]
    lookup -->|"order exists"| write["write: draft a reply with the model"]
    lookup -->|"unknown order"| escalate
    write --> check{"check: does the reply mention the order id?"}
    check -->|"yes"| e(["END"])
    check -->|"no, attempts left"| write
    check -->|"no, out of attempts"| escalate
    escalate --> e

The code uses nearly everything from Parts 3 to 9: input and output schemas (callers send message and get reply and needs_human; everything else is internal), a reducer on problems and trail, Command nodes that update and route in one return, a bounded loop whose limit comes from the runtime context, an LCEL chain (08F.7) inside a node, and a fake model whose first draft deliberately forgets the order id, so the loop has something to fix. A factory function takes the model as a parameter, which is what makes the graph testable (13.3):

python
# g19_support_graph.py: a complete small workflow: input and output schemas, reducers, Command routing,
# a checked-draft loop with a bounded retry count, runtime context, and a fake model so it runs without a key
import operator
from dataclasses import dataclass
from typing import Annotated, Literal

from langchain_core.language_models import BaseChatModel, GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from typing_extensions import NotRequired, TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from langgraph.types import Command

ORDERS = {"A-1042": {"status": "shipped", "eta": "2026-11-18"}, "B-7": {"status": "processing", "eta": None}}


class Request(TypedDict):                  # what callers send
    message: str


class Reply(TypedDict):                    # what callers get back
    reply: str
    needs_human: bool


class State(Request, Reply):               # everything the nodes share
    order_id: NotRequired[str]
    order: NotRequired[dict]
    attempts: NotRequired[int]             # not in the input schema: no value until a node sets it
    problems: Annotated[list[str], operator.add]
    trail: Annotated[list[str], operator.add]


@dataclass
class Context:
    max_attempts: int = 2
    shop_name: str = "Northwind"


PROMPT = ChatPromptTemplate.from_template(
    "Write a short reply for {shop}. Facts: {facts}. Problems with the last draft: {problems}"
)


def build_graph(model: BaseChatModel):
    draft_chain = PROMPT | model | StrOutputParser()

    def extract(state: State) -> Command[Literal["lookup", "escalate"]]:
        for word in state["message"].replace("?", " ").replace(".", " ").split():
            if len(word) > 2 and word[1] == "-" and word[2:].isdigit():
                return Command(update={"order_id": word, "trail": ["extract"]}, goto="lookup")
        return Command(update={"trail": ["extract: no order id"]}, goto="escalate")

    def lookup(state: State) -> Command[Literal["write", "escalate"]]:
        order = ORDERS.get(state["order_id"])
        if order is None:
            return Command(update={"trail": ["lookup: unknown order"]}, goto="escalate")
        return Command(update={"order": order, "trail": ["lookup"]}, goto="write")

    def write(state: State, runtime: Runtime[Context]):
        ctx = runtime.context or Context()       # context is None when the caller passes none
        text = draft_chain.invoke({
            "shop": ctx.shop_name,
            "facts": f"{state['order_id']} {state['order']}",
            "problems": "; ".join(state["problems"]) or "none",
        })
        return {"reply": text, "attempts": state.get("attempts", 0) + 1, "trail": ["write"]}

    def check(state: State, runtime: Runtime[Context]) -> Command[Literal["write", "escalate", "__end__"]]:
        ctx = runtime.context or Context()
        if state["order_id"] in state["reply"]:
            return Command(update={"needs_human": False, "trail": ["check: ok"]}, goto=END)
        if state["attempts"] >= ctx.max_attempts:
            return Command(update={"trail": ["check: out of attempts"]}, goto="escalate")
        return Command(
            update={"problems": ["the reply must mention the order id"], "trail": ["check: retry"]},
            goto="write",
        )

    def escalate(state: State):
        return {"reply": "A colleague will follow up shortly.", "needs_human": True, "trail": ["escalate"]}

    builder = StateGraph(State, context_schema=Context, input_schema=Request, output_schema=Reply)
    for fn in (extract, lookup, write, check, escalate):
        builder.add_node(fn)
    builder.add_edge(START, "extract")
    builder.add_edge("write", "check")
    builder.add_edge("escalate", END)
    return builder.compile(name="support_triage")


def scripted_model() -> GenericFakeChatModel:
    # the first draft forgets the order id, the second includes it
    return GenericFakeChatModel(messages=iter([
        AIMessage(content="Good news, your parcel is on its way!"),
        AIMessage(content="Order A-1042 has shipped and should arrive by 2026-11-18."),
    ]))


for message in ["Where is order A-1042?", "My parcel never came", "What happened to Z-99?"]:
    print(f"{message!r:28} ->", build_graph(scripted_model()).invoke({"message": message}))

print("--- the first run, node by node, with max_attempts=1")
graph = build_graph(scripted_model())
for chunk in graph.stream({"message": "Where is order A-1042?"}, stream_mode="updates", context={"max_attempts": 1}):
    node, update = next(iter(chunk.items()))
    print(f"{node:9s}", {k: v for k, v in (update or {}).items() if k in ("problems", "reply", "needs_human", "trail")})
Output9 lines
'Where is order A-1042?'     -> {'reply': 'Order A-1042 has shipped and should arrive by 2026-11-18.', 'needs_human': False}
'My parcel never came'       -> {'reply': 'A colleague will follow up shortly.', 'needs_human': True}
'What happened to Z-99?'     -> {'reply': 'A colleague will follow up shortly.', 'needs_human': True}
--- the first run, node by node, with max_attempts=1
extract   {'trail': ['extract']}
lookup    {'trail': ['lookup']}
write     {'reply': 'Good news, your parcel is on its way!', 'trail': ['write']}
check     {'trail': ['check: out of attempts']}
escalate  {'reply': 'A colleague will follow up shortly.', 'needs_human': True, 'trail': ['escalate']}

Reading the run:

  • Where is order A-1042?: the first draft ("Good news, your parcel is on its way!") did not mention the order, so check wrote a problem and routed back to write; the second draft did, needs_human became False, and the run ended. Note that the caller sees only reply and needs_human (the output schema): the trail, the attempts and the problems stayed inside.
  • My parcel never came: extract found no order id and went straight to escalate. No model was called.
  • What happened to Z-99?: extract found an id, lookup did not know it, and escalate ran. The graph handled an unknown order as a normal path, not an exception.
  • The node-by-node stream with context={"max_attempts": 1} shows the loop limit working: write produced the bad draft, check saw attempts >= 1 and routed to escalate (check: out of attempts) instead of retrying. One graph, two behaviours, no code change, because the limit lives in context, not in the code.

Design decisions worth noticing:

Decision Why
check is a plain-Python rule, not a model call A deterministic check is testable and free. Use an LLM grader only for what a rule cannot judge (08A.9, 3.5)
Every path ends in END through a named node The graph has no "falls off the end" behaviour, and a drawing shows every outcome
escalate is a node, not an exception A person taking over is a business outcome; it deserves a state value (needs_human)
The loop's counter is in state and its limit in context The counter changes during the run; the limit is configuration
runtime.context or Context() Context is None when the caller passes none (Part 9)
name="support_triage" on compile The name appears in traces and drawings
The Command annotations list every destination So get_graph() draws the real topology (6.1)

13.3 Testing a graph without a model#

Because the model is a parameter and nodes are plain functions, three kinds of test need no key and no network. This is the keyless basis for the testing material in 11A.5:

Test How What it protects
A node on its own Call the function with a dict, assert on the dict it returns (or the Command it returns) The logic of one step
A path through the graph Build with a scripted fake model, invoke, assert on the output and, with stream_mode="updates", on which nodes ran Routing and loops (the three runs above are exactly this)
The topology graph.get_graph().edges; assert on the expected edges A refactor that silently changes the wiring (6.5, 10.4)
python
def test_unknown_order_escalates():
    graph = build_graph(scripted_model())
    result = graph.invoke({"message": "What happened to Z-99?"})
    assert result["needs_human"] is True

(This fragment assumes the sample's build_graph and scripted_model are importable from your module.) A scripted fake model's replies are consumed in order, so build a fresh model per test, as the sample does per run. Test every branch of every router: a wrong routing value from an unannotated router fails silently (5.2).


Part 14: Changing a graph that is already running, and reading old tutorials#

Reference

14.1 Changing a graph that already has saved threads#

Once a graph runs with a checkpointer (08F.11), threads exist that were paused, or finished, under an older version of your code. Deploying a new graph version is then a migration. The docs' rules, which this lesson reproduces so you know them before you ever need persistence:

Topology (nodes and edges). The graph's edges are not stored in the checkpoint; a resumed run uses the saved state and the graph as compiled now.

Thread status Safe changes Do not
Finished Add, remove or rename nodes and edges freely Nothing to avoid: a finished thread only matters if you continue it with a new turn
Interrupted (paused, waiting) Change edges; add nodes Rename or remove the node the thread is about to enter. Resume looks the node up by name, and a missing name fails the run

State schema.

Change Effect on saved threads
Add a key Compatible: old threads simply lack it. Declare it NotRequired[...] and read it with .get so old state does not raise KeyError
Remove a key Compatible: the saved value is ignored
Rename a key The saved value is dropped: old threads lose it. Do it as add-the-new-key, migrate in a node, then remove the old one
Change a key's type incompatibly Can break old state, for example a stricter Pydantic type that old data fails

Practical habits that follow:

  • Add keys as NotRequired and treat removals as deprecations that live for a release.
  • If a business-logic change means "old threads must take the old path", stamp a flow_version on the state at the start of each thread and branch on it in the router.
  • Do not rename nodes that can be paused on. Add the new name, keep the old one routing to it, and remove the old one when no thread can be waiting there.
  • Nodes that use tasks or interrupt (08F.12) have stricter rules: changing the order of tasks or interrupts before a resume point can mismatch stored values.

14.2 Legacy names in old tutorials, and what replaced them#

LangGraph has been on a 1.x line since October 2025, and v1 was explicitly a stability release: custom graphs, checkpointers, interrupt, Command, Send and the in-memory saver "continue to work unchanged". So a graph from a 2024 tutorial usually still runs, but it may use names that have been renamed or deprecated. This table lets you read old code. Everything in the left column is legacy; write the right column.

You see in an old tutorial Status Write instead
from langgraph.prebuilt import create_react_agent, prompt=... Deprecated since 1.0 from langchain.agents import create_agent, system_prompt=... (08F.8, 08F.15)
MessageGraph() Deprecated since 1.0, removal planned for 2.0 StateGraph(MessagesState) or a state with a messages key (3.4)
StateGraph(State, config_schema=Config) Deprecated since 0.6 StateGraph(State, context_schema=Context) (Part 9)
StateGraph(State, input=..., output=...) Deprecated since 0.5 input_schema=..., output_schema=... (Part 8)
add_node("n", fn, retry=RetryPolicy()) and input=... Deprecated since 0.5 retry_policy=..., input_schema=... (4.6)
config["configurable"]["model"] for app settings Still works context= plus Runtime[Context] (Part 9); thread_id stays in configurable
from langgraph.constants import Send, Interrupt Deprecated import path from langgraph.types import Send, Interrupt
NodeInterrupt Deprecated interrupt() (08F.12)
AgentState, AgentStatePydantic and friends from langgraph.prebuilt Moved langchain.agents.AgentState (08F.8)
HumanInterruptConfig, ActionRequest, HumanInterrupt Replaced InterruptOnConfig and HITLRequest in langchain.agents.middleware.human_in_the_loop (08F.12)
ValidationNode Replaced create_agent validates tool input itself
MemorySaver Still accepted InMemorySaver is the current class name (08F.11)
langgraph-supervisor's create_supervisor The package is archived Subagents as tools with create_agent (08F.13)
"The recursion limit is 25" Old default 10,007 in current versions (11.2)
Python 3.9 Dropped in LangGraph 1.0 Python 3.10 for langgraph, 3.11 for langchain (this course: 3.11 or newer)

You do not have to take the table's word for the warnings. The sample below imports or constructs seven legacy names and prints what Python says about each (the lines are truncated for display):

python
# g20_deprecations.py: the legacy names you will meet in old tutorials, and what Python says about each
import warnings

from typing_extensions import TypedDict


class State(TypedDict):
    n: int


def show(label, fn):
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        try:
            fn()
            status = "works"
        except Exception as e:  # noqa: BLE001
            status = f"{type(e).__name__}: {str(e).splitlines()[0][:80]}"
    first = f"{caught[0].category.__name__}: {str(caught[0].message)[:110]}" if caught else "no warning"
    print(f"{label:34s}| {status}\n{'':34s}| {first}")


def message_graph():
    from langgraph.graph import MessageGraph
    MessageGraph()


def react_agent():
    from langgraph.prebuilt import create_react_agent
    from langchain_core.language_models import GenericFakeChatModel
    create_react_agent(GenericFakeChatModel(messages=iter([])), tools=[])


def config_schema():
    from langgraph.graph import StateGraph
    StateGraph(State, config_schema=dict)


def old_input_kwargs():
    from langgraph.graph import StateGraph
    StateGraph(State, input=State, output=State)


def old_send_import():
    from langgraph.constants import Send  # noqa: F401


def old_retry_kwarg():
    from langgraph.graph import StateGraph
    from langgraph.types import RetryPolicy
    StateGraph(State).add_node("a", lambda s: s, retry=RetryPolicy())


def old_node_interrupt():
    from langgraph.errors import NodeInterrupt
    NodeInterrupt("why")


for label, fn in [
    ("MessageGraph()", message_graph),
    ("create_react_agent(...)", react_agent),
    ("StateGraph(config_schema=...)", config_schema),
    ("StateGraph(input=..., output=...)", old_input_kwargs),
    ("from langgraph.constants import Send", old_send_import),
    ("add_node(..., retry=RetryPolicy())", old_retry_kwarg),
    ("NodeInterrupt(...)", old_node_interrupt),
]:
    show(label, fn)
Output14 lines
MessageGraph()                    | works
                                  | LangGraphDeprecatedSinceV10: MessageGraph is deprecated in LangGraph v1.0.0, to be removed in v2.0.0. Please use StateGraph with a `message
create_react_agent(...)           | works
                                  | LangGraphDeprecatedSinceV10: create_react_agent has been moved to `langchain.agents`. Please update your import to `from langchain.agents i
StateGraph(config_schema=...)     | works
                                  | LangGraphDeprecatedSinceV10: `config_schema` is deprecated and will be removed. Please use `context_schema` instead. Deprecated in LangGrap
StateGraph(input=..., output=...) | works
                                  | LangGraphDeprecatedSinceV05: `input` is deprecated and will be removed. Please use `input_schema` instead. Deprecated in LangGraph V0.5 to
from langgraph.constants import Send| works
                                  | LangGraphDeprecatedSinceV10: Importing Send from langgraph.constants is deprecated. Please use 'from langgraph.types import Send' instead.
add_node(..., retry=RetryPolicy())| works
                                  | LangGraphDeprecatedSinceV05: `retry` is deprecated and will be removed. Please use `retry_policy` instead. Deprecated in LangGraph V0.5 to
NodeInterrupt(...)                | works
                                  | LangGraphDeprecatedSinceV10: NodeInterrupt is deprecated. Please use `langgraph.types.interrupt` instead. Deprecated in LangGraph V1.0 to b

Every legacy name still works in 1.2.22 and prints a LangGraphDeprecated... warning that names its replacement. Python's default warning filters can hide some warnings (they show only once per location, and some categories are hidden outside __main__), so run your tests with warnings enabled (pytest lists them in its summary; python -W default shows them in scripts) and you will find them before an upgrade removes them.

Two more things that confuse readers of old material:

  • Two functions named create_react_agent. The deprecated one in langgraph.prebuilt and the very old one in langchain.agents (the pre-1.0 ReAct prompt agent) are different things, and both are replaced by create_agent (08F.4, Part 4).
  • Examples that quote model ids (claude-sonnet-4-6 in the docs' quickstart, gpt-4o in older posts) are placeholders that were current on the day they were written. Take current ids from 08F.5 and the provider's page.

Part 15: Pitfalls, real error messages and a checklist#

Reference

15.1 Errors you will meet#

The sample provokes five mistakes and prints the real messages and behaviour. It is the quickest way to recognize them in your own logs:

python
# g21_pitfalls.py: real error messages and silent traps, one at a time
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    items: Annotated[list[str], operator.add]
    note: str


def attempt(label, fn):
    try:
        print(f"{label}: OK ->", fn())
    except Exception as e:  # noqa: BLE001
        print(f"{label}: {type(e).__name__}: {' '.join(str(e).split())[:150]}")


# 1. invoking the builder instead of the compiled graph
builder = StateGraph(State)
builder.add_node("a", lambda s: {"note": "a"})
builder.add_edge(START, "a")
attempt("builder.invoke(...)", lambda: builder.invoke({"items": [], "note": ""}))

# 2. a node that mutates state in place instead of returning an update
def mutate(state: State):
    state["items"].append("sneaky")      # mutates the list object that happens to be shared
    state["note"] = "changed"            # rebinding a key on the dict you were handed


m = StateGraph(State).add_node(mutate).add_edge(START, "mutate").add_edge("mutate", END).compile()
attempt("in-place mutation", lambda: m.invoke({"items": ["original"], "note": "original"}))
print("   updates stream  :", list(m.stream({"items": ["original"], "note": "original"}, stream_mode="updates")))

# 3. reading a key that was never set (it is simply absent, not None)
def read_missing(state: State):
    return {"note": state["note"]}


r = StateGraph(State).add_node(read_missing).add_edge(START, "read_missing").add_edge("read_missing", END).compile()
attempt("missing key", lambda: r.invoke({"items": []}))

# 4. a checkpointer without a thread_id
c = StateGraph(State).add_node("a", lambda s: {"note": "a"}).add_edge(START, "a").add_edge("a", END).compile(checkpointer=InMemorySaver())
attempt("checkpointer, no thread_id", lambda: c.invoke({"items": [], "note": ""}))

# 5. recursion_limit under "configurable" is NOT the limit (the top-level key is)
steps = []


def tick(state: State):
    steps.append(1)
    return {"items": ["x"]}


loop = StateGraph(State).add_node(tick).add_edge(START, "tick").add_edge("tick", "tick").compile()
for label, cfg in [("top-level recursion_limit=5", {"recursion_limit": 5}),
                   ("configurable recursion_limit=5", {"configurable": {"recursion_limit": 5}})]:
    steps.clear()
    try:
        loop.invoke({"items": [], "note": ""}, cfg)
    except Exception as e:  # noqa: BLE001
        print(f"{label}: {type(e).__name__} after {len(steps)} steps: {str(e).split('.')[0]}")
Output7 lines
builder.invoke(...): AttributeError: 'StateGraph' object has no attribute 'invoke'
in-place mutation: OK -> {'items': ['original', 'sneaky'], 'note': 'original'}
   updates stream  : [{'mutate': None}]
missing key: KeyError: 'note'
checkpointer, no thread_id: ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_id
top-level recursion_limit=5: GraphRecursionError after 5 steps: Recursion limit of 5 reached without hitting a stop condition
configurable recursion_limit=5: GraphRecursionError after 10007 steps: Recursion limit of 10007 reached without hitting a stop condition
You see It means Fix
AttributeError: 'StateGraph' object has no attribute 'invoke' You ran the builder, not the compiled graph graph = builder.compile() then graph.invoke(...)
{'mutate': None} in the stream and a half-applied change A node mutated state and returned nothing Return the update. A list that two places share appeared to change; the plain key assignment state["note"] = ... was lost; and neither appears in the updates stream
KeyError: 'note' A key was read before anything wrote it (TypedDict keys are absent, not None) state.get("note"), NotRequired, or initialize it in the first node
ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, ... A graph compiled with a checkpointer was invoked with no thread_id Pass {"configurable": {"thread_id": "..."}} (08F.11)
GraphRecursionError after 10,007 steps A loop with no stop, and the limit was placed under configurable so it was ignored Top-level recursion_limit (Part 11)

The same mutating node with a checkpointer (a preview of 08F.11) shows that what the caller receives and what is saved can differ:

python
import operator
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    items: Annotated[list[str], operator.add]
    note: str


def mutate(state: State):
    state["items"].append("sneaky")
    state["note"] = "changed"


m = StateGraph(State).add_node(mutate).add_edge(START, "mutate").add_edge("mutate", END).compile(checkpointer=InMemorySaver())
cfg = {"configurable": {"thread_id": "1"}}
print("returned   :", m.invoke({"items": ["original"], "note": "original"}, cfg))
print("saved state:", m.get_state(cfg).values)
Output2 lines
returned   : {'items': ['original', 'sneaky'], 'note': 'original'}
saved state: {'items': ['original'], 'note': 'original'}

The appended list item reached the caller (the list object is shared) but not the saved state, and the note assignment reached neither. A resume or a time-travel replay from that checkpoint would start from the saved version. | InvalidUpdateError: At key 'x': Can receive only one value per step | Two parallel nodes wrote an un-reduced key | Add a reducer (3.3) | | InvalidUpdateError: Expected dict, got ... | A node returned a string or a list | Return a dict, None or a Command (4.2) | | TypeError: No synchronous function provided to "x" | An async node under invoke | Use ainvoke and astream (4.4) | | TypeError: f() missing 1 required positional argument: 'config' | A config parameter with the wrong annotation | Annotate it RunnableConfig (4.3) | | ValueError: Graph must have an entrypoint | No edge from START | add_edge(START, "first") (2.3) | | ValueError: Found edge ending at unknown node | An edge names a node that was never added | Check spelling and add_node (2.3) |

Python tracebacks from node code end with a line such as During task with name 'write' and id '...'. That line names the node that raised, which is the first thing to read.

15.2 Silent failures#

The failures above raise. The worst ones do not, and each is a place where a test that checks the final state of every path catches what no exception will:

Silent failure Where What to do
An unannotated routing function (no Literal, no path_map) returns a name that is not a node 5.2 Literal annotations (they turn it into a KeyError), total routers, a test per branch; watch for the unknown channel branch:to:... warning in logs
A list-form join whose branch was skipped never runs 5.4 defer=True for joins after conditional branches
A node that is connected to nothing never runs, and compile() does not notice 2.3 Draw the graph, assert on edges and on which nodes ran
A node returns a key that is not in the schema 4.2 Assert on the final state; type-check your returns
An empty Send list skips the reduce step 7.2 Handle the empty case explicitly
runtime.context is None when context= was not passed (and after a resume that omitted it) Part 9 Always pass it, or default defensively
recursion_limit under configurable is ignored Part 11 Top-level key
Drawing hides Command and router destinations 10.4 Annotate with Literal or set destinations=
In-place mutation of state 15.1 Return updates
stream_mode="values" shows private keys Part 8 output_keys= or updates
A reducer-less list is overwritten 3.2 Add operator.add

15.3 A pre-flight checklist#

Before you call a graph done:

  • Every node returns a dict, None or a Command, and none of them mutates state.
  • Every key written by parallel nodes or workers has a reducer that does not depend on arrival order.
  • Every router has a Literal return annotation or a path_map, returns only valid node names, and has a default branch.
  • Every node with Command(goto=...) has no static outgoing edges, and its return type lists its destinations.
  • Every join after a conditional or dynamic fork uses defer=True.
  • Every loop has a counter or flag in state, an explicit stop, and a limit sized to the job (and recursion_limit is a top-level config key).
  • Every irreversible action is its own node, after the decision, with an idempotency key.
  • Optional keys are NotRequired; callers see an input and an output schema, not the internals.
  • Context is passed on every call, including resumes, and runtime.context is handled when it is None.
  • Each path through the graph, including every escalation, has a test with a fake model; the topology is asserted from get_graph().
  • The graph has a name, and its drawing has been looked at by a second person.
  • Install commands and imports match the versions in your lockfile, and warnings are enabled in tests (08F.4, 5.10).

15.4 JavaScript, in one note#

LangGraph also ships for JavaScript and TypeScript as @langchain/langgraph, with the same ideas: StateGraph, nodes, edges, Command, Send, checkpointers. The docs say TypeScript uses a StateSchema where Python uses TypedDict, and camel-case names such as streamMode. timeout and error_handler are Python-only features of the 1.2 line, while retry policies exist in both. The JavaScript API names were not verified for this lesson; read the JavaScript docs at docs.langchain.com/oss/javascript/langgraph if you need them.


Common misconceptions#

Misconception Reality
"LangGraph is part of LangChain, so I need LangChain to use it." LangGraph is a separate package that needs only langchain-core. Nodes are plain Python functions; call any SDK inside them (1.2).
"A graph is for agents." A graph is for workflows with branches, loops, shared state, pauses or recovery. Many graphs have no model-chosen tool loop at all, and an agent is just one particular graph (Part 12).
"Nodes run one after another in the order I added them." Order of add_node calls means nothing. Edges decide, and nodes with edges from the same source run in parallel in one super-step (1.3).
"A node returns the new state." A node returns a partial update of only the keys it changes (or a Command, or None). Returning the whole state is unnecessary and, with reducers, wrong (3.2).
"Returning a list appends to the list in state." Only with a reducer such as operator.add. Without one, the new list replaces the old (3.2, 3.3).
"Returning [] clears a reduced list." It merges [] into the list and changes nothing. Return Overwrite([]) (3.5).
"Two parallel nodes can see each other's updates." They both read the state as it was before the super-step; their writes are applied together afterwards (1.3).
"compile() checks my graph." It rejects a missing entry edge and edges to unknown nodes. It does not detect orphaned nodes, unmapped routing values or a join that will never fire (2.3).
"A router that returns a wrong name always raises." Only when it has a Literal annotation or a path_map (then KeyError). An unannotated router ends the run silently, with a log warning (5.2).
"A join with several add_edge calls waits for all branches." Separate edges run the join once per arrival. Use the list form (unconditional branches) or defer=True (conditional or dynamic) (5.4).
"Command replaces edges completely." It adds a dynamic edge. Static edges from the same node still fire (6.1).
"Command(update=...) is how I send the next user message." As an input it only resumes from the latest checkpoint and can run nothing. A new turn is a plain dict (6.4).
"Send results arrive in the order I sent them." They arrive in completion order. Carry an ordering key and sort (7.2).
"An output schema hides my private keys from the stream." It filters invoke. stream_mode="values" and "updates" still show them (Part 8).
"runtime.context has my dataclass defaults if I pass nothing." It is None, and it is not restored from a checkpoint on resume (Part 9).
"The recursion limit is 25, so my loops are bounded." The default is 10,007 super-steps, and only the top-level recursion_limit key sets it (Part 11).
"invoke and stream return the same thing in different shapes." Their default modes differ (values versus updates). Pass stream_mode explicitly (10.2).
"The drawing shows what the graph does." It shows what the annotations declare. A router or Command without a Literal return type is drawn with an edge to END only (10.4).
"create_react_agent and MessageGraph are the standard tools." Both are deprecated; use create_agent and StateGraph with MessagesState (14.2).

Key takeaways#

  1. LangGraph is a low-level runtime for stateful workflows. You describe nodes (functions), edges (transitions) and state (a schema with merge rules); it runs them, and create_agent is built on it. It does not require LangChain, and a compiled graph is a Runnable.
  2. A run is a series of super-steps: plan, execute (nodes of one step run in parallel on the same snapshot), update (writes applied together through reducers). The step is transactional, checkpoints sit at its boundaries, and the recursion limit counts steps.
  3. State is typed channels. A key without a reducer is overwritten; a key with one merges. Use operator.add for lists, add_messages or MessagesState for conversations (it replaces same-id messages and honours RemoveMessage), custom reducers for everything else, and Overwrite to reset a reduced key. Parallel writers to an un-reduced key raise InvalidUpdateError.
  4. Nodes return partial updates, a Command or None; never mutate state. They receive config, runtime, writer and store by name. A node that is retried or resumed reruns from its first line, so side effects must be idempotent and irreversible actions deserve their own node.
  5. Edges: normal edges are fixed; conditional edges route on state with a pure function (annotate it Literal and make it total); loops are edges that point back, with a stop condition in state. Join branches with the list form (unconditional) or defer=True (conditional or dynamic); never mix static edges and Command(goto=...) on one node.
  6. Command(update, goto) updates and routes in one return value; prefer conditional edges for routing alone. Command.PARENT leaves a subgraph; a Command as an input only resumes and is not a way to start a turn.
  7. Send runs a node once per item of a list known only at run time, each with its own input; results merge through a reducer; arrival order is not guaranteed; an empty list skips the reduce step; cap parallelism with max_concurrency.
  8. Schemas: input_schema and output_schema shape the graph's contract; private state and narrow node inputs keep internals internal, but streams still show everything unless you restrict them. Context carries immutable per-run configuration (not state, not the store); it is None when not passed and is not saved in checkpoints.
  9. Limits: recursion_limit is a top-level config key, defaults to 10,007 and raises GraphRecursionError; use RemainingSteps for graceful exits and ModelCallLimitMiddleware for agents. Put business limits in state.
  10. Run and see: always pass stream_mode; use version="v2" for typed output; draw with draw_mermaid() (local), remember draw_mermaid_png() calls a web service, and annotate routers so drawings are true.
  11. Test without a model: nodes are functions, models are parameters, fake models script the paths, and get_graph() lets you assert on the topology. The silent failures (wrong names from unannotated routers, never-firing joins, orphans, ignored keys) are caught only by tests on every path.
  12. Legacy: create_react_agent, MessageGraph, config_schema, input=/output=, retry=, langgraph.constants imports and NodeInterrupt still run with warnings and have replacements (14.2). Persistence, human approval, subgraphs, streaming in depth and deployment are the next five lessons.

Terms introduced in this lesson#

Term One-line definition
LangGraph A low-level orchestration framework and runtime for stateful, long-running workflows and agents; the engine under create_agent
StateGraph The builder class: you add nodes and edges to it and call compile() to get a runnable graph
Node A function that reads the state and returns a partial update, a Command or None
Edge A transition between nodes: normal (fixed), conditional (chosen by a function) or dynamic (Command, Send)
START and END The virtual entry and exit nodes ("__start__" and "__end__")
State schema The TypedDict, dataclass or Pydantic model whose keys become the graph's channels
Channel The storage and update rule behind one state key: last value wins by default, or a reducer merges
Reducer A function (current, update) -> new attached to a key with Annotated, combining repeated and parallel writes
add_messages The reducer for conversation lists: appends, replaces same-id messages and deletes with RemoveMessage
MessagesState A prebuilt TypedDict with one messages key using add_messages; subclass it to add keys
Overwrite A wrapper that bypasses a key's reducer so a write replaces the value
Super-step One round of the runtime: plan, execute all triggered nodes in parallel, apply their writes together
Conditional edge An edge whose destination is computed from the state by a routing function
Command A return value (and a resume input) carrying a state update, a goto and optionally a graph target
Send A message that runs a named node with its own input; returned in lists to fan out over a runtime-sized collection
Map-reduce (in LangGraph) Fan-out with Send (map), then a reducer on a shared key and a join node (reduce)
defer=True A node option that delays the node until no other work is pending, so it joins conditional and dynamic branches once
Input, output and private schema The shapes a graph accepts, returns and passes privately between nodes
Runtime context Immutable per-run configuration passed as context= and read through runtime.context; declared with context_schema
Runtime The object injected into a node as runtime: context, store, stream writer and execution info
Recursion limit The maximum number of super-steps in one run (default 10,007); exceeding it raises GraphRecursionError
RemainingSteps A managed state value holding the number of super-steps left, for graceful exits
ToolNode and tools_condition The prebuilt node that runs the last AIMessage's tool calls, and the router that loops to it while tool calls remain
get_graph() The method returning a drawable structure (draw_mermaid, draw_ascii, draw_png) and the nodes and edges as data

Exercises#

All of these run with no API key. Use uv run python file.py in the lesson's project.

  1. A reducer that keeps the best three. Two parallel nodes scorer_a and scorer_b each write a list of float scores to the same key. First write the graph with a plain list[float] key and read the error. Then fix it with a custom reducer that keeps only the three highest scores in total, in descending order. Predict the result for [0.4, 0.9] and [0.7, 0.2, 0.95] before you run it.
  2. A join that always fires once. Build start -> (base, and sometimes extra) -> report, where a router returns ["base", "extra"] when state["want_extra"] is true and ["base"] otherwise. First join with add_edge(["base", "extra"], "report") and observe the want_extra=False case. Then make report run exactly once in both cases.
  3. A total router. A fake classifier returns the labels "Billing.", "shipping", "refund?" and "". Route them to billing, shipping or human nodes. Normalize the label, make every input reach a node, annotate the router so a drawing shows the real destinations, and print the edges leaving START. Then change the router to return "nowhere" for one label and observe what happens, and observe it again after deleting the Literal annotation.
  4. Map-reduce with an empty case. Write a graph that counts the words in each of a list of documents with Send, and reduces to one report line. Make the empty list produce no documents instead of silently skipping the reduce step.
  5. Context. Write a greeting graph with a Context dataclass (tenant, formal) so the same graph greets differently per call. It must work when the caller passes no context. Then explain, in one sentence, what would break if you resumed an interrupted thread without passing context= again.
  6. Graceful exit. Write a refinement loop that adds one character per iteration and stops itself two steps before a recursion limit of 7, using RemainingSteps, and returns the best draft so far. Show that the same loop without the guard raises GraphRecursionError.
  7. Two tools in one turn. Using the fake-model subclass from 12.1, script a model reply with two tool calls in one AIMessage, build the model, tools and loop by hand, and print the message types and the tool results. How many model calls happened?
  8. Pin the topology. Take the Command[Literal[...]] graph from 6.1 and write an assertion that fails if anyone changes its edges. Then remove the return annotation on the routing node and see what the assertion reports.
  9. A migration plan. Your graph's state has a key customer holding a string name, and 400 interrupted threads exist. You want it to hold a dict {"name": ..., "tier": ...}. Using 14.1, write the rollout steps (no code needed) that avoid breaking the 400 threads.
  10. Translate an old tutorial. Rewrite this snippet with current names, and list what each changed line was replaced by:
python
from langgraph.graph import MessageGraph, END
from langgraph.constants import Send
from langgraph.prebuilt import create_react_agent

class Config(dict): ...
workflow = MessageGraph()
agent = create_react_agent(model, tools=[], prompt="You are a support agent.")
app = StateGraph(State, config_schema=Config, input=InputState, output=OutputState)
app.add_node("fetch", fetch, retry=RetryPolicy(max_attempts=3))
Answers and hints
  1. With a plain list[float] key and two parallel writers, InvalidUpdateError: At key 'scores': Can receive only one value per step.... A reducer that merges and trims works. The prediction: the six values are 0.4, 0.9, 0.7, 0.2, 0.95, so the top three are 0.95, 0.9, 0.7. Run on 14 November 2026:
python
# ex1_top_k.py: two parallel scorers write the same key; a custom reducer keeps the three best scores
import heapq
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


def top3(left: list[float], right: list[float]) -> list[float]:
    return heapq.nlargest(3, [*left, *right])      # a new list; order-independent


class State(TypedDict):
    scores: Annotated[list[float], top3]


def scorer_a(state: State):
    return {"scores": [0.4, 0.9]}


def scorer_b(state: State):
    return {"scores": [0.7, 0.2, 0.95]}


g = StateGraph(State)
g.add_node(scorer_a)
g.add_node(scorer_b)
g.add_edge(START, "scorer_a")
g.add_edge(START, "scorer_b")
g.add_edge("scorer_a", END)
g.add_edge("scorer_b", END)
print(g.compile().invoke({"scores": []}))
Output1 line
{'scores': [0.95, 0.9, 0.7]}

The reducer is order-independent (it sorts what it has), builds a new list and never mutates left, as 3.3 requires.

  1. With the list form, add_edge(["base", "extra"], "report"), when want_extra is false the router skips extra, so report never runs and no error appears (5.4). The fix is separate edges plus defer=True on report. Run:
python
# ex2_join_once.py: a join after a conditional fork that runs exactly once, whichever branches were taken
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    want_extra: bool
    trace: Annotated[list[str], operator.add]


def node(name):
    def fn(state: State):
        return {"trace": [name]}
    fn.__name__ = name
    return fn


def fork(state: State):
    return ["base", "extra"] if state["want_extra"] else ["base"]


g = StateGraph(State)
for n in ("start", "base", "extra"):
    g.add_node(node(n))
g.add_node("report", node("report"), defer=True)
g.add_edge(START, "start")
g.add_conditional_edges("start", fork, ["base", "extra"])
g.add_edge("base", "report")
g.add_edge("extra", "report")
g.add_edge("report", END)
graph = g.compile()
for want in (True, False):
    print(want, graph.invoke({"want_extra": want, "trace": []})["trace"])
Output2 lines
True ['start', 'base', 'extra', 'report']
False ['start', 'base', 'report']
  1. The router lower-cases, strips punctuation and sends anything unknown (refund?, "") to human; the Literal return annotation makes the drawing show three edges from START. Run:
python
# ex3_total_router.py: a total router: every label maps to a node, unknown labels go to a default
import logging
from typing import Literal

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph

logging.basicConfig(level=logging.WARNING, format="LOG %(message)s")


class State(TypedDict):
    label: str
    handled_by: str


def make(name):
    def fn(state: State):
        return {"handled_by": name}
    fn.__name__ = name
    return fn


KNOWN = {"billing", "shipping"}


def route(state: State) -> Literal["billing", "shipping", "human"]:
    label = state["label"].strip().lower().rstrip(".?!")      # normalise model output first
    return label if label in KNOWN else "human"                # explicit default branch


g = StateGraph(State)
for n in ("billing", "shipping", "human"):
    g.add_node(make(n))
g.add_conditional_edges(START, route)
for n in ("billing", "shipping", "human"):
    g.add_edge(n, END)
graph = g.compile()
for label in ["Billing.", "shipping", "refund?", ""]:
    print(repr(label), "->", graph.invoke({"label": label})["handled_by"])
print("edges from START:", sorted(e.target for e in graph.get_graph().edges if e.source == "__start__"))
Output5 lines
'Billing.' -> billing
'shipping' -> shipping
'refund?' -> human
'' -> human
edges from START: ['billing', 'human', 'shipping']

With return "nowhere" for one label, the annotated router makes the run fail with KeyError: 'nowhere'. Delete the Literal annotation and the same graph does not raise at all: the run ends with handled_by unset and only a log line, wrote to unknown channel branch:to:nowhere, ignoring it (5.2, which ran both cases). Either way the fix is the default branch: a router must never return a name it has not mapped.

  1. Route the empty case to the report node. A deferred report node plus an extra add_edge(START, "report") does it: the report runs once, after any workers finished, and also runs when there are none. Run:
python
# ex4_map_empty.py: map-reduce that still produces a report when there is nothing to map
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Send


class State(TypedDict):
    docs: list[str]
    lengths: Annotated[list[tuple[int, int]], operator.add]
    report: str


class Worker(TypedDict):
    idx: int
    text: str


def measure(state: Worker):
    return {"lengths": [(state["idx"], len(state["text"].split()))]}


def fan_out(state: State):
    return [Send("measure", {"idx": i, "text": t}) for i, t in enumerate(state["docs"])]


def report(state: State):
    if not state["lengths"]:
        return {"report": "no documents"}
    return {"report": ", ".join(f"doc {i}: {n} words" for i, n in sorted(state["lengths"]))}


g = StateGraph(State)
g.add_node(measure)
g.add_node("report", report, defer=True)       # runs when nothing else is pending, even if nothing was mapped
g.add_conditional_edges(START, fan_out, ["measure"])
g.add_edge("measure", "report")
g.add_edge(START, "report")                    # so the empty case still reaches the report node
g.add_edge("report", END)
graph = g.compile()
print(graph.invoke({"docs": ["one two three", "four five"]})["report"])
print(graph.invoke({"docs": []})["report"])
Output2 lines
doc 0: 3 words, doc 1: 2 words
no documents

An alternative is a router that returns "report" instead of an empty list when docs is empty.

  1. A dataclass context with defaults, read as runtime.context or Context() (Part 9). Run:
python
# ex5_context_greeting.py: per-tenant behaviour from runtime context, safe when no context is passed
from dataclasses import dataclass

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime


@dataclass
class Context:
    tenant: str = "default"
    formal: bool = False


class State(TypedDict):
    name: str
    greeting: str


def greet(state: State, runtime: Runtime[Context]):
    ctx = runtime.context or Context()
    opener = "Dear" if ctx.formal else "Hi"
    return {"greeting": f"{opener} {state['name']}, welcome to {ctx.tenant}."}


graph = StateGraph(State, context_schema=Context).add_node(greet).add_edge(START, "greet").add_edge("greet", END).compile()
print(graph.invoke({"name": "Asha"})["greeting"])
print(graph.invoke({"name": "Asha"}, context={"tenant": "Northwind", "formal": True})["greeting"])
Output2 lines
Hi Asha, welcome to default.
Dear Asha, welcome to Northwind.

On resume without context=, the node would see None instead of the tenant's settings, because the context is not stored in the checkpoint (the sample in Part 9 ran it): code that reads runtime.context.tenant raises AttributeError, and code that falls back to defaults would silently use the wrong tenant's settings.

  1. The guard checks remaining_steps <= 2 after each improvement. Run:
python
# ex6_wrap_up.py: a refinement loop that stops gracefully before the recursion limit
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
from langgraph.managed.is_last_step import RemainingSteps


class State(TypedDict):
    draft: str
    notes: Annotated[list[str], operator.add]
    remaining_steps: RemainingSteps


def improve(state: State):
    return {"draft": state["draft"] + "+", "notes": [f"improved (steps left: {state['remaining_steps']})"]}


def finish(state: State):
    return {"notes": ["finished early: returning the best draft so far"]}


def keep_going(state: State):
    return "finish" if state["remaining_steps"] <= 2 else "improve"      # never reaches the wall


g = StateGraph(State)
g.add_node(improve)
g.add_node(finish)
g.add_edge(START, "improve")
g.add_conditional_edges("improve", keep_going)
g.add_edge("finish", END)
graph = g.compile()
result = graph.invoke({"draft": "v", "notes": []}, {"recursion_limit": 7})
print(result["draft"], result["notes"])

# the same loop without the guard hits the wall
g2 = StateGraph(State)
g2.add_node(improve)
g2.add_edge(START, "improve")
g2.add_edge("improve", "improve")
try:
    g2.compile().invoke({"draft": "v", "notes": []}, {"recursion_limit": 7})
except GraphRecursionError:
    print("unguarded loop: GraphRecursionError")
Output2 lines
v+++++ ['improved (steps left: 6)', 'improved (steps left: 5)', 'improved (steps left: 4)', 'improved (steps left: 3)', 'improved (steps left: 2)', 'finished early: returning the best draft so far']
unguarded loop: GraphRecursionError

The guarded loop made five improvements and finished at step 6 of 7; the unguarded one ran into the limit.

  1. One AIMessage with two tool_calls; ToolNode returned two ToolMessages, and the model was called twice in total (once to ask, once to answer). Run:
python
# ex7_two_tools.py: a hand-written agent loop where the model calls two tools in ONE turn
from langchain.messages import AIMessage
from langchain.tools import tool
from langchain_core.language_models import GenericFakeChatModel
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition


class ToolFakeChatModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self


@tool
def order_status(order_id: str) -> str:
    """Look up an order's shipping status."""
    return f"{order_id}: shipped"


@tool
def refund_policy(country: str) -> str:
    """Return the refund window for a country."""
    return f"{country}: 30 days"


tools = [order_status, refund_policy]
script = iter([
    AIMessage(content="", tool_calls=[
        {"name": "order_status", "args": {"order_id": "A-1"}, "id": "c1"},
        {"name": "refund_policy", "args": {"country": "Canada"}, "id": "c2"},
    ]),
    AIMessage(content="A-1 has shipped, and Canadian refunds have a 30-day window."),
])
model = ToolFakeChatModel(messages=script).bind_tools(tools)


def call_model(state: MessagesState):
    return {"messages": [model.invoke(state["messages"])]}


g = StateGraph(MessagesState)
g.add_node("model", call_model)
g.add_node("tools", ToolNode(tools))
g.add_edge(START, "model")
g.add_conditional_edges("model", tools_condition)
g.add_edge("tools", "model")
agent = g.compile()
result = agent.invoke({"messages": [("user", "Where is A-1, and what is the refund window in Canada?")]})
print([(m.type, len(getattr(m, "tool_calls", []) or [])) for m in result["messages"]])
print([m.content for m in result["messages"] if m.type == "tool"])
Output2 lines
[('human', 0), ('ai', 2), ('tool', 0), ('tool', 0), ('ai', 0)]
['A-1: shipped', 'Canada: 30 days']

Reading the first list: the user message, the AI message with 2 tool calls, two tool messages, and the final AI message.

  1. Compare the set of (source, target) pairs from graph.get_graph().edges with the expected set. Run:
python
# ex8_edge_test.py: assert on a graph's topology, so a refactor cannot silently change the wiring
from typing import Literal

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph
from langgraph.types import Command


class State(TypedDict):
    n: int


def a(state: State) -> Command[Literal["b", "c"]]:
    return Command(goto="b" if state["n"] > 0 else "c")


def b(state: State):
    return {"n": state["n"] + 1}


def c(state: State):
    return {"n": 0}


g = StateGraph(State).add_node(a).add_node(b).add_node(c)
g.add_edge(START, "a")
g.add_edge("b", END)
g.add_edge("c", END)
graph = g.compile()

EXPECTED = {("__start__", "a"), ("a", "b"), ("a", "c"), ("b", "__end__"), ("c", "__end__")}
actual = {(e.source, e.target) for e in graph.get_graph().edges}
assert actual == EXPECTED, f"topology changed: {actual ^ EXPECTED}"
print("topology OK:", len(actual), "edges")
print("n=5 ->", graph.invoke({"n": 5}), "| n=0 ->", graph.invoke({"n": 0}))
Output2 lines
topology OK: 5 edges
n=5 -> {'n': 6} | n=0 -> {'n': 0}

If you delete -> Command[Literal["b", "c"]] from a, the drawn edges from a collapse to a single edge to __end__ (10.4), so the assertion fails with a message that lists the differing edges. That is the point of the test: the routing is still correct at run time, but the declared topology changed.

  1. A safe rollout: (1) add a new key customer_profile: NotRequired[dict] and keep customer; (2) deploy code that writes both and reads the new key, falling back to the old (state.get("customer_profile") or {"name": state["customer"], "tier": "standard"}); (3) wait until the 400 interrupted threads have finished or been migrated by a one-off update; (4) deploy code that reads only the new key; (5) remove customer later. Renaming in place would drop the saved value for every old thread (14.1), and a flow_version stamp lets you branch if old threads must follow old logic.

  2. The current form:

python
from langgraph.graph import END, StateGraph, MessagesState
from langgraph.types import Send, RetryPolicy
from langchain.agents import create_agent
from dataclasses import dataclass

@dataclass
class Context:
    ...

workflow = StateGraph(MessagesState)                                  # was MessageGraph()
agent = create_agent(model, tools=[], system_prompt="You are a support agent.")   # was create_react_agent(..., prompt=...)
app = StateGraph(State, context_schema=Context, input_schema=InputState, output_schema=OutputState)
app.add_node("fetch", fetch, retry_policy=RetryPolicy(max_attempts=3))

MessageGraph became StateGraph with MessagesState; langgraph.constants.Send moved to langgraph.types; langgraph.prebuilt.create_react_agent(prompt=...) became langchain.agents.create_agent(system_prompt=...); config_schema became context_schema (with a dataclass instead of a dict); input and output became input_schema and output_schema; and retry became retry_policy. RetryPolicy is imported from langgraph.types (08F.12). The fragment above is not run (it needs a model).


Check yourself#

  1. What are the three things a LangGraph program is made of, and what does compile() return?
  2. Two nodes have edges from the same source node. In what order do they run, and can one see the other's output?
  3. What is a super-step, and what are its three phases?
  4. A node returns {"log": ["x"]} and the earlier entries vanish. Why, what is the fix, and what must a reducer take, return and avoid?
  5. How do you clear a list that has an operator.add reducer?
  6. What happens when two parallel nodes write the same key that has no reducer?
  7. What happens when a routing function returns a name that is not a node?
  8. Name the three ways to join parallel branches and what each does when a branch is skipped.
  9. When should you use Command instead of a conditional edge, and what must you do to the node's edges?
  10. What does Send do, why must worker results go through a reducer, and what happens with an empty list?
  11. How do input, output and private schemas differ, and which of them does stream_mode="values" respect?
  12. What is the difference between runtime.context, state and the store? What is runtime.context when you pass nothing?
  13. What is the default recursion limit, where must the key go, and what are two ways to exit a loop gracefully?
  14. How do you draw a graph without a network call, and why does the annotation on a router matter?
  15. What does ToolNode do on a tool that raises, on bad arguments and on an unknown tool name, by default?

Further resources#

Official sources only. The LangGraph documentation is larger and moves faster than this lesson; where the docs are more complete (they are, for every option, stream mode and integration), read them. 08F.17 is the closing lesson that says how.


← 08F.9: RAG with LangChain | Module 08F overview | 08F.11: Persistence, Durable Execution and Memory →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close