08F.12 Human-in-the-Loop and Control Flow

Agents & multimodalLesson 12 of 1717,413 words13 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

A graph that runs from start to finish without stopping is the easy case. Real workflows stop: a manager has to approve a refund, a reviewer has to fix a draft, a payment API times out, a process is shut down for a deploy while a job is half done. 08F.10 taught how a graph runs; 08F.11 taught how its state is saved between steps. This lesson is about what you do with those two capabilities: pausing a run to wait for a person, resuming it with their answer, and everything that decides what happens when a step does not go to plan, namely retries, error handlers, timeouts, caching and cancellation.

The centrepiece is one function, interrupt(). Call it inside a node and the run stops, its state is saved, and your program gets a question to show a person; call the graph again with Command(resume=...) and interrupt() returns the answer and the run continues, minutes or days later, possibly in a different process. The function is small but it comes with rules that every learner breaks once (the node restarts from its first line, answers are matched by position, a bare except swallows the pause), so this lesson shows each rule failing before it shows the fix. The second half covers the failure-handling features added in LangGraph 1.2: retry policies with their exact default rule, error handlers for compensation flows, timeouts, node caching and graceful shutdown. Nearly every sample runs on your machine without an API key (plain-Python nodes, scripted fake models, in-memory checkpointers), and every output shown is the real output of that run.

What you'll learn

  • Why a long-running workflow needs a durable pause, and the three requirements of interrupt(): a checkpointer, a thread id and a serializable payload
  • The anatomy of a pause: the Interrupt object (value, id, response_schema), the four places a pending interrupt can be read, and the documented (beta) event-streaming resume loop
  • Resuming with Command(resume=...): what values are legal, the resume map for several pending interrupts, typed and validated answers with response_schema, and the forms that do not work (resume=None, Command(update=...) alone)
  • The re-execution rule: the node restarts from its first line on every resume, and what that means for code placed before interrupt()
  • The patterns: approve or reject with Command(goto=...), review and edit, validating human input with a loop, several questions in one node, parallel interrupts, interrupts inside tools, and graphs called as functions
  • The rules of interrupts, each shown failing: no bare except, position-based matching, serializable values, idempotent side effects, and how interrupts interact with retries
  • Static breakpoints (interrupt_before, interrupt_after), why the docs recommend interrupt() instead for human-in-the-loop, and the silent traps
  • How HumanInTheLoopMiddleware is built on interrupt, and a decision table for the four ways to pause
  • Failure handling: RetryPolicy and the exact default retry rule (with a table of real results), at-least-once semantics and idempotency keys, error handlers and NodeError, set_node_defaults, and a recovery-strategy table
  • Timeouts (timeout=, TimeoutPolicy, run versus idle, heartbeats, async only), node caching (CachePolicy, InMemoryCache, SqliteCache, key functions, ttl), graceful shutdown (RunControl, GraphDrained) and aborting a stream
  • A complete refund workflow that combines all of it, with tests that need no model, then the legacy names you will meet in old tutorials and a failure gallery

What you don't need

  • An API key. Every runnable sample uses plain-Python nodes, a scripted fake model or none at all. One sample (the human-as-a-tool agent in 3.6) calls a real provider and is labelled illustrative.
  • Checkpointers in depth. 08F.11 owns them (backends, threads, history, time travel, serializers). Here an in-memory checkpointer is only the thing that makes a pause possible.
  • Graph basics (state, reducers, Command, Send). 08F.10 owns them and this lesson builds on them.
  • Approval design: what a reviewer should see, how to word a confirmation, when to escalate. 08A.12 owns the gate pattern; 08A.14, 2.5 and 08A.14, Part 6 own that. This lesson owns the LangGraph mechanics.
  • Subgraphs and multi-agent handoffs (08F.13), the Functional API and streaming modes (08F.14), and LangSmith and the Agent Server (11A.5). They appear only where an interrupt or a retry touches them.
  • Provider-level retries and rate limits. 03.8 owns them; Part 7 explains how they stack with graph retries.

Setup

You need Python 3.11 or newer and uv; see 08F.4, Part 5 for the project setup.

bash
uv init hitl-lab --bare --python 3.13 && cd hitl-lab   # first time only
uv add langgraph langchain
uv add langgraph-checkpoint-sqlite                     # only for the SQLite node cache (9.4)
uv add --dev pytest                                    # only for the tests in Part 11
uv add python-dotenv langchain-openai                  # only for the one illustrative sample (3.6)
# or: pip install langgraph langchain langgraph-checkpoint-sqlite pytest python-dotenv langchain-openai

No .env file is needed for the runnable samples. Run each sample with uv run python file.py. Part 11's samples are several files in one folder (refund_flow.py, refund_demo.py, test_refund_flow.py); keep them together.

Versions (current at time of writing, read from PyPI on 14 November 2026; langgraph ships a patch release roughly weekly, so treat these as a snapshot): langgraph 1.2.22, langgraph-prebuilt 1.1.2, langgraph-checkpoint 4.3.2, langgraph-checkpoint-sqlite 3.1.3, langchain 1.5.0, langchain-core 1.8.0 and pydantic 2.14.3 (a later langchain-core patch, 1.8.2, gave the same output when the samples were re-run on 18 November 2026). Every sample marked as run was executed on 14 November 2026 with Python 3.13.14 and these versions, using uv run --no-project --python 3.13 --with langgraph --with langchain python -I sample.py. The docs and the package source were checked on the same day. A few features need a minimum version, noted where they appear: typed resume values need langgraph>=1.2.12, per-interrupt ids need 1.2.20, and the timeout, error-handler, node-defaults and graceful-shutdown features are part of the 1.2 line.


What you must be able to do after this lesson#

  • Pause a graph with interrupt and resume it with Command
  • Explain why a node restarts from its first line on resume
  • Build an approve, reject and edit flow
  • Follow the rules of interrupts and avoid the classic traps
  • Build a refund workflow with a human approval step

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The agent should ask a human before it sends the email." Part 1, 3.6 and Part 6
"How does the graph remember where it was while I wait?" 1.2
"Why did my code before interrupt() run twice?" 1.6 and 4.4
"My interrupt never pauses." 4.1
"I get a RuntimeError about multiple pending interrupts." 3.5
"Can the reviewer's answer be validated?" 2.4 and 3.3
"Should I use interrupt_before or interrupt()?" Part 5 and 6.3
"Which exceptions does LangGraph retry by default?" 7.2
"We charged the customer twice after a timeout." 7.4
"What happens after the retries run out?" 7.5
"My node hangs forever on a model call." Part 8
"Can I cache a slow node between runs?" Part 9
"How do I stop a run cleanly during a deploy?" Part 10
"This tutorial uses NodeInterrupt or interrupt_before=['tools']." Part 12

Part 1: Pausing a graph: the idea and your first interrupt#

1.1 Why a run needs a durable pause#

An agent that sends emails, issues refunds or deletes records should not do it unsupervised on day one. 08A.14, Part 2 explains why and when a person should confirm an action. The engineering question is how to build the confirmation. There are three common answers, and only the third survives contact with production. 08A.12 section 4.1 explains the same save-and-stop idea without a framework.

Approach How it works Where it breaks
Block on input() or a blocking call The function waits in memory for the answer Dies with the process; ties up a worker or a request for as long as the person takes; cannot be deployed behind a normal web server
Poll a flag The graph loops, sleeping and checking a database row You wrote a scheduler and a state machine by hand, and every workflow needs its own copy
Save and stop The run ends, its state is stored, and a later call continues it Needs a runtime that can resume mid-workflow, which is what a checkpointer gives you

LangGraph implements the third. interrupt() ends the current run normally from the caller's point of view: invoke returns, with the question in its result. Nothing is waiting in memory. The saved checkpoint (08F.11) holds the state and the pending question. When the person answers, you call the graph again on the same thread id with Command(resume=answer); the node that paused runs again, interrupt() returns the answer instead of pausing, and the run continues. Between the two calls the process can exit, the server can redeploy, and a week can pass.

1.2 The mechanism in one picture#

sequenceDiagram
    participant App as Your app
    participant G as Compiled graph
    participant CP as Checkpointer
    participant P as Person
    App->>G: invoke(input, thread_id=T)
    G->>G: node runs up to interrupt(question)
    G->>CP: save state and the pending question for T
    G-->>App: returns with the interrupt in the result
    App->>P: show the question
    Note over App,P: minutes, hours or days pass, the process may restart
    P-->>App: answer
    App->>G: invoke(Command(resume=answer), thread_id=T)
    G->>CP: load state for T
    G->>G: node restarts, interrupt() returns the answer
    G-->>App: final result

Two details in the diagram carry most of the lesson. First, the pause is a return, not a wait, so your application code must look at the result and decide whether it is finished or waiting. Second, on resume the node restarts; interrupt() is not a coroutine suspended in memory that wakes up where it slept. Section 1.6 shows what that implies.

1.3 Your first interrupt#

The smallest complete example: one node writes a draft reply, the next asks a person to review it.

python
# h01_first_interrupt.py: the smallest interrupt: pause, read the question, resume with an answer
from typing_extensions import TypedDict

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


class State(TypedDict):
    draft: str
    verdict: str


def write_draft(state: State):
    return {"draft": "Dear customer, your refund of 480 EUR is on its way."}


def human_review(state: State):
    # The first time this line runs, the graph stops here. On resume it returns the human's answer.
    answer = interrupt({"question": "Send this reply?", "draft": state["draft"]})
    return {"verdict": answer}


builder = StateGraph(State)
builder.add_node("write_draft", write_draft)
builder.add_node("human_review", human_review)
builder.add_edge(START, "write_draft")
builder.add_edge("write_draft", "human_review")
builder.add_edge("human_review", END)
graph = builder.compile(checkpointer=InMemorySaver())     # a checkpointer is mandatory

config = {"configurable": {"thread_id": "ticket-1001"}}   # the thread id is how the pause is found again

first = graph.invoke({"draft": "", "verdict": ""}, config)
print("first call returned:", first)
print("pending interrupt  :", first["__interrupt__"][0].value)
print("next node to run   :", graph.get_state(config).next)

second = graph.invoke(Command(resume="approved"), config)  # same thread id
print("second call returned:", second)
print("next node to run    :", graph.get_state(config).next)
Output5 lines
first call returned: {'draft': 'Dear customer, your refund of 480 EUR is on its way.', 'verdict': '', '__interrupt__': [Interrupt(value={'question': 'Send this reply?', 'draft': 'Dear customer, your refund of 480 EUR is on its way.'}, id='292d9b5c8e84c093993effe1c6713106', response_schema=None)]}
pending interrupt  : {'question': 'Send this reply?', 'draft': 'Dear customer, your refund of 480 EUR is on its way.'}
next node to run   : ('human_review',)
second call returned: {'draft': 'Dear customer, your refund of 480 EUR is on its way.', 'verdict': 'approved'}
next node to run    : ()

Read it line by line:

  • interrupt(...) took any serializable value (here a dict with a question and the draft). That value is what your application shows to the person.
  • The first invoke returned instead of raising. The result is the state so far plus an extra key, __interrupt__, holding the pending Interrupt objects. graph.get_state(config).next says which node is waiting: ('human_review',).
  • The second invoke passed Command(resume="approved") with the same thread_id. The value "approved" became the return value of interrupt(...) inside the node, and the node wrote it to verdict. The graph finished and next is empty.
  • The checkpointer is not optional, and thread_id is how the second call finds the first call's saved run (08F.11 owns threads and checkpoints).

1.4 The Interrupt object and the signature#

text
from langgraph.types import interrupt, Command, Interrupt

interrupt(value, *, response_schema=None)    # returns the resume value
Piece What it is
value What you want the person to see. Any JSON-serializable value: string, number, bool, list or dict. Not a function or a class instance
response_schema Optional (needs langgraph>=1.2.12). A Pydantic model class, TypedDict or dataclass that describes and validates the answer (2.4)
Interrupt.value The value you passed, on the pending interrupt
Interrupt.id A 32-character hex string that identifies this one pause; use it to answer a specific interrupt (3.5)
Interrupt.response_schema The JSON Schema form of response_schema, for a UI that renders a typed form, or None

interrupt() works by raising a special exception (an internal GraphInterrupt) the first time it is called in a task. The runtime catches it, saves state and surfaces an Interrupt. On resume, the same call returns the resume value instead of raising. That one fact explains the exception rule in 4.1.

1.5 The three requirements, and the errors you get without them#

interrupt() needs three things. Each fails in its own way, and one of the failures is quiet.

python
# h03_requirements.py: the three things interrupt() needs, and the errors you get without them
from typing_extensions import TypedDict

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


class State(TypedDict):
    answer: str


class Order:                       # an arbitrary class instance: not JSON-friendly
    def __init__(self, order_id: str):
        self.order_id = order_id


def ask(state: State):
    return {"answer": interrupt("approve?")}


def ask_object(state: State):
    return {"answer": interrupt({"order": Order("A-1")})}


def build(node, checkpointer):
    return (StateGraph(State).add_node("ask", node).add_edge(START, "ask").add_edge("ask", END)
            .compile(checkpointer=checkpointer))


# 1. no checkpointer at all
graph = build(ask, None)
try:
    print("1. no checkpointer, first call:", graph.invoke({"answer": ""}))
except Exception as error:
    print("1. no checkpointer, first call:", type(error).__name__, "-", error)
try:
    graph.invoke(Command(resume="yes"))
except Exception as error:
    print("   resume:", type(error).__name__, "-", error)

# 2. a checkpointer but no thread_id
graph = build(ask, InMemorySaver())
try:
    graph.invoke({"answer": ""})
except Exception as error:
    print("2. no thread_id:", type(error).__name__, "-", str(error)[:110])

# 3. a payload that is not plain data
graph = build(ask_object, InMemorySaver())
config = {"configurable": {"thread_id": "obj"}}
try:
    result = graph.invoke({"answer": ""}, config)
    print("3. object payload accepted by InMemorySaver:", result["__interrupt__"][0].value)
except Exception as error:
    print("3. object payload:", type(error).__name__, "-", str(error)[:140])
Output4 lines
1. no checkpointer, first call: {'answer': '', '__interrupt__': [Interrupt(value='approve?', id='8ca0933e825959b7df38e4815aa2861f', response_schema=None)]}
   resume: RuntimeError - Cannot use Command(resume=...) without checkpointer
2. no thread_id: ValueError - Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_i
3. object payload: TypeError - Type is not msgpack serializable: Interrupt
  1. A checkpointer. Without one, the first invoke still returns the interrupt (so a demo looks fine), but there is nothing saved to continue: the resume raises RuntimeError: Cannot use Command(resume=...) without checkpointer. A graph that pauses without a checkpointer is a bug that only shows when the answer arrives.
  2. A thread id. With a checkpointer, config["configurable"]["thread_id"] is mandatory; its absence raises a ValueError naming the missing keys.
  3. A serializable payload. The checkpointer must be able to store the interrupt value. A plain class instance made the in-memory saver's serializer raise a TypeError in this run. The message names Interrupt because the checkpointer is serialising the Interrupt object that wraps your Order; the unserialisable part is the Order inside its value. Send dicts of strings, numbers and lists, and rebuild objects on the other side. 08F.11 covers serializers and what each backend accepts.

1.6 Re-execution: the node restarts from its first line#

This is the rule that surprises everyone. On resume LangGraph does not continue inside the paused function; it calls the node again from the top, and this time interrupt() returns the answer. Everything above the interrupt() line therefore runs twice: once before the pause and once after.

python
# h02_reexecution.py: on resume the node restarts from its FIRST line, so code above interrupt() runs again
from typing_extensions import TypedDict

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

calls = {"charge_card": 0, "audit_log": []}


class State(TypedDict):
    result: str


def refund(state: State):
    calls["audit_log"].append("refund node started")        # runs on EVERY attempt of this node
    calls["charge_card"] += 1                               # a non-idempotent side effect ABOVE the interrupt
    ok = interrupt("Approve the refund?")
    calls["audit_log"].append(f"refund node resumed with {ok!r}")
    return {"result": "refunded" if ok else "declined"}


graph = (
    StateGraph(State)
    .add_node("refund", refund)
    .add_edge(START, "refund")
    .add_edge("refund", END)
    .compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "t1"}}

graph.invoke({"result": ""}, config)
print("after the pause :", calls)
print("final           :", graph.invoke(Command(resume=True), config))
print("after the resume:", calls)
Output3 lines
after the pause : {'charge_card': 1, 'audit_log': ['refund node started']}
final           : {'result': 'refunded'}
after the resume: {'charge_card': 2, 'audit_log': ['refund node started', 'refund node started', 'refund node resumed with True']}

The "card" was charged twice and the audit line was written twice, for one human approval. In a real system the counter is a payment, an email or a database insert. Three habits follow, and Part 4 develops them:

  • Put the interrupt() call as early as you can in the node, before anything that has an effect outside the graph.
  • Put side effects after the interrupt, or in a separate node that runs after the approval node.
  • If something must come before the interrupt, make it idempotent (running it twice equals running it once): an upsert, not an insert; a deduplication key, not a blind call.

1.7 Pause in one process, resume in another#

Every sample so far runs in one process with InMemorySaver. The promise of 1.1, a pause that survives a restart, needs a database-backed checkpointer. Here it is with SQLite (the langgraph-checkpoint-sqlite package from the setup; 08F.11 owns the choice of saver). Process A is the graph of 1.3 on a file-backed saver; it starts the run and exits.

python
# h22_a_pause.py: process A: start the run on a SQLite checkpointer file, print what B needs, then exit
import sys

from typing_extensions import TypedDict

from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt


class State(TypedDict):
    draft: str
    verdict: str


def write_draft(state: State):
    return {"draft": "Dear customer, your refund of 480 EUR is on its way."}


def human_review(state: State):
    return {"verdict": interrupt({"question": "Send this reply?", "draft": state["draft"]})}


def build(saver):
    return (StateGraph(State).add_node("write_draft", write_draft).add_node("human_review", human_review)
            .add_edge(START, "write_draft").add_edge("write_draft", "human_review")
            .add_edge("human_review", END).compile(checkpointer=saver))


if __name__ == "__main__":
    with SqliteSaver.from_conn_string(sys.argv[1]) as saver:
        graph = build(saver)
        config = {"configurable": {"thread_id": "ticket-1001"}}
        result = graph.invoke({"draft": "", "verdict": ""}, config)
        print("A: returned with interrupt id", result["__interrupt__"][0].id)
        print("A: next node:", graph.get_state(config).next, "| exiting now")

Process B is a separate Python process, started later. It builds the same graph, reads the pending question from the saved snapshot (what an approvals page does) and resumes. It takes a flag so that the same script can also run against a fresh InMemorySaver.

python
# h22_b_resume.py: process B: a NEW Python process finds the pause by thread id and resumes it
import sys

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command

from h22_a_pause import build

kind, path = sys.argv[1], sys.argv[2]
config = {"configurable": {"thread_id": "ticket-1001"}}


def run(saver):
    graph = build(saver)
    snapshot = graph.get_state(config)
    print("B: next node:", snapshot.next, "| pending:", [i.value for i in snapshot.interrupts])
    result = graph.invoke(Command(resume="approved"), config)
    print("B: resume returned:", result)


if kind == "sqlite":
    with SqliteSaver.from_conn_string(path) as saver:
        run(saver)
else:
    run(InMemorySaver())      # a fresh in-memory saver: the pause lived in process A's memory and is gone

Run uv run python h22_a_pause.py ticket.db, then, as a separate command, uv run python h22_b_resume.py sqlite ticket.db. Output of A, then of B:

text
A: returned with interrupt id dc4e43419fec729db1337f38363fe604
A: next node: ('human_review',) | exiting now
text
B: next node: ('human_review',) | pending: [{'question': 'Send this reply?', 'draft': 'Dear customer, your refund of 480 EUR is on its way.'}]
B: resume returned: {'draft': 'Dear customer, your refund of 480 EUR is on its way.', 'verdict': 'approved'}

The interrupt id differs on every run. B never saw A's memory: the question, the draft and the position in the graph all came from the file, which is why the payload must be plain serializable data (1.5). Now the same B against InMemorySaver after a fresh A run (uv run python h22_b_resume.py memory ticket.db):

text
B: next node: () | pending: []
B: resume returned: {'draft': 'Dear customer, your refund of 480 EUR is on its way.', '__interrupt__': [Interrupt(value={'question': 'Send this reply?', 'draft': 'Dear customer, your refund of 480 EUR is on its way.'}, id='e78a34222c8852fd368138172894788f', response_schema=None)]}

Nothing was pending, so the "resume" did not resume anything: it started a new run on an empty thread and paused again at the question, with no error and no approval recorded (the behaviour of an unknown thread in 2.3). That is exactly what a deploy does to a refund that waits on an in-memory saver.


Part 2: Reading the pause and resuming#

2.1 Four surfaces to read a pending interrupt (and a fifth variant)#

Your application must notice that a run paused. There are several surfaces, and which one you use depends on how you call the graph.

python
# h04_surfaces.py: four surfaces (and a fifth variant) to see a pending interrupt
from typing_extensions import TypedDict

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


class State(TypedDict):
    answer: str


def ask(state: State):
    return {"answer": interrupt("Which carrier?")}


def build():
    return (StateGraph(State).add_node("ask", ask).add_edge(START, "ask").add_edge("ask", END)
            .compile(checkpointer=InMemorySaver()))


def show(label, value):
    print(f"{label:28s}{value}")


def cfg(n):
    return {"configurable": {"thread_id": n}}


# 1. invoke, default format: a dict with an extra "__interrupt__" key (absent when nothing is pending)
g = build()
r = g.invoke({"answer": ""}, cfg("1"))
show("1. invoke (v1) keys", list(r))
show("   value", r["__interrupt__"][0].value)
show("   resumed keys", list(g.invoke(Command(resume="DHL"), cfg("1"))))

# 2. invoke with version="v2": a typed result with .value and .interrupts
g = build()
r = g.invoke({"answer": ""}, cfg("2"), version="v2")
show("2. invoke (v2) type", type(r).__name__)
show("   r.value", r.value)
show("   r.interrupts[0].value", r.interrupts[0].value)
r = g.invoke(Command(resume="DHL"), cfg("2"), version="v2")
show("   after resume", f"value={r.value} interrupts={r.interrupts}")

# 3. stream_mode="updates": a chunk with the "__interrupt__" key
g = build()
chunks = list(g.stream({"answer": ""}, cfg("3"), stream_mode="updates"))
show("3. updates chunks", [list(c) for c in chunks])
show("   chunk[0]['__interrupt__']", chunks[0]["__interrupt__"][0].value)

# 4. the saved state: the pending task carries the interrupt
g = build()
g.invoke({"answer": ""}, cfg("4"))
snap = g.get_state(cfg("4"))
show("4. snapshot.next", snap.next)
show("   snapshot.tasks[0].name", snap.tasks[0].name)
show("   snapshot.tasks[0].interrupts", [i.value for i in snap.tasks[0].interrupts])
show("   snapshot.interrupts", [i.value for i in snap.interrupts])

# 5. stream_values with version v2
g = build()
parts = list(g.stream({"answer": ""}, cfg("5"), stream_mode="values", version="v2"))
show("5. values/v2 parts", [(p["type"], list(p.keys())) for p in parts])
show("   last part interrupts", [i.value for i in parts[-1]["interrupts"]])
Output15 lines
1. invoke (v1) keys         ['answer', '__interrupt__']
   value                    Which carrier?
   resumed keys             ['answer']
2. invoke (v2) type         GraphOutput
   r.value                  {'answer': ''}
   r.interrupts[0].value    Which carrier?
   after resume             value={'answer': 'DHL'} interrupts=()
3. updates chunks           [['__interrupt__']]
   chunk[0]['__interrupt__']Which carrier?
4. snapshot.next            ('ask',)
   snapshot.tasks[0].name   ask
   snapshot.tasks[0].interrupts['Which carrier?']
   snapshot.interrupts      ['Which carrier?']
5. values/v2 parts          [('values', ['type', 'ns', 'data', 'interrupts']), ('values', ['type', 'ns', 'data', 'interrupts'])]
   last part interrupts     ['Which carrier?']
Surface What you get Use when
invoke (default format) A dict with an extra __interrupt__ key holding a list of Interrupt objects; the key is absent when nothing is pending The simplest case; check "__interrupt__" in result
invoke(..., version="v2") A GraphOutput with .value (the state) and .interrupts (a tuple, empty when nothing is pending) You want a typed result with no magic key in the state dict. Pass version explicitly: the default is still "v1" as of November 2026, so check the docs for the current default (08F.10, 10.3)
stream(..., stream_mode="updates") A chunk {"__interrupt__": (...)} at the moment of the pause; the value is a tuple of Interrupt objects here, not the list that invoke returns You are streaming progress to a UI and want the pause as just another event
graph.get_state(config) snapshot.next (nodes waiting), snapshot.tasks[i].interrupts and snapshot.interrupts You are in a different process from the one that started the run, such as an approvals page that lists everything waiting

Note that stream_mode="values" with version="v2" also puts the pending interrupts on the interrupts field of the values part, as the last lines of the output show.

The fourth row matters more than it looks. The process that shows the approval page is usually not the process that started the run. It reads the saved snapshot by thread id, which is why the pending question must be a plain, serializable value: it is stored and re-read, not handed over in memory.

2.2 The documented streaming loop (event streaming v3, beta)#

The docs call stream_events(..., version="v3") the recommended way to drive a graph that may interrupt, because the returned stream object exposes interrupted, interrupts and output directly. The package labels the API experimental: it prints a LangChainBetaWarning in this run and its source docstring says it may change. Teach and use invoke and stream as the stable base, and treat v3 as the documented direction (check the docs before relying on its exact attributes; 08F.14 owns streaming in depth). The loop is short:

python
# h05_v3_loop.py: the documented resume loop with stream_events(version="v3") (beta API)
from typing_extensions import TypedDict

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


class State(TypedDict):
    carrier: str
    insured: bool


def pick_carrier(state: State):
    return {"carrier": interrupt("Which carrier?")}


def pick_insurance(state: State):
    return {"insured": interrupt("Insure the parcel? (true/false)")}


graph = (StateGraph(State)
         .add_node(pick_carrier).add_node(pick_insurance)
         .add_edge(START, "pick_carrier").add_edge("pick_carrier", "pick_insurance").add_edge("pick_insurance", END)
         .compile(checkpointer=InMemorySaver()))

config = {"configurable": {"thread_id": "ship-7"}}
scripted_answers = iter(["DHL", True])        # stands in for a person typing

stream_input = {"carrier": "", "insured": False}
turn = 0
while True:
    turn += 1
    stream = graph.stream_events(stream_input, config=config, version="v3")
    if not stream.interrupted:                # reading this drives the run to the end or to the pause
        print(f"turn {turn}: finished with", stream.output)
        break
    question = stream.interrupts[0].value
    answer = next(scripted_answers)
    print(f"turn {turn}: paused with {question!r}; answering {answer!r}")
    stream_input = Command(resume=answer)
Output3 lines
turn 1: paused with 'Which carrier?'; answering 'DHL'
turn 2: paused with 'Insure the parcel? (true/false)'; answering True
turn 3: finished with {'carrier': 'DHL', 'insured': True}

The same program printed two LangChainBetaWarning lines on standard error (not shown): The v3 streaming protocol on Pregel is experimental. Reading stream.interrupted drives the run to its end or to the next pause, so the loop reads it before it looks at anything else. One stream object handles one leg of the run; a resume starts a new one with Command(resume=...) as the input.

2.3 Resuming: Command(resume=...)#

text
graph.invoke(Command(resume=value), config)                      # one pending interrupt
graph.invoke(Command(resume={interrupt_id: value, ...}), config)  # several pending interrupts (3.5)

The rules:

  • Same thread id as the paused run. A different thread id is a different run.
  • The resume value becomes the return value of the paused interrupt(). Any JSON-serializable value is legal: a string, a number, a boolean, a list, a dict.
  • The node restarts from its first line (1.6).
  • Command(resume=..., update={...}) is allowed: the update is applied to the state together with the resume. (A release fix in 1.2.16 made sure a resumed Command's update is applied once.)

Here is what that looks like for different values, and for the cases that do not work:

python
# h06_resume_forms.py: what you can pass as the resume value, and what happens on the wrong thread
from typing_extensions import TypedDict

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


class State(TypedDict):
    answer: object
    note: str


def ask(state: State):
    return {"answer": interrupt({"question": "Anything to add?"})}


def build():
    return (StateGraph(State).add_node("ask", ask).add_edge(START, "ask").add_edge("ask", END)
            .compile(checkpointer=InMemorySaver()))


def cfg(n):
    return {"configurable": {"thread_id": n}}


g = build()
start = {"answer": None, "note": ""}

# any JSON-serializable value is a legal resume value
for n, value in enumerate(["yes", 42, True, ["a", "b"], {"action": "edit", "text": "hi"}]):
    g.invoke(start, cfg(f"v{n}"))
    print(f"resume {value!r:32} -> answer={g.invoke(Command(resume=value), cfg(f'v{n}'))['answer']!r}")

# a Command may carry a state update next to the resume value
g.invoke(start, cfg("u"))
print("resume + update:", g.invoke(Command(resume="ok", update={"note": "reviewed by Ana"}), cfg("u")))

# resuming a thread id that has nothing pending
g.invoke(start, cfg("p"))
try:
    out = g.invoke(Command(resume="x"), cfg("other-thread"))
    print("resume on an unknown thread:", out)
except Exception as error:
    print("resume on an unknown thread:", type(error).__name__, "-", error)

# resuming a thread that already finished
print("resume on a finished thread:", g.invoke(Command(resume="again"), cfg("v0")))

# resume=None is the same as passing nothing: it is not a usable answer
g.invoke(start, cfg("n"))
try:
    print("resume=None:", g.invoke(Command(resume=None), cfg("n")))
except Exception as error:
    print("resume=None:", type(error).__name__, "-", error)
print("snapshot.next after the failed resume:", g.get_state(cfg("n")).next)
Output10 lines
resume 'yes'                            -> answer='yes'
resume 42                               -> answer=42
resume True                             -> answer=True
resume ['a', 'b']                       -> answer=['a', 'b']
resume {'action': 'edit', 'text': 'hi'} -> answer={'action': 'edit', 'text': 'hi'}
resume + update: {'answer': 'ok', 'note': 'reviewed by Ana'}
resume on an unknown thread: {'__interrupt__': [Interrupt(value={'question': 'Anything to add?'}, id='2f8e68645dc5fa0acd002dc1f9e661e0', response_schema=None)]}
resume on a finished thread: {'answer': 'yes', 'note': ''}
resume=None: UnboundLocalError - cannot access local variable 'resume_is_map' where it is not associated with a value
snapshot.next after the failed resume: ('ask',)

Three results deserve a close look:

  1. Command(resume=None) fails in langgraph 1.2.22. It raises UnboundLocalError: cannot access local variable 'resume_is_map', and the thread stays paused. None is the same as "no resume value", so it cannot be used as an answer. If you mean "just continue", resume with True or a small dict such as {"ok": True}. This is an observed bug in the version above, not documented behaviour, so re-test it after upgrading.
  2. A resume on a thread that has nothing pending does not raise. On an unknown thread id the call started a run from scratch (with an empty state) and paused again at the first question; on a finished thread it returned the old state and did nothing. Neither tells you the id was wrong, so validate the thread id in your application before you resume.
  3. A dict is a value, not a map, unless its keys are interrupt ids. A dict whose keys are not 32-hex-digit interrupt ids is delivered whole as the answer (the {"action": "edit", ...} case). Only a dict whose keys are all interrupt ids is treated as an id map (3.5).

2.4 Typed answers with response_schema#

A free-form resume value is a trap when the answer comes from a form: the UI sends "maybe" where you need a boolean, the node crashes after the resume, and the retry crashes again. response_schema (needs langgraph>=1.2.12) moves the validation to the boundary: the interrupt carries a schema, the resume value is validated against it, and interrupt() returns a validated object.

python
# h07_response_schema.py: typed resume values with response_schema (langgraph >= 1.2.12)
from dataclasses import dataclass
from typing import Literal

from pydantic import BaseModel, ValidationError, Field
from typing_extensions import TypedDict

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


class Decision(BaseModel):
    approved: bool
    amount: float = Field(gt=0, description="Amount to refund in EUR")
    note: str | None = None


class State(TypedDict):
    decision: object


def review(state: State):
    decision = interrupt({"question": "Approve the refund?", "proposed_amount": 480.0}, response_schema=Decision)
    return {"decision": decision}


graph = (StateGraph(State).add_node("review", review).add_edge(START, "review").add_edge("review", END)
         .compile(checkpointer=InMemorySaver()))
config = {"configurable": {"thread_id": "r1"}}

pending = graph.invoke({"decision": None}, config)["__interrupt__"][0]
print("schema on the Interrupt :", pending.response_schema)

for attempt in [{"approved": "maybe", "amount": 480}, {"approved": True, "amount": -5}]:
    try:
        graph.invoke(Command(resume=attempt), config)
    except ValidationError as error:
        print("rejected                :", attempt, "->", error.errors()[0]["type"], "| is_invalid_resume:", is_invalid_resume(error))
    print("still waiting?          :", graph.get_state(config).next)

result = graph.invoke(Command(resume={"approved": True, "amount": "480"}), config)
print("accepted                :", repr(result["decision"]))
print("type                    :", type(result["decision"]).__name__)


# a TypedDict or dataclass works too; a plain JSON Schema dict is advertised but NOT enforced
@dataclass
class Choice:
    option: Literal["refund", "credit"]


def review2(state: State):
    return {"decision": interrupt("Pick one", response_schema=Choice)}


def review3(state: State):
    return {"decision": interrupt("Pick one", response_schema={"type": "object", "required": ["option"]})}


for name, node in [("dataclass", review2), ("raw JSON Schema dict", review3)]:
    g = (StateGraph(State).add_node("n", node).add_edge(START, "n").add_edge("n", END)
         .compile(checkpointer=InMemorySaver()))
    c = {"configurable": {"thread_id": name}}
    g.invoke({"decision": None}, c)
    try:
        out = g.invoke(Command(resume={"option": "voucher"}), c)
        print(f"{name:22}: accepted {out['decision']!r}")
    except ValidationError as error:
        print(f"{name:22}: ValidationError on", error.errors()[0]["loc"])
Output9 lines
schema on the Interrupt : {'properties': {'approved': {'title': 'Approved', 'type': 'boolean'}, 'amount': {'description': 'Amount to refund in EUR', 'exclusiveMinimum': 0, 'title': 'Amount', 'type': 'number'}, 'note': {'anyOf': [{'type': 'string'}, {'type': 'null'}], 'default': None, 'title': 'Note'}}, 'required': ['approved', 'amount'], 'title': 'Decision', 'type': 'object'}
rejected                : {'approved': 'maybe', 'amount': 480} -> bool_parsing | is_invalid_resume: True
still waiting?          : ('review',)
rejected                : {'approved': True, 'amount': -5} -> greater_than | is_invalid_resume: True
still waiting?          : ('review',)
accepted                : Decision(approved=True, amount=480.0, note=None)
type                    : Decision
dataclass             : ValidationError on ('option',)
raw JSON Schema dict  : accepted {'option': 'voucher'}

What the run shows:

  • The schema is exposed on Interrupt.response_schema as JSON Schema, so an approvals UI (or LangGraph Studio, which renders it as a typed form) can build the right inputs.
  • An invalid answer raises pydantic.ValidationError out of the resume call, and nothing is saved: get_state(config).next still says the node is waiting, so the same interrupt can be answered again on the same thread. langgraph.errors.is_invalid_resume(error) tells such a failure from other errors, which is how the prebuilt ToolNode lets a bad reviewer answer be retried instead of reported as a bad tool call.
  • A valid answer is coerced: the string "480" became the float 480.0, and interrupt() returned a Decision instance, not the dict you sent. A TypedDict schema returns a dict and a dataclass returns a dataclass instance.
  • A plain JSON-Schema dict is advertised to the UI but not enforced: the last line accepted {"option": "voucher"}. Use a model class if you want enforcement.

Part 3: Patterns#

Everything in this part uses the same ingredients: interrupt() somewhere, a Command(resume=...) later, and a routing or update decision made from the answer. The patterns differ in where the answer goes. The decisions a reviewer can make (approve, edit, deny, defer) are defined in 08A.12 Part 3; the sections below show how each is wired in LangGraph.

3.1 Approve or reject#

The classic: the human says yes or no, and the graph takes one of two paths. The node that asks is also the node that routes, using Command(goto=...) from 08F.10, Part 6.

python
# h08_approve_reject.py: approve or reject with Command(goto=...), plus review-and-edit
from typing import Literal, Optional

from typing_extensions import TypedDict

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


class RefundState(TypedDict):
    amount: float
    reply: str
    status: Optional[Literal["pending", "refunded", "declined"]]


def draft_reply(state: RefundState):
    return {"reply": f"We have refunded {state['amount']:.2f} EUR to your card."}


def approval(state: RefundState) -> Command[Literal["issue_refund", "decline"]]:
    # The routing decision belongs to the human; the node only translates it into a goto.
    decision = interrupt({"question": "Approve this refund?", "amount": state["amount"]})
    return Command(goto="issue_refund" if decision else "decline")


def issue_refund(state: RefundState):
    return {"status": "refunded"}


def decline(state: RefundState):
    return {"status": "declined", "reply": "We are sorry, we could not approve this refund."}


builder = StateGraph(RefundState)
builder.add_node("draft_reply", draft_reply)
builder.add_node("approval", approval)          # no edge out of it: its Command(goto=...) is the edge
builder.add_node("issue_refund", issue_refund)
builder.add_node("decline", decline)
builder.add_edge(START, "draft_reply")
builder.add_edge("draft_reply", "approval")
builder.add_edge("issue_refund", END)
builder.add_edge("decline", END)
graph = builder.compile(checkpointer=InMemorySaver())

for thread, decision in [("refund-1", True), ("refund-2", False)]:
    config = {"configurable": {"thread_id": thread}}
    graph.invoke({"amount": 480.0, "reply": "", "status": "pending"}, config)
    print(f"{thread}: waiting at {graph.get_state(config).next}")
    final = graph.invoke(Command(resume=decision), config)
    print(f"{thread}: resumed with {decision!s:5} -> status={final['status']}, reply={final['reply']!r}")


# --- review and edit: the human returns a changed version, and the node writes it into state ---
class DraftState(TypedDict):
    generated_text: str


def review_and_edit(state: DraftState):
    edited = interrupt({"instruction": "Review and edit this content", "content": state["generated_text"]})
    return {"generated_text": edited}


editor = (StateGraph(DraftState).add_node("review", review_and_edit)
          .add_edge(START, "review").add_edge("review", END).compile(checkpointer=InMemorySaver()))
config = {"configurable": {"thread_id": "draft-1"}}
paused = editor.invoke({"generated_text": "Your parcl will arrive tomorow."}, config)
print("\nreviewer sees :", paused["__interrupt__"][0].value["content"])
print("after the edit:", editor.invoke(Command(resume="Your parcel will arrive tomorrow."), config)["generated_text"])
Output7 lines
refund-1: waiting at ('approval',)
refund-1: resumed with True  -> status=refunded, reply='We have refunded 480.00 EUR to your card.'
refund-2: waiting at ('approval',)
refund-2: resumed with False -> status=declined, reply='We are sorry, we could not approve this refund.'

reviewer sees : Your parcl will arrive tomorow.
after the edit: Your parcel will arrive tomorrow.

if decision treats any non-empty string as approval, so a UI that sends "reject", "no" or "false" would approve the refund. Resume with a real boolean, or better, use a response_schema with approved: bool (2.4) and test decision.approved.

Note that approval has no static edge leaving it: its Command(goto=...) is the edge (08F.10, 5.6 explains why you do not mix both). The Command[Literal["issue_refund", "decline"]] return annotation is what lets the drawing and get_graph() show both destinations.

3.2 Review and edit#

The human does not only decide; they change the content. The node returns the edited text as a state update, so later nodes see the reviewer's version. The second half of the same sample runs it: the reviewer sees the draft with its typos, and the resume value is the corrected text. Use this for drafts, summaries, extracted fields and anything a model produces that a person should be able to fix instead of reject. Combine it with a typed response_schema (2.4) when the edit has a shape, for example a corrected invoice with required fields.

3.3 Validating human input#

People mistype. The recommended way to validate is one interrupt() per node run, and a conditional edge that loops back until the input is acceptable:

python
# h09_validate_loop.py: validating human input: ONE interrupt per node run, a conditional edge loops back
from typing_extensions import TypedDict

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

runs = {"collect_age": 0}


class FormState(TypedDict):
    age: int | None
    pending_question: str | None


def collect_age(state: FormState):
    runs["collect_age"] += 1
    question = state.get("pending_question") or "What is your age?"
    answer = interrupt(question)                       # exactly once per run of the node
    if isinstance(answer, int) and answer > 0:
        return {"age": answer, "pending_question": None}
    return {"pending_question": f"{answer!r} is not a valid age. Please enter a positive number."}


def route(state: FormState):
    return END if state.get("age") is not None else "collect_age"


graph = (StateGraph(FormState).add_node(collect_age).add_edge(START, "collect_age")
         .add_conditional_edges("collect_age", route).compile(checkpointer=InMemorySaver()))
config = {"configurable": {"thread_id": "form-1"}}

result = graph.invoke({"age": None, "pending_question": None}, config)
print("asks:", result["__interrupt__"][0].value)
for attempt in ["abc", -3, 34]:
    result = graph.invoke(Command(resume=attempt), config)
    pending = result.get("__interrupt__")
    print(f"answer {attempt!r:6} ->", pending[0].value if pending else f"done, age={result['age']}")
print("node body ran", runs["collect_age"], "times to collect 3 answers (each resume re-enters the node; each loop iteration is a new run)")
Output5 lines
asks: What is your age?
answer 'abc'  -> 'abc' is not a valid age. Please enter a positive number.
answer -3     -> -3 is not a valid age. Please enter a positive number.
answer 34     -> done, age=34
node body ran 6 times to collect 3 answers (each resume re-enters the node; each loop iteration is a new run)

Notice the design: the node asks, checks, and if the answer is bad it writes a new question into state (pending_question) and returns; the conditional edge sends the run back to the same node, which asks again with the new wording. Each pass is a fresh node run with a fresh, single interrupt. The counter shows the cost of the restart rule: six body executions for three answers (every resume re-enters the node before it can consume the answer). That is fine when the body is cheap and pure, and a reason to keep nodes that interrupt small.

If validation can be expressed as a schema, prefer response_schema (2.4): the runtime rejects the bad answer before your node sees it and the interrupt stays answerable, with no loop at all. The loop is for validation that needs state or a lookup ("does this order id exist?").

3.4 Several questions in one node, and the while True trap#

A node can call interrupt() more than once. LangGraph matches resume values to calls by position within the node: the first answer goes to the first call, the second to the second, and so on. On each resume the node restarts, and the earlier calls instantly return their stored answers instead of pausing again.

python
# h10_multi_interrupt.py: several interrupts in ONE node (index matching), and the while-True trap
from typing_extensions import TypedDict

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

replays = []


class State(TypedDict):
    result: str


def onboarding(state: State):
    replays.append("onboarding started")
    name = interrupt("What is your name?")            # interrupt #0 of this node run
    team = interrupt(f"Hi {name}, which team?")        # interrupt #1
    plan = interrupt(f"{name} from {team}: which plan?")  # interrupt #2
    return {"result": f"{name} / {team} / {plan}"}


def build(node):
    return (StateGraph(State).add_node("n", node).add_edge(START, "n").add_edge("n", END)
            .compile(checkpointer=InMemorySaver()))


g = build(onboarding)
config = {"configurable": {"thread_id": "o1"}}
out = g.invoke({"result": ""}, config)
for answer in ["Ana", "Support", "Pro"]:
    print("asks:", out["__interrupt__"][0].value, "->", answer)
    out = g.invoke(Command(resume=answer), config)
print("result:", out["result"])
print("node body started", len(replays), "times for 3 questions\n")

# the trap: a while-True loop of interrupts inside one node replays every earlier iteration on each resume
iterations = []


def loop_collect(state: State):
    items = []
    while True:
        iterations.append(len(items))                  # one entry per pass through the loop body
        item = interrupt(f"Item {len(items) + 1}? (say 'done' to stop)")
        if item == "done":
            return {"result": ", ".join(items)}
        items.append(item)


g = build(loop_collect)
config = {"configurable": {"thread_id": "o2"}}
out = g.invoke({"result": ""}, config)
for answer in ["pen", "ink", "paper", "done"]:
    out = g.invoke(Command(resume=answer), config)
print("loop result:", out["result"])
print("loop body passes:", len(iterations), "for 4 answers ->", iterations)
Output8 lines
asks: What is your name? -> Ana
asks: Hi Ana, which team? -> Support
asks: Ana from Support: which plan? -> Pro
result: Ana / Support / Pro
node body started 4 times for 3 questions

loop result: pen, ink, paper
loop body passes: 14 for 4 answers -> [0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3]

The first half is the supported pattern: three questions, three answers, and the questions can even use earlier answers (f"Hi {name}, which team?"). The body started four times, once per leg. The second half is the trap the docs warn about: a while True loop that calls interrupt() inside one node replays every earlier iteration on every resume. For four answers the loop body ran fourteen times. With an inexpensive body it is merely wasteful; with a model call or a side effect inside the loop it is a bug. Use the conditional-edge loop of 3.3 for open-ended collection and keep the number of interrupt() calls in a node fixed.

3.5 Parallel interrupts and resume maps#

When two branches of a super-step both call interrupt(), both pause in the same step, and __interrupt__ lists both. A single resume value is now ambiguous, so LangGraph refuses it and asks for interrupt ids.

python
# h11_parallel.py: two branches interrupt in the same super-step; answer them all with a map of interrupt ids
import operator
from typing import Annotated

from typing_extensions import TypedDict

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


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


def legal(state: State):
    return {"vals": [f"legal: {interrupt('Is the contract wording OK?')}"]}


def finance(state: State):
    return {"vals": [f"finance: {interrupt('Is the discount within budget?')}"]}


def build():
    return (StateGraph(State).add_node(legal).add_node(finance)
            .add_edge(START, "legal").add_edge(START, "finance")
            .add_edge("legal", END).add_edge("finance", END)
            .compile(checkpointer=InMemorySaver()))


g = build()
config = {"configurable": {"thread_id": "p1"}}
out = g.invoke({"vals": []}, config)
pending = out["__interrupt__"]
print("pending interrupts:", len(pending), sorted(i.value for i in pending))
print("ids look like     :", [len(i.id) for i in pending], "hex characters each")

# 1. ONE plain value for TWO pending interrupts is refused
try:
    g.invoke(Command(resume="yes"), config)
except RuntimeError as error:
    print("\nsingle value ->", type(error).__name__ + ":", str(error)[:104], "...")

# 2. a map {interrupt id: answer} answers them together
answers = {i.id: "approved" for i in pending}
out = g.invoke(Command(resume=answers), config)
print("\nmap resume   ->", sorted(out["vals"]))

# 3. you can also answer one at a time: the run stays paused on the other one
g = build()
config = {"configurable": {"thread_id": "p2"}}
pending = g.invoke({"vals": []}, config)["__interrupt__"]
by_text = {i.value: i.id for i in pending}
out = g.invoke(Command(resume={by_text["Is the contract wording OK?"]: "approved"}), config)
print("\nafter answering one:", [i.value for i in out["__interrupt__"]], "| vals so far:", out["vals"])
out = g.invoke(Command(resume={by_text["Is the discount within budget?"]: "approved"}), config)
print("after answering both:", sorted(out["vals"]))

# 4. a dict whose keys are not interrupt ids is an ordinary VALUE, not a map
class Single(TypedDict):
    answer: object


def one(state: Single):
    return {"answer": interrupt("form?")}


g1 = StateGraph(Single).add_node("one", one).add_edge(START, "one").add_edge("one", END).compile(checkpointer=InMemorySaver())
c = {"configurable": {"thread_id": "p3"}}
g1.invoke({"answer": None}, c)
print("\ndict with ordinary keys is a value:", g1.invoke(Command(resume={"name": "Ana", "age": 34}), c)["answer"])
Output11 lines
pending interrupts: 2 ['Is the contract wording OK?', 'Is the discount within budget?']
ids look like     : [32, 32] hex characters each

single value -> RuntimeError: When there are multiple pending interrupts, you must specify the interrupt id when resuming. Docs: https ...

map resume   -> ['finance: approved', 'legal: approved']

after answering one: ['Is the discount within budget?'] | vals so far: ['legal: approved']
after answering both: ['finance: approved', 'legal: approved']

dict with ordinary keys is a value: {'name': 'Ana', 'age': 34}

What to take from the run:

  • A plain value with two pending interrupts raises RuntimeError: When there are multiple pending interrupts, you must specify the interrupt id when resuming.
  • A resume map {interrupt.id: answer, ...} answers any subset. Answering one leaves the other pending; the answered branch keeps its result and does not re-ask. This is how two reviewers (legal and finance in the sample) can answer on different days.
  • The map is detected by its keys: a dict is treated as an id map only if all its keys are interrupt ids. A form-shaped dict such as {"name": ..., "age": ...} is just a value.
  • A map whose ids match no pending interrupt is silently ignored: the call returns normally, the run stays paused and nothing changes. A typo or a stale id therefore looks like "the graph asked the same question again" (h21_stale_id.py, 2.3).
  • The order of two parallel branches' entries in a list reducer is not guaranteed; the sample sorts before printing, and so should your tests.

3.6 Interrupts inside tools#

Often the thing that needs approval is a tool call. You can put the interrupt() inside the tool. The approval logic then lives with the tool and every agent that uses the tool inherits it, and the reviewer's answer can override the tool's arguments.

python
# h12_tool_interrupt.py: an interrupt INSIDE a tool, with create_agent and a scripted model (no key needed)
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langchain_core.language_models import GenericFakeChatModel
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

sent: list[tuple[str, str]] = []


class ScriptedModel(GenericFakeChatModel):
    """GenericFakeChatModel replays AIMessages; create_agent also needs bind_tools to exist."""

    def bind_tools(self, tools, **kwargs):
        return self


@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email to a customer."""
    # The approval logic lives WITH the tool, so every agent that uses the tool gets it.
    response = interrupt({"action": "send_email", "to": to, "subject": subject, "body": body,
                          "message": "Approve sending this email?"})
    if response.get("action") != "approve":
        return "Email cancelled by the reviewer."
    final_to = response.get("to", to)                 # the reviewer may override the arguments
    final_subject = response.get("subject", subject)
    sent.append((final_to, final_subject))            # the side effect comes AFTER the interrupt
    return f"Email sent to {final_to} with subject {final_subject!r}."


def build_agent():
    call = ToolCall(name="send_email", id="c1",
                    args={"to": "ana@example.com", "subject": "Your refund", "body": "It is on its way."})
    model = ScriptedModel(messages=iter([AIMessage(content="", tool_calls=[call]), AIMessage(content="Done.")]))
    return create_agent(model, tools=[send_email], checkpointer=InMemorySaver())


def run(label, response):
    sent.clear()
    agent = build_agent()
    config = {"configurable": {"thread_id": label}}
    paused = agent.invoke({"messages": [HumanMessage("Tell Ana about her refund")]}, config)
    if label == "approve":
        print("the reviewer is shown:", paused["__interrupt__"][0].value)
        print("the graph is waiting at:", agent.get_state(config).next)
    done = agent.invoke(Command(resume=response), config)
    tool_message = [m for m in done["messages"] if m.type == "tool"][-1]
    print(f"{label:8s} -> sent={sent} | tool result: {tool_message.content!r}")


run("approve", {"action": "approve"})
run("edit", {"action": "approve", "to": "manager@example.com"})
run("cancel", {"action": "reject"})
Output5 lines
the reviewer is shown: {'action': 'send_email', 'to': 'ana@example.com', 'subject': 'Your refund', 'body': 'It is on its way.', 'message': 'Approve sending this email?'}
the graph is waiting at: ('tools',)
approve  -> sent=[('ana@example.com', 'Your refund')] | tool result: "Email sent to ana@example.com with subject 'Your refund'."
edit     -> sent=[('manager@example.com', 'Your refund')] | tool result: "Email sent to manager@example.com with subject 'Your refund'."
cancel   -> sent=[] | tool result: 'Email cancelled by the reviewer.'

The run shows the structure to copy: the pause comes first, the side effect (sent.append) comes after it, and the resume payload can carry corrections ("to": "manager@example.com") that the tool applies. The graph was waiting at ('tools',), the node that runs the tool, because the tool is what paused.

A model can also ask for several gated tool calls in one turn. The tools run in parallel, so each pauses with its own interrupt, and you answer them by id as in 3.5:

python
# h13_parallel_tools: two gated tool calls in ONE model turn: two pending interrupts, answered by id
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langchain_core.language_models import GenericFakeChatModel
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

done_actions: list[str] = []


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


@tool
def cancel_order(order_id: str) -> str:
    """Cancel an order."""
    if interrupt({"action": "cancel_order", "order_id": order_id}) is not True:
        return f"Cancelling {order_id} was refused."
    done_actions.append(f"cancelled {order_id}")
    return f"Order {order_id} cancelled."


model = ScriptedModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="cancel_order", args={"order_id": "A-1"}, id="c1"),
                                      ToolCall(name="cancel_order", args={"order_id": "B-2"}, id="c2")]),
    AIMessage(content="Handled both."),
]))
agent = create_agent(model, tools=[cancel_order], checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "multi"}}

paused = agent.invoke({"messages": [HumanMessage("Cancel A-1 and B-2")]}, config)
pending = paused["__interrupt__"]
print("pending:", [i.value["order_id"] for i in pending])

# approve A-1, refuse B-2: answer each interrupt by its id
answers = {i.id: (i.value["order_id"] == "A-1") for i in pending}
final = agent.invoke(Command(resume=answers), config)
print("done actions:", done_actions)
for m in final["messages"]:
    if m.type == "tool":
        print("tool message:", m.content)
Output4 lines
pending: ['A-1', 'B-2']
done actions: ['cancelled A-1']
tool message: Order A-1 cancelled.
tool message: Cancelling B-2 was refused.

Both orders were pending at once, one was approved and one refused, and each tool received its own answer.

When to put the interrupt in the tool, and when to use the middleware. An interrupt in a tool is the lowest-level, most flexible option and you write the payload shape yourself. HumanInTheLoopMiddleware gives you a standard payload (action requests, review configs and four decision types) for create_agent without touching the tools, which is better when you do not own the tools or want a uniform approval UI across many of them.

A human as a tool. A related pattern turns the human into a tool the model chooses to call when it lacks information, for example the customer gave no order id. It is the same mechanism, aimed at a different job: here the agent decides when to ask, not a rule.

python
# h20_ask_human.py: "human as a tool": the agent decides WHEN to ask, interrupt() does the asking (illustrative: needs a provider key)
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.messages import HumanMessage
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

load_dotenv()                                   # OPENAI_API_KEY or ANTHROPIC_API_KEY (GEMINI_API_KEY if you use Gemini, optional) from .env


@tool
def ask_human(question: str) -> str:
    """Ask the human operator a question when you are missing information you cannot look up yourself.
    Do not use it for things the other tools can answer."""
    return interrupt({"question": question})    # the operator's answer becomes the tool result


@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"


# "openai:gpt-6-luna" | "anthropic:claude-haiku-5-5" | "google_genai:gemini-3.8-flash" (optional)
agent = create_agent("openai:gpt-6-luna", tools=[ask_human, order_status], checkpointer=InMemorySaver(),
                     system_prompt="You are a support agent. If the customer gives no order id, ask the operator.")
config = {"configurable": {"thread_id": "support-77"}}

paused = agent.invoke({"messages": [HumanMessage("Where is my parcel?")]}, config)
if "__interrupt__" in paused:
    print("agent asks:", paused["__interrupt__"][0].value["question"])
    final = agent.invoke(Command(resume="The order id is A-1042"), config)
    print(final["messages"][-1].text)

This sample is illustrative: it calls a real provider, so your wording and the exact sequence of tool calls will differ, and it was not run for this lesson. The mechanism (a tool whose body is return interrupt(...)) is the same one the keyless samples above ran. Give the tool a clear description that says when not to use it, or the model will ask the operator about things it could look up.

3.7 A graph called as a function#

If a node calls another compiled graph inside its own body (sub.invoke(state)), an interrupt in the inner graph pauses the whole run, and on resume both the outer node and the inner node restart from their first lines. When the subgraph is added as a node instead, only the subgraph's node re-runs.

python
# h16_subgraph_fn.py: a graph called as a FUNCTION from a node: both restart on resume; as a node it does not
from typing_extensions import TypedDict

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

log: list[str] = []


class State(TypedDict):
    answer: str


def ask(state: State):
    log.append("  subgraph node 'ask' started")
    return {"answer": interrupt("Approve?")}


sub = StateGraph(State).add_node("ask", ask).add_edge(START, "ask").add_edge("ask", END).compile()


def parent_calls_sub(state: State):
    log.append("  parent node started (calls the subgraph inside its own body)")
    return sub.invoke(state)


def build(parent_node, subgraph_as_node=False):
    b = StateGraph(State)
    b.add_node("parent", sub if subgraph_as_node else parent_node)
    b.add_edge(START, "parent").add_edge("parent", END)
    return b.compile(checkpointer=InMemorySaver())


for label, g in [("subgraph called as a function inside a node", build(parent_calls_sub)),
                 ("subgraph added as a node", build(None, subgraph_as_node=True))]:
    log.clear()
    config = {"configurable": {"thread_id": label}}
    g.invoke({"answer": ""}, config)
    g.invoke(Command(resume="yes"), config)
    print(label)
    print("\n".join(log))
Output8 lines
subgraph called as a function inside a node
  parent node started (calls the subgraph inside its own body)
  subgraph node 'ask' started
  parent node started (calls the subgraph inside its own body)
  subgraph node 'ask' started
subgraph added as a node
  subgraph node 'ask' started
  subgraph node 'ask' started

Anything you did in the outer node before calling the inner graph runs twice. Prefer adding the subgraph as a node, and read 08F.13 for subgraph state and how interrupts bubble up through nested graphs.

3.8 What to put in the payload#

The interrupt value is your interface to the reviewer, so design it like an API response:

  • Everything the reviewer needs to decide, nothing else. The action, the exact arguments, the amount, the customer, the policy limit. A reviewer who must open three other tabs will click approve.
  • A stable shape with a type or action field, so one approvals UI can render many kinds of requests, and so a change in wording does not break the UI.
  • Small and serializable. It is stored in every checkpoint. Send an id or a link for a large document, not the document.
  • No secrets. The payload is saved and shown; keep tokens and full card numbers out of it.
  • Facts at the time of the pause. State can change while a person decides; re-check preconditions after the resume (the order may have shipped), as 08F.8, 8.9 noted.

08A.14, 2.5, 08A.14, Part 6 and 08A.12 Part 5 cover what makes an approval trustworthy rather than a rubber stamp, how to time out an unanswered request (expire to deny) and who to escalate to; 13A.3 Part 4 covers what the reviewer's screen should show. Those decisions become nodes and conditional edges in your graph: a timer that resumes the thread with a "no answer" value, or a scheduled job that lists threads whose next has been waiting too long.


Part 4: The rules of interrupts#

Interrupts have five rules. Each is a consequence of the mechanism in Part 1 (an exception, a restart, a saved task), and each is easier to remember after seeing it fail.

4.1 Never wrap interrupt() in a bare except#

interrupt() pauses by raising an exception. A broad except Exception (or a bare except:) catches that exception, so the pause never happens and your node carries on with whatever the except block assigned.

python
# h14_swallow.py: a bare "except Exception" around interrupt() swallows the pause
from typing_extensions import TypedDict

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


class State(TypedDict):
    answer: str


def swallowing(state: State):
    try:
        answer = interrupt("approve?")
    except Exception:                       # BAD: interrupt() works by raising an exception
        answer = "no answer (error swallowed)"
    return {"answer": str(answer)}


def narrow(state: State):
    try:
        answer = interrupt("approve?")      # the interrupt is raised OUTSIDE the risky code
    except GraphInterrupt:
        raise                               # if you must catch broadly, let the pause through
    return {"answer": str(answer)}


def build(node):
    return (StateGraph(State).add_node("n", node).add_edge(START, "n").add_edge("n", END)
            .compile(checkpointer=InMemorySaver()))


for label, node in [("bare except", swallowing), ("re-raise GraphInterrupt", narrow)]:
    g = build(node)
    out = g.invoke({"answer": ""}, {"configurable": {"thread_id": label}})
    print(f"{label:24s}-> paused: {'__interrupt__' in out}, answer: {out['answer']!r}")
Output2 lines
bare except             -> paused: False, answer: 'no answer (error swallowed)'
re-raise GraphInterrupt -> paused: True, answer: ''

With the bare except, the run did not pause at all and the node proceeded with the fallback string. If you must catch broadly, re-raise GraphInterrupt first, or, better, call interrupt() first and put the error-prone code after it or outside the try. Catch specific exception types for the risky call, never Exception around the interrupt.

4.2 Do not reorder or conditionally skip interrupt calls#

Resume values are matched to interrupt() calls by position in the node, not by question text. If the sequence of interrupt calls changes between the pause and the resume, answers go to the wrong questions. That can happen through a non-deterministic loop (iterating a set, or a list whose contents change), a conditional that depends on something that changed while the person was deciding, or a deploy that reorders two questions while threads are waiting:

python
# h15_order_mismatch.py: resume values are matched to interrupt() calls by POSITION, not by question
from typing_extensions import TypedDict

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


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


def v1(state: State):
    return {"name": interrupt("What is your name?"), "team": interrupt("Which team?")}


def v2(state: State):
    # a "harmless" refactor shipped while a thread was waiting: the two questions swapped places
    team = interrupt("Which team?")
    name = interrupt("What is your name?")
    return {"name": name, "team": team}


def build(node, saver):
    return (StateGraph(State).add_node("n", node).add_edge(START, "n").add_edge("n", END)
            .compile(checkpointer=saver))


saver = InMemorySaver()
config = {"configurable": {"thread_id": "t"}}
out = build(v1, saver).invoke({"name": "", "team": ""}, config)
print("v1 asks :", out["__interrupt__"][0].value)
out = build(v1, saver).invoke(Command(resume="Ana"), config)
print("v1 asks :", out["__interrupt__"][0].value, "(Ana answered the first question)")

# deploy v2 against the saved thread, then answer the second question
out = build(v2, saver).invoke(Command(resume="Support"), config)
print("v2 result:", {k: out[k] for k in ("name", "team")})
print("-> Ana's answer 'Ana' went to the FIRST interrupt() call of v2, which asks about the team")
Output4 lines
v1 asks : What is your name?
v1 asks : Which team? (Ana answered the first question)
v2 result: {'name': 'Support', 'team': 'Ana'}
-> Ana's answer 'Ana' went to the FIRST interrupt() call of v2, which asks about the team

Ana typed her name for the first question of version 1. Version 2, deployed while the thread waited, asks about the team first, so her name became the team and "Support" became her name. Nothing raised an error. The rule: keep the number and order of interrupt() calls in a node fixed, branch between nodes rather than between interrupts, and treat reordering a node's questions like a schema migration (08F.10, 14.1): add a new node for the new flow and let old threads finish on the old one. The same family of bug exists for tasks: results are matched by task name plus position, so a same-task call with swapped arguments silently returns the old result (08F.11, 4.5). Interrupts have no name, so position is their whole identity.

Replaying or forking from an earlier checkpoint (08F.11, 3.2) re-executes every later node, including interrupts: the run stops at the question again and needs a new Command(resume=...).

4.3 Only serializable values#

The payload and the resume value are stored by the checkpointer, so both must be plain data (1.5 showed the TypeError). Convert before you interrupt: order.model_dump() instead of order, an id instead of a database connection, an ISO string instead of a datetime unless your serializer is configured for it (08F.11).

4.4 Side effects before an interrupt must be idempotent#

1.6 showed a charge made twice because it sat above the interrupt(). The ways out, in order of preference:

  1. Move the side effect after the interrupt, or into the next node. Then it runs once, after the approval. This is the right answer almost every time.
  2. If the effect must happen first, make it idempotent: an upsert (set the row to a value) instead of an insert (add a row), a deterministic key that makes the external system ignore the repeat.
  3. Even a side effect after the interrupt can repeat if the node later fails and is retried (7.3), so the external system should deduplicate as well (7.4).
python
def refund(state: State):
    approved = interrupt({"question": "Approve?", "order_id": state["order_id"]})   # first line of real work
    if approved:
        gateway.refund(key=f"refund:{state['order_id']}", amount=state["amount"])   # after the pause, with a key
    return {"status": "refunded" if approved else "declined"}

4.5 An interrupt is not an error: retries and handlers ignore it#

interrupt() is a control-flow signal, not a failure, so retry policies and error handlers never see it (Part 7). The corollary is easy to miss: after the human has answered, the answer is remembered for that node run. If the node then fails and the retry policy re-runs it, the retried attempt does not ask the person again; interrupt() returns the stored answer immediately.

python
# r07_interrupt_and_retry.py: interrupt() is not an error: retry policies and handlers ignore it
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import NodeError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, RetryPolicy, interrupt
from typing_extensions import TypedDict

log: list[str] = []


class State(TypedDict):
    out: str


def risky(state: State):
    log.append("risky started")
    answer = interrupt("Proceed?")
    if answer == "boom":
        raise ConnectionError("failure AFTER the human answered")
    return {"out": f"answered {answer}"}


def handler(state: State, error: NodeError):
    log.append(f"handler ran for {type(error.error).__name__}")
    return {"out": "handled"}


g = (StateGraph(State)
     .add_node("risky", risky, retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False), error_handler=handler)
     .add_edge(START, "risky").add_edge("risky", END).compile(checkpointer=InMemorySaver()))

config = {"configurable": {"thread_id": "x"}}
paused = g.invoke({"out": ""}, config)
print("1. paused:", "__interrupt__" in paused, "| log:", log)

log.clear()
print("2. resume with 'boom':", g.invoke(Command(resume="boom"), config), "| log:", log)
Output2 lines
1. paused: True | log: ['risky started']
2. resume with 'boom': {'out': 'handled'} | log: ['risky started', 'risky started', 'risky started', 'handler ran for ConnectionError']

The pause was not retried or handled. After the resume, the node failed with a ConnectionError, was retried twice (three starts in total), every start received the same stored answer, and only then did the error handler run. For a human decision this is the behaviour you want, and it is a second reason the work after an interrupt() must be safe to repeat.

4.6 The checklist#

Rule What breaks if you ignore it Fix
Need a checkpointer and a thread id Resume raises RuntimeError or ValueError; a pause that can never continue Compile with a durable checkpointer; always pass thread_id
Node restarts from line 1 Duplicate emails, charges, log lines interrupt() first; side effects after, or idempotent
No bare except around interrupt() The node never pauses Catch specific exceptions; interrupt before risky code
Position-based matching Answers land on the wrong question after a code change Fixed number and order of calls; migrate by adding nodes
Serializable payloads TypeError at the pause Plain data only
Command(resume=None) UnboundLocalError in 1.2.22 Resume with True or a dict
Several pending interrupts RuntimeError for a plain value Resume by interrupt id
while True with interrupt() Quadratic replays Conditional-edge loop with one interrupt per node run

Part 5: Static breakpoints#

Deep-dive

5.1 What they are#

A static breakpoint pauses the graph before or after a named node, no matter what the node does. You do not write anything inside the node; you list node names when you compile or when you call the graph. It is the debugger's breakpoint, not a conversation with a user. Like interrupt(), it needs a checkpointer and a thread id.

python
graph = builder.compile(
    checkpointer=checkpointer,
    interrupt_before=["node_a"],               # pause before node_a runs
    interrupt_after=["node_b", "node_c"],      # pause after node_b and node_c have run
)
graph.invoke(inputs, config)                   # runs until the first breakpoint
graph.invoke(None, config)                     # input None: continue to the next breakpoint

The same two arguments can be passed to invoke and stream to change the stops for one call without recompiling.

5.2 A complete run#

python
# h17_breakpoints.py: static breakpoints: interrupt_before and interrupt_after, compile time and run time
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):
    text: str


def fetch(state: State):
    return {"text": state["text"] + " | fetched"}


def transform(state: State):
    return {"text": state["text"] + " | transformed"}


def publish(state: State):
    return {"text": state["text"] + " | published"}


def builder():
    b = StateGraph(State)
    for fn in (fetch, transform, publish):
        b.add_node(fn)
    b.add_edge(START, "fetch").add_edge("fetch", "transform").add_edge("transform", "publish").add_edge("publish", END)
    return b


def cfg(n):
    return {"configurable": {"thread_id": n}}


# 1. compile-time breakpoints
g = builder().compile(checkpointer=InMemorySaver(), interrupt_before=["transform"], interrupt_after=["publish"])
out = g.invoke({"text": "start"}, cfg("a"))
print("1. first call    :", out, "| next:", g.get_state(cfg("a")).next)
out = g.invoke(None, cfg("a"))        # None as input = continue from the checkpoint
print("   second call   :", out, "| next:", g.get_state(cfg("a")).next)
out = g.invoke(None, cfg("a"))
print("   third call    :", out, "| next:", g.get_state(cfg("a")).next)

# 2. run-time breakpoints: same compiled graph, a different stop per call
g = builder().compile(checkpointer=InMemorySaver())
out = g.invoke({"text": "start"}, cfg("b"), interrupt_after=["fetch"])
print("2. interrupt_after=['fetch']:", out, "| next:", g.get_state(cfg("b")).next)
print("   continue to the end     :", g.invoke(None, cfg("b")))

# 3. "*" stops before (or after) every node
g = builder().compile(checkpointer=InMemorySaver(), interrupt_before="*")
g.invoke({"text": "start"}, cfg("c"))
steps = []
while g.get_state(cfg("c")).next:
    steps.append(g.get_state(cfg("c")).next[0])
    g.invoke(None, cfg("c"))
print("3. interrupt_before='*' stopped before:", steps)

# 4. edit the state while stopped, then continue (the edit is a normal checkpoint write)
g = builder().compile(checkpointer=InMemorySaver(), interrupt_before=["publish"])
g.invoke({"text": "start"}, cfg("d"))
g.update_state(cfg("d"), {"text": "REVIEWED"})
print("4. after update_state and resume:", g.invoke(None, cfg("d")))

# 5. an unknown node name
try:
    builder().compile(checkpointer=InMemorySaver(), interrupt_before=["transfrom"])
except Exception as error:
    print("5.", type(error).__name__, "-", error)

# 6. no checkpointer
try:
    g = builder().compile(interrupt_before=["transform"])
    print("6. compiled without a checkpointer; invoke ->", g.invoke({"text": "start"}))
except Exception as error:
    print("6.", type(error).__name__, "-", str(error)[:120])

# 7. the resume value for a breakpoint is None; a Command(resume=...) is also accepted
g = builder().compile(checkpointer=InMemorySaver(), interrupt_before=["transform"])
g.invoke({"text": "start"}, cfg("e"))
print("7. Command(resume='x') on a breakpoint:", g.invoke(Command(resume="x"), cfg("e")))
Output10 lines
1. first call    : {'text': 'start | fetched'} | next: ('transform',)
   second call   : {'text': 'start | fetched | transformed | published'} | next: ()
   third call    : {'text': 'start | fetched | transformed | published'} | next: ()
2. interrupt_after=['fetch']: {'text': 'start | fetched'} | next: ('transform',)
   continue to the end     : {'text': 'start | fetched | transformed | published'}
3. interrupt_before='*' stopped before: ['fetch', 'transform', 'publish']
4. after update_state and resume: {'text': 'REVIEWED | published'}
5. ValueError - Interrupt node `transfrom` not found
6. compiled without a checkpointer; invoke -> {'text': 'start | fetched'}
7. Command(resume='x') on a breakpoint: {'text': 'start | fetched | transformed | published'}

What each numbered line shows:

  1. Compile-time breakpoints. The first call stopped before transform. invoke(None, config) continued; interrupt_after=["publish"] was on the last node, so there was nothing left to resume and the third call returned the finished state again. An interrupt_after on the final node adds no useful pause.
  2. Run-time breakpoints. The same compiled graph stopped after fetch because the call asked it to. This is how Studio and test code vary the stops without rebuilding.
  3. "*" pauses before (or after) every node: single-stepping through a run. Note it is a string, not a list.
  4. Editing state at a breakpoint. update_state changed the text while the run was stopped and the continuation used the edit (08F.11 owns update_state, history and time travel). This is what makes breakpoints useful for debugging.
  5. Unknown names are caught at compile time: ValueError: Interrupt node `transfrom` not found.
  6. No checkpointer: no error and no pause you can use. The graph compiled and invoke quietly stopped after the first node, returning a partial state with nothing to continue from. If you set a breakpoint and the run appears to end early, check for the checkpointer first.
  7. A Command(resume=...) is accepted for a breakpoint, but the conventional resume is invoke(None, config).

5.3 Traps#

  • Pass lists, not strings. One docs page passes a bare string to interrupt_after. In langgraph 1.2.22 it fails when you compile:
python
# h18_bare_string.py: pass breakpoint names as LISTS; what a bare string does
from typing_extensions import TypedDict

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


class State(TypedDict):
    text: str


def mk(name):
    return lambda s: {"text": s["text"] + f" {name}"}


b = StateGraph(State)
for n in ("node1", "node2", "node3"):
    b.add_node(n, mk(n))
b.add_edge(START, "node1").add_edge("node1", "node2").add_edge("node2", "node3").add_edge("node3", END)

for label, kwargs in [("list ['node2']", dict(interrupt_after=["node2"])), ("bare 'node2'", dict(interrupt_after="node2"))]:
    try:
        g = b.compile(checkpointer=InMemorySaver(), **kwargs)
        cfg = {"configurable": {"thread_id": label}}
        out = g.invoke({"text": ""}, cfg)
        print(f"{label:16s}-> {out} | next: {g.get_state(cfg).next}")
    except Exception as error:
        print(f"{label:16s}-> {type(error).__name__}: {error}")
Output2 lines
list ['node2']  -> {'text': ' node1 node2'} | next: ('node3',)
bare 'node2'    -> TypeError: can only concatenate list (not "str") to list

Treat the bare-string form as a docs inconsistency and always pass a list (or "*").

  • A breakpoint pause has no __interrupt__. Detect it with get_state(config).next (2.1).
  • Breakpoints are global to the node. Every thread that reaches node_a stops there, including production traffic if you compiled the breakpoint in. Keep them out of production builds.

5.4 When to use them#

The docs are explicit: static interrupts are not recommended for human-in-the-loop workflows; use interrupt() instead. The reasons follow from what you have seen. A breakpoint carries no question and no typed answer, it cannot depend on the state ("only pause if the amount is large"), it cannot show the reviewer a payload, and it pauses every run. Use breakpoints for debugging and testing: stepping through a graph in Studio, pausing after a node in a test to inspect or edit state with update_state and then continue (the pattern the testing docs use), and reproducing a bug from a saved checkpoint. For anything a person must decide in production, use interrupt() (Parts 1 to 4), an interrupt in a tool, or the middleware (Part 6).


Part 6: HumanInTheLoopMiddleware and choosing a mechanism#

Deep-dive

6.1 What the middleware is built on#

08F.8, 8.9 taught how to use HumanInTheLoopMiddleware with create_agent. Now that you know interrupt(), you can read it for what it is: a middleware that, after the model asks for a tool and before the tool runs, calls interrupt() with a standard payload and then acts on the resume value. Everything in Parts 1 to 4 applies to it unchanged: it needs a checkpointer, it pauses by returning, it resumes with Command(resume=...) on the same thread, it restarts the hook on resume, and an answer in the wrong shape fails the resume.

python
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model="openai:gpt-6-luna",
    tools=[write_file, execute_sql, read_data],
    middleware=[HumanInTheLoopMiddleware(
        interrupt_on={
            "write_file": True,                                              # pause; allow every decision
            "execute_sql": {"allowed_decisions": ["approve", "reject"]},     # no edits allowed
            "read_data": False,                                              # never pause
        },
        description_prefix="Tool execution pending approval",
    )],
    checkpointer=InMemorySaver(),
)

This sketch is illustrative (it names a provider and three tools you would define). The keyless, run version is in 08F.8, 8.9.

Piece Shape
Pause payload (Interrupt.value) {"action_requests": [{"name", "args", "description"}, ...], "review_configs": [{"action_name", "allowed_decisions"}, ...]} (the HITLRequest type)
Resume (default batched mode) Command(resume={"decisions": [d1, d2, ...]}), one decision per action request, in the same order
approve {"type": "approve"} runs the tool as requested
edit {"type": "edit", "edited_action": {"name": ..., "args": {...}}} runs the tool with the reviewer's arguments
reject {"type": "reject", "message": "..."} skips the tool and tells the model why
respond {"type": "respond", "message": "..."} (message required) returns the reviewer's text as a successful tool result; do not use it to deny an action
interrupt_mode "batched" (default: one interrupt per model turn) or "per_call" (one per gated call, answered by interrupt id; needs langchain>=1.4.6; from the middleware docs, not run here)
InterruptOnConfig.when A predicate for conditional interrupts (needs langchain>=1.3.3; from the middleware docs, not run here); in batched mode it receives tool=None, so use per_call when the decision depends on the tool

The types (HITLRequest, HITLResponse, the four decision classes, InterruptMode) live in langchain.agents.middleware.human_in_the_loop; HumanInTheLoopMiddleware and InterruptOnConfig are exported from langchain.agents.middleware. With invoke(..., version="v2") the pending request is in result.interrupts[0].value. The minimum versions are the ones the docs state; check the docs for the current ones.

Two consequences of "it is just interrupt()":

  • Batched answers are positional. The list of decisions is matched to the list of action requests by index, exactly the position-based matching of 4.2, so build the list from the request list, never from memory. per_call mode instead gives one interrupt per call and you answer with a resume map keyed by interrupt id (3.5), which is why the docs recommend it for new agents.
  • Command(resume=...) without a checkpointer raises RuntimeError here too (1.5). 08F.8, 8.9 ran it.

6.2 Run-time context does not survive a pause#

context= passed to the first call is not saved in the checkpoint. When you resume, pass it again, or the tool and the middleware see None. 08F.10, Part 9 showed it for a plain graph; here it is with an agent, a gated tool and the middleware:

python
# h19_middleware_context.py: HumanInTheLoopMiddleware, and run-time context across a pause
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import ToolRuntime, tool
from langchain_core.language_models import GenericFakeChatModel
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command


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


@dataclass
class Ctx:
    tenant: str


@tool
def issue_refund(order_id: str, amount: float, runtime: ToolRuntime[Ctx]) -> str:
    """Refund an order."""
    return f"[tenant={runtime.context.tenant if runtime.context else None}] refunded {amount} on {order_id}"


def build():
    model = ScriptedModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="issue_refund", args={"order_id": "A-1", "amount": 480.0}, id="c1")]),
        AIMessage(content="Done."),
    ]))
    return create_agent(
        model, tools=[issue_refund], context_schema=Ctx, checkpointer=InMemorySaver(),
        middleware=[HumanInTheLoopMiddleware(interrupt_on={"issue_refund": {"allowed_decisions": ["approve", "reject"]}})],
    )


approve = Command(resume={"decisions": [{"type": "approve"}]})
for label, resume_kwargs in [("context passed again on resume", {"context": Ctx(tenant="acme")}),
                             ("context NOT passed on resume   ", {})]:
    agent = build()
    config = {"configurable": {"thread_id": label}}
    agent.invoke({"messages": [HumanMessage("Refund A-1")]}, config, context=Ctx(tenant="acme"))
    done = agent.invoke(approve, config, **resume_kwargs)
    print(label, "->", [m.content for m in done["messages"] if m.type == "tool"][-1])
Output2 lines
context passed again on resume -> [tenant=acme] refunded 480.0 on A-1
context NOT passed on resume    -> [tenant=None] refunded 480.0 on A-1

The tool ran after the resume in both cases, but without the context it read None for the tenant. In a real system that is a refund booked against no tenant, or a permissions check that sees no role. Make resuming go through one function in your application that rebuilds the context from the authenticated request and passes it on every call, first call or resume alike. State survives the pause; the context object does not.

6.3 Which mechanism for which job#

You want Use Why
Approve, edit or reject tool calls of a create_agent agent, with a standard UI payload HumanInTheLoopMiddleware No change to tools; four decision types; per-tool policy
Approval logic that belongs to one tool and travels with it, or custom payloads interrupt() inside the tool (3.6) You own the payload; the answer can override arguments
A human decision in the middle of a hand-written graph (approve, edit, collect missing data) interrupt() in a node (Part 3) Full control of routing with Command(goto=...)
The model decides when to ask for information A tool whose body is interrupt() (3.6, "human as a tool") The agent chooses; the pause is the same
Pause for debugging, tests or Studio Static breakpoints (Part 5) Not for production HITL
A conditional approval ("only above 100 EUR") Middleware when in per_call mode, or a routing node before the approval node Static breakpoints cannot depend on state

6.4 Names to migrate from#

Older code and tutorials used HumanInterruptConfig, ActionRequest and HumanInterrupt from langgraph.prebuilt. The migration guide replaces them with InterruptOnConfig and HITLRequest from langchain.agents.middleware.human_in_the_loop. They still import in langgraph 1.2.22 without a warning (Part 12), so a deprecation will not announce itself; search your code for them. Hand-rolled agents that pause with interrupt_before=["tools"] should move to an interrupt inside the tool or to the middleware.


Part 7: When a node fails: retries, error handlers and recovery#

Deep-dive

7.1 Who handles which failure#

Before the features, the decision. Failures are not all alike, and each kind has a different right owner. The official fault-tolerance docs give the same split; this table is the one to keep.

Failure Example Who recovers Mechanism
Transient A dropped connection, a 503, a locked database The system retry_policy
Recoverable, after retries are spent The payment gateway stays down The developer's compensation logic error_handler (saga, compensation, fallback path)
LLM-recoverable A tool rejected the arguments the model chose The model Store the error in state and route back to the model
User-fixable A missing or invalid piece of information A person interrupt() (Parts 1 to 4)
Unexpected A bug: KeyError, a bad schema The developer Let it raise and fail the run; fix the code

The last row is as important as the others. The default retry rule (7.2) deliberately does not retry programming errors, because running a bug three times does not fix it.

How a single attempt moves through these mechanisms:

flowchart TD
    A["Node attempt starts"] --> B{"Finished in time?"}
    B -- "timeout fires" --> E["NodeTimeoutError"]
    B -- "raises an exception" --> F{"interrupt pause?"}
    B -- "returns" --> OK["Writes applied, graph continues"]
    E --> G
    F -- "yes" --> P["Run pauses, no retry, no handler"]
    F -- "no" --> G{"retry_on matches and attempts left?"}
    G -- "yes" --> W["Wait with backoff, discard this attempt's writes"]
    W --> A
    G -- "no" --> H{"error_handler set?"}
    H -- "yes" --> HH["Handler runs with NodeError, returns update or Command"]
    H -- "no" --> X["Run fails with the original exception"]

The order is fixed: any exception (including a timeout) goes to the retry policy first; only when the retries are exhausted does the error handler run; with no handler the run fails with the node's own exception. An interrupt() pause bypasses all of it.

7.2 RetryPolicy and the default rule#

python
from langgraph.types import RetryPolicy

RetryPolicy(
    initial_interval=0.5,    # seconds before the first retry
    backoff_factor=2.0,      # multiplier per retry
    max_interval=128.0,      # cap on the wait
    max_attempts=3,          # total attempts INCLUDING the first
    jitter=True,             # randomize the wait to avoid thundering herds
    retry_on=default_retry_on,   # an exception class, a sequence of classes, or a function (exception) -> bool
)

Attach it to a node: builder.add_node("call_api", call_api, retry_policy=RetryPolicy(max_attempts=3)). max_attempts counts the first attempt, so max_attempts=3 means one try and two retries. The same retry_policy= exists on @task and @entrypoint (08F.14) and on set_node_defaults (7.6). The old retry= argument is deprecated (Part 12).

The default rule. When you do not set retry_on, LangGraph uses default_retry_on. The docs list the exceptions that are not retried, but the source has more to it. Here is what it actually returns, run on 14 November 2026:

python
# r01_default_retry.py: which exceptions does the DEFAULT retry rule retry?
import sqlite3

import httpx
import requests

from langgraph.errors import NodeTimeoutError
from langgraph.types import default_retry_on


class PaymentGatewayDown(Exception):       # a custom exception that subclasses plain Exception
    pass


def http_status(code: int) -> httpx.HTTPStatusError:
    request = httpx.Request("GET", "https://api.example.com/orders")
    return httpx.HTTPStatusError("boom", request=request, response=httpx.Response(code, request=request))


def requests_status(code: int) -> requests.HTTPError:
    response = requests.Response()
    response.status_code = code
    return requests.HTTPError("boom", response=response)


cases = [
    ("ConnectionError", ConnectionError("reset by peer")),
    ("TimeoutError", TimeoutError("timed out")),
    ("OSError", OSError("disk")),
    ("sqlite3.OperationalError", sqlite3.OperationalError("database is locked")),
    ("httpx.HTTPStatusError 503", http_status(503)),
    ("httpx.HTTPStatusError 429", http_status(429)),
    ("httpx.HTTPStatusError 404", http_status(404)),
    ("requests.HTTPError 502", requests_status(502)),
    ("requests.HTTPError 404", requests_status(404)),
    ("requests.HTTPError, no response", requests.HTTPError("no response")),
    ("ValueError", ValueError("bad value")),
    ("TypeError", TypeError("bad type")),
    ("RuntimeError", RuntimeError("bug")),
    ("KeyError", KeyError("missing")),
    ("IndexError", IndexError("oops")),
    ("ZeroDivisionError", ZeroDivisionError("x")),
    ("custom Exception subclass", PaymentGatewayDown("gateway down")),
    ("NodeTimeoutError", NodeTimeoutError("n", 1.0, kind="run", run_timeout=1.0)),
]
for label, exc in cases:
    print(f"{label:28s} retried: {default_retry_on(exc)}")
Output18 lines
ConnectionError              retried: True
TimeoutError                 retried: False
OSError                      retried: False
sqlite3.OperationalError     retried: True
httpx.HTTPStatusError 503    retried: True
httpx.HTTPStatusError 429    retried: False
httpx.HTTPStatusError 404    retried: False
requests.HTTPError 502       retried: True
requests.HTTPError 404       retried: True
requests.HTTPError, no response retried: True
ValueError                   retried: False
TypeError                    retried: False
RuntimeError                 retried: False
KeyError                     retried: False
IndexError                   retried: False
ZeroDivisionError            retried: False
custom Exception subclass    retried: True
NodeTimeoutError             retried: True

The rule, in the order the source applies it:

  1. ConnectionError is retried, even though it is a subclass of OSError and OSError is otherwise excluded. Plain TimeoutError and OSError are not retried.
  2. httpx.HTTPStatusError is retried only for status 500 to 599. A 429 (rate limited) is not retried by the default rule, so if you want a retry on a rate limit write your own retry_on.
  3. requests.HTTPError is retried when there is no response or the status is 5xx, with a catch: the source tests exc.response for truthiness, and a requests.Response is falsy for any error status. The run above shows both a 404 and a 502 being retried, so in practice every requests.HTTPError raised by raise_for_status() is retried, including 4xx. Treat the documented "5xx only" as wrong for requests in this version, and write a retry_on function if it matters to you.
  4. ValueError, TypeError, ArithmeticError, ImportError, LookupError (so KeyError and IndexError), NameError, SyntaxError, RuntimeError, ReferenceError, StopIteration, StopAsyncIteration and OSError are not retried: they usually mean a bug.
  5. Everything else is retried, including your own Exception subclasses and sqlite3.OperationalError (it is not an OSError). NodeTimeoutError (Part 8) is retried too.

So the default is "retry what is probably transient, never retry what is probably a bug", with two quirks (the requests case and the broad "everything else" case). The predicate imports both httpx and requests when it runs; both were installed by langgraph alone in this clean environment, since they come in transitively, but that is not a guarantee for every minimal install.

7.3 Retries in action#

python
# r02_retry_basic.py: RetryPolicy in action: attempts, the attempt counter, what is NOT retried
from typing_extensions import TypedDict

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

attempts: dict[str, int] = {}


class State(TypedDict):
    result: str


def flaky_lookup(state: State, runtime: Runtime):
    attempts["flaky_lookup"] = runtime.execution_info.node_attempt           # 1-indexed
    if runtime.execution_info.node_attempt < 3:
        raise ConnectionError(f"attempt {runtime.execution_info.node_attempt}: connection reset")
    return {"result": f"succeeded on attempt {runtime.execution_info.node_attempt}"}


def buggy(state: State):
    attempts["buggy"] = attempts.get("buggy", 0) + 1
    raise ValueError("a bug in my code")                                        # a ValueError is not retried by default


def always_down(state: State):
    attempts["always_down"] = attempts.get("always_down", 0) + 1
    raise ConnectionError("still down")


# tiny intervals so the demo is instant; in production keep the defaults or similar
fast = dict(initial_interval=0.01, backoff_factor=1.0, jitter=False)


def build(name, fn, **policy):
    return (StateGraph(State).add_node(name, fn, retry_policy=RetryPolicy(**fast, **policy))
            .add_edge(START, name).add_edge(name, END).compile())


print("flaky, max_attempts=3 :", build("flaky_lookup", flaky_lookup, max_attempts=3).invoke({"result": ""}), "| attempts:", attempts["flaky_lookup"])

for name, fn in [("buggy", buggy), ("always_down", always_down)]:
    try:
        build(name, fn, max_attempts=3).invoke({"result": ""})
    except Exception as error:
        print(f"{name:12s}: raised {type(error).__name__}({error}) after {attempts[name]} attempt(s)")

# a policy with retry_on=ValueError retries the bug too; max_attempts counts the FIRST attempt
attempts.pop("buggy")
try:
    build("buggy", buggy, max_attempts=4, retry_on=ValueError).invoke({"result": ""})
except ValueError:
    print("buggy with retry_on=ValueError, max_attempts=4: attempts =", attempts["buggy"])
Output4 lines
flaky, max_attempts=3 : {'result': 'succeeded on attempt 3'} | attempts: 3
buggy       : raised ValueError(a bug in my code) after 1 attempt(s)
always_down : raised ConnectionError(still down) after 3 attempt(s)
buggy with retry_on=ValueError, max_attempts=4: attempts = 4

The flaky node succeeded on its third attempt; the bug (ValueError) was attempted once and raised immediately; the permanently failing node used all three attempts and then raised its own ConnectionError; and retry_on=ValueError with max_attempts=4 retried the bug four times in total. Inside a node, runtime.execution_info.node_attempt gives the 1-indexed attempt number (and node_first_attempt_time the start time), which is useful for logging and for idempotency keys. It exists even when no retry policy is set (the value is then 1). The sample shrinks the intervals so the demo is instant; keep the defaults or similar in production.

More control:

python
# r03_retry_advanced.py: retry_on callables, several policies per node, parallel branches, and write discards
import operator
import sqlite3
from typing import Annotated

from typing_extensions import TypedDict

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

fast = dict(initial_interval=0.01, backoff_factor=1.0, jitter=False)
seen: dict[str, int] = {}


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


class QuotaExceeded(Exception):
    """A custom error that must NOT be retried: waiting will not fix a spent quota."""


def retry_unless_quota(exc: Exception) -> bool:
    if isinstance(exc, QuotaExceeded):
        return False
    return default_retry_on(exc)            # extend the default instead of rewriting it


def quota_node(state: State):
    seen["quota"] = seen.get("quota", 0) + 1
    raise QuotaExceeded("monthly quota spent")


g = (StateGraph(State).add_node("n", quota_node, retry_policy=RetryPolicy(**fast, retry_on=retry_unless_quota))
     .add_edge(START, "n").add_edge("n", END).compile())
try:
    g.invoke({"log": []})
except QuotaExceeded:
    print("1. QuotaExceeded with a custom retry_on: attempts =", seen["quota"])


# 2. a LIST of policies: the first one that matches the exception decides
def make_node(exc_type):
    def node(state: State):
        key = exc_type.__name__
        seen[key] = seen.get(key, 0) + 1
        raise exc_type("fails every time")
    return node


policies = [RetryPolicy(max_attempts=4, retry_on=sqlite3.OperationalError, **fast),   # patient with a locked database
            RetryPolicy(max_attempts=2, retry_on=ConnectionError, **fast)]            # quick to give up on the network
for exc_type in (sqlite3.OperationalError, ConnectionError):
    g = (StateGraph(State).add_node("n", make_node(exc_type), retry_policy=policies)
         .add_edge(START, "n").add_edge("n", END).compile())
    try:
        g.invoke({"log": []})
    except Exception as error:
        print(f"2. policy list, {type(error).__name__}: {seen[exc_type.__name__]} attempts")


# 3. parallel branches: only the failing branch is retried
def good(state: State):
    seen["good"] = seen.get("good", 0) + 1
    return {"log": ["good ran"]}


def flaky(state: State, runtime: Runtime):
    seen["flaky"] = runtime.execution_info.node_attempt
    if runtime.execution_info.node_attempt < 3:
        raise ConnectionError("blip")
    return {"log": [f"flaky ran (attempt {runtime.execution_info.node_attempt})"]}


b = StateGraph(State)
b.add_node("good", good)
b.add_node("flaky", flaky, retry_policy=RetryPolicy(**fast))
b.add_edge(START, "good").add_edge(START, "flaky").add_edge("good", END).add_edge("flaky", END)
print("3. parallel:", sorted(b.compile().invoke({"log": []})["log"]), "| good ran", seen["good"], "time(s), flaky attempts", seen["flaky"])


# 4. a failed attempt's WRITES are discarded; only the successful attempt's update is applied
def writes_then_fails(state: State, runtime: Runtime):
    if runtime.execution_info.node_attempt == 1:
        raise ConnectionError("fail after preparing a result")
    return {"log": ["written by attempt 2"]}


g = (StateGraph(State).add_node("n", writes_then_fails, retry_policy=RetryPolicy(**fast))
     .add_edge(START, "n").add_edge("n", END).compile())
print("4. state after a retry:", g.invoke({"log": []}))
Output5 lines
1. QuotaExceeded with a custom retry_on: attempts = 1
2. policy list, OperationalError: 4 attempts
2. policy list, ConnectionError: 2 attempts
3. parallel: ['flaky ran (attempt 3)', 'good ran'] | good ran 1 time(s), flaky attempts 3
4. state after a retry: {'log': ['written by attempt 2']}
  1. Extend, do not replace, the default. retry_on can be a function; calling default_retry_on(exc) (importable from langgraph.types, though it is not in __all__) after your own exclusions keeps the standard behaviour for everything else. QuotaExceeded was attempted once.
  2. A list of policies: the first policy that matches the exception decides. A locked database got four patient attempts and a dropped connection two.
  3. Parallel branches retry independently. Only the failing branch was re-run; its successful sibling ran once.
  4. A failed attempt's writes are discarded. Only the successful attempt's update reached the state.

7.4 Retries are at-least-once: idempotency keys#

A retry re-runs the entire node function. Graph writes from a failed attempt are thrown away, but side effects outside the graph (a payment, an email, a row in another database) are not. Retries therefore give at-least-once execution: the node body may run more than once, and the world must tolerate that.

The classic failure: the charge succeeds, the network drops the acknowledgement, the node raises ConnectionError, the policy retries, and the customer is charged twice. The fix is an idempotency key: a value that is the same on every attempt, sent with the request so the external system recognizes the repeat.

python
# r04_idempotency.py: retries are at-least-once, so a side effect needs an idempotency key
from typing_extensions import TypedDict

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


class FakeGateway:
    """Stands in for a payment API: the charge happens, then the acknowledgement may be lost."""

    def __init__(self):
        self.charges: dict[str, int] = {}       # idempotency key -> amount
        self.ledger: list[int] = []             # every charge the bank actually made

    def charge(self, amount: int, key: str | None):
        if key is None or key not in self.charges:      # a real gateway deduplicates on the key
            self.ledger.append(amount)
            if key is not None:
                self.charges[key] = amount


class State(TypedDict):
    order_id: str
    status: str


def make_node(gateway: FakeGateway, use_key: bool):
    def charge_card(state: State, runtime: Runtime):
        key = f"charge:{state['order_id']}" if use_key else None    # derived from DURABLE state: same on every attempt
        gateway.charge(480, key)                                     # the money moves ...
        if runtime.execution_info.node_attempt == 1:
            raise ConnectionError("acknowledgement lost")            # ... but the node still fails
        return {"status": "charged"}
    return charge_card


for use_key in (False, True):
    gateway = FakeGateway()
    g = (StateGraph(State)
         .add_node("charge_card", make_node(gateway, use_key),
                   retry_policy=RetryPolicy(initial_interval=0.01, jitter=False))
         .add_edge(START, "charge_card").add_edge("charge_card", END).compile())
    result = g.invoke({"order_id": "A-1042", "status": "new"})
    print(f"idempotency key: {use_key!s:5} -> status={result['status']}, bank ledger={gateway.ledger}")
Output2 lines
idempotency key: False -> status=charged, bank ledger=[480, 480]
idempotency key: True  -> status=charged, bank ledger=[480]

Without a key the bank ledger shows two charges for one order. With charge:A-1042, derived from durable state (the order id), the second request is recognized and ignored. Three rules for keys:

  • Derive the key from state that is the same on every attempt (an order id, a ticket id), or from a value you generated and saved in an earlier node. A key generated inside the failing node (uuid4()) is different on every attempt and protects nothing. If you must generate one, generate it in its own node first and make sure it is checkpointed (durability="sync"; 08F.11 owns durability modes).
  • A lost acknowledgement is "unknown", not "failed". If the final attempt fails after the request may have been accepted, do not assume nothing happened: look it up by key, or hand it to a person (7.5).
  • Not every tool is safe to retry. Reading is; "send an email" is only as safe as the provider's deduplication. 08A.14, Part 5 covers idempotent tool design for agents, and 08F.8, 4.5 warned that ToolRetryMiddleware retries everything unless you restrict it.

7.5 Error handlers: after the retries are spent#

An error handler is a function attached to a node that runs only after the node has failed for good: after the retries are exhausted, or immediately when there is no retry policy. It receives the state and a NodeError and returns an update or a Command, so it can route the run onto a recovery path, which is how you write compensation steps (a saga: if step 3 fails, undo or mark steps 1 and 2).

python
# r05_error_handler.py: error_handler (runs AFTER retries are exhausted), NodeError, and compensation
from typing import Literal

from typing_extensions import TypedDict

from langgraph.errors import NodeError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, RetryPolicy

attempts = {"charge": 0}


class State(TypedDict):
    status: str
    detail: str


def charge_payment(state: State):
    attempts["charge"] += 1
    raise ConnectionError("payment gateway unreachable")


def payment_error_handler(state: State, error: NodeError) -> Command[Literal["finalize"]]:
    # error.node is the failed node's name, error.error is the exception that was raised
    return Command(update={"status": "needs_manual_payment", "detail": f"{error.node} failed: {error.error!r}"},
                   goto="finalize")


def finalize(state: State):
    return {"detail": state["detail"] + " (a person has been notified)"}


builder = StateGraph(State)
builder.add_node("charge_payment", charge_payment,
                 retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False, retry_on=ConnectionError),
                 error_handler=payment_error_handler)
builder.add_node("finalize", finalize)
builder.add_edge(START, "charge_payment")
builder.add_edge("finalize", END)
graph = builder.compile()

result = graph.invoke({"status": "new", "detail": ""})
print("attempts before the handler ran:", attempts["charge"])
print("result:", result)

# the same node WITHOUT a handler: the run fails with the node's own exception
plain = StateGraph(State).add_node("charge_payment", charge_payment).add_edge(START, "charge_payment").compile()
try:
    plain.invoke({"status": "new", "detail": ""})
except ConnectionError as error:
    print("no handler -> raised", type(error).__name__, "-", error)
Output3 lines
attempts before the handler ran: 3
result: {'status': 'needs_manual_payment', 'detail': "charge_payment failed: ConnectionError('payment gateway unreachable') (a person has been notified)"}
no handler -> raised ConnectionError - payment gateway unreachable

The node was attempted three times, then the handler ran with the failure and sent the run to finalize, so the graph finished with a status a person can act on, instead of raising. The same node without a handler raised its original exception. The details:

  • NodeError has two fields: node (the failed node's name) and error (the exception). It is injected because of the type annotation error: NodeError, in the same way runtime: Runtime is. The allowed handler signatures are (state), (state, runtime), (state, error) and (state, error, config).
  • A handler may return a dict update or a Command. The next sample shows the surprise below.
  • One handler per node. If the handler itself raises, the failure propagates as if there were no handler. According to the docs, a failing subgraph surfaces at the parent node's handler (with the subgraph's exception in error.error), and failure provenance is checkpointed, so a crash between the failure and the end of the handler replays the handler with the same NodeError. Those two were not run for this lesson.
python
# r06_defaults_handlers.py: dict-returning handlers, handler signatures, set_node_defaults, handler failures
from typing import Literal

from typing_extensions import TypedDict

from langchain_core.runnables import RunnableConfig
from langgraph.errors import NodeError
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from langgraph.types import Command, RetryPolicy

calls: dict[str, int] = {}


class State(TypedDict):
    out: str


def count(name):
    calls[name] = calls.get(name, 0) + 1


def fetch(state: State):
    count("fetch")
    raise ConnectionError("down")


def fallback_value(state: State, error: NodeError):
    return {"out": f"fallback after {type(error.error).__name__}"}       # a plain dict: the branch stops here


def after(state: State):
    return {"out": state["out"] + " -> after"}


# 1. a handler that returns a plain dict: the update is saved, but the failed node's normal edges do NOT fire
g = (StateGraph(State).add_node("fetch", fetch, error_handler=fallback_value).add_node("after", after)
     .add_edge(START, "fetch").add_edge("fetch", "after").add_edge("after", END).compile())
print("1.", g.invoke({"out": ""}), "<- 'after' never ran: nothing told the graph where to go next")


# 2. the other handler signatures
def with_runtime(state: State, runtime: Runtime, error: NodeError):
    return {"out": f"attempt {runtime.execution_info.node_attempt}, error {error.error}"}


def with_config(state: State, error: NodeError, config: RunnableConfig):
    return {"out": f"thread {config['configurable']['thread_id']}: {error.error}"}


for label, handler in [("(state, runtime, error)", with_runtime), ("(state, error, config)", with_config)]:
    g = (StateGraph(State).add_node("fetch", fetch, error_handler=handler)
         .add_edge(START, "fetch").add_edge("fetch", END).compile())
    print("2.", label, "->", g.invoke({"out": ""}, {"configurable": {"thread_id": "t9"}}))


# 3. a handler that itself fails: the failure propagates as if there were no handler
def broken_handler(state: State, error: NodeError):
    raise RuntimeError("handler bug")


g = (StateGraph(State).add_node("fetch", fetch, error_handler=broken_handler)
     .add_edge(START, "fetch").add_edge("fetch", END).compile())
try:
    g.invoke({"out": ""})
except Exception as error:
    print("3. broken handler ->", type(error).__name__, "-", error)


# 4. set_node_defaults: one policy for the whole graph, per-node values win
calls.clear()


def a(state: State):
    count("a")
    raise ConnectionError("a down")


def b(state: State):
    count("b")
    raise ConnectionError("b down")


def default_handler(state: State, error: NodeError) -> Command[Literal["b", "__end__"]]:
    # the ANNOTATION is what asks LangGraph to inject the error; a Command says where to go next
    return Command(update={"out": state["out"] + f" [{error.node} handled]"}, goto="b" if error.node == "a" else END)


builder = StateGraph(State)
builder.set_node_defaults(retry_policy=RetryPolicy(max_attempts=4, initial_interval=0.01, jitter=False),
                          error_handler=default_handler)
builder.add_node("a", a)                                                     # inherits both defaults
builder.add_node("b", b, retry_policy=RetryPolicy(max_attempts=2, initial_interval=0.01, jitter=False))  # own retry policy
builder.add_edge(START, "a").add_edge("a", "b").add_edge("b", END)
print("4.", builder.compile().invoke({"out": ""}), "| attempts:", calls)


# 5. the trap: without the NodeError annotation nothing is injected and the handler call itself fails
g = (StateGraph(State).add_node("fetch", fetch, error_handler=lambda state, error: {"out": "handled"})
     .add_edge(START, "fetch").add_edge("fetch", END).compile())
try:
    g.invoke({"out": ""})
except TypeError as error:
    print("5. unannotated handler ->", type(error).__name__, "-", str(error).splitlines()[0])
Output6 lines
1. {'out': 'fallback after ConnectionError'} <- 'after' never ran: nothing told the graph where to go next
2. (state, runtime, error) -> {'out': 'attempt 1, error down'}
2. (state, error, config) -> {'out': 'thread t9: down'}
3. broken handler -> RuntimeError - handler bug
4. {'out': ' [a handled] [b handled]'} | attempts: {'a': 4, 'b': 2}
5. unannotated handler -> TypeError - <lambda>() missing 1 required positional argument: 'error'
  1. A dict-returning handler ends that branch. The update was saved, but the failed node's normal outgoing edge did not fire: after never ran. The handler ran as its own step (the updates stream names it __error_handler__fetch). To continue the graph, return Command(update=..., goto=...). This is observed behaviour in 1.2.22; the docs do not spell it out, so test your recovery paths.
  2. Other signatures work: the handler can read the attempt number from runtime or the thread id from config.
  3. A broken handler raised its own error.
  4. Defaults (7.6): one retry policy and one handler for the whole graph, with a per-node policy winning for b.
  5. The annotation is not optional. A lambda without the NodeError annotation is called without the error and fails with a TypeError.

7.6 set_node_defaults: one policy for the whole graph#

python
builder = StateGraph(State)
builder.set_node_defaults(retry_policy=RetryPolicy(max_attempts=4), error_handler=default_handler, timeout=60,
                          cache_policy=None)

StateGraph.set_node_defaults(*, retry_policy=None, cache_policy=None, error_handler=None, timeout=None) sets defaults that are resolved at compile(); call it before or after add_node. A value set on a node wins over the default. Details worth knowing:

  • retry_policy and timeout defaults also apply to error-handler nodes; cache_policy and error_handler defaults apply only to regular nodes. A handler never gets a default handler ("handlers never catch themselves"), and caching a handler's result would be unsafe.
  • Defaults are not inherited by subgraphs: each compiled subgraph needs its own.
  • This replaces the habit of writing try/except in every node. It is a 1.2 feature, so check your installed version.

7.7 LLM-recoverable and user-fixable errors#

Some errors are for the model or the person to fix, and a retry policy is the wrong tool. For a model-recoverable error (a tool rejected the arguments), catch the specific tool error in the node, write it to state and route back to the model with Command, so the next model call sees what went wrong:

python
def execute_tool(state: State) -> Command[Literal["agent", "execute_tool"]]:
    try:
        result = run_tool(state["tool_call"])
        return Command(update={"tool_result": result}, goto="agent")
    except ToolError as error:                       # a specific, expected error, not Exception
        return Command(update={"tool_result": f"Tool error: {error}"}, goto="agent")

run_tool, ToolError and State stand for your own code. The agent-level versions of this idea are ToolNode's error handling (08F.10, 12.2) and ToolErrorMiddleware (08F.8, 4.4). For a user-fixable error (an ambiguous request, a missing field), call interrupt() and ask. Loop bounds still apply: a model that keeps producing the same bad call needs a call limit (08F.8, 7.5).

7.8 Retries at other layers stack#

A graph retry policy is one of four places a call can be retried: the provider SDK's own retries (03.8), the chat model's max_retries (08F.5), ModelRetryMiddleware and ToolRetryMiddleware (08F.8, 8.10), and the node's RetryPolicy. Layers multiply: three at each of two layers is nine calls to a failing provider, and nine charges to your rate limit. Pick one layer for each kind of call. A sound default: retry the model call inside the model (or its middleware), where the failure is understood and the call is idempotent, and use the node RetryPolicy for nodes that talk to your own services. Turn the other layers down when you add one.


Part 8: Timeouts#

Deep-dive

A model call that never returns is the most common way an agent hangs. (This Part is about execution timeouts on a node. The timeout on a human's answer, where an unanswered approval expires to deny, is a different thing and is in 08A.12 Part 5.) LangGraph 1.2 added node timeouts: a per-node limit after which the node's attempt is cancelled and a NodeTimeoutError is raised.

8.1 The three forms#

python
from datetime import timedelta
from langgraph.types import TimeoutPolicy

builder.add_node("model", call_model, timeout=60)                              # a number: a hard run timeout, in seconds
builder.add_node("model", call_model, timeout=timedelta(minutes=2))            # a timedelta: the same
builder.add_node("model", call_model, timeout=TimeoutPolicy(run_timeout=120, idle_timeout=30))
Field Meaning
run_timeout A hard wall-clock cap per attempt, never refreshed
idle_timeout The longest the node may go without observable progress; the clock resets whenever progress is seen
refresh_on What counts as progress for the idle clock: "auto" (default) or "heartbeat"

Values must be greater than zero. The same timeout= parameter exists on @task, @entrypoint (08F.14) and set_node_defaults (7.6), and per push on Send("worker", {...}, timeout=TimeoutPolicy(idle_timeout=15)). Choose the number from your real latencies (the p99 of the call plus margin), not from hope; the sample uses fractions of a second only so that it finishes quickly.

8.2 Behaviour#

python
# t01_timeouts.py: node timeouts (async nodes only): run timeout, NodeTimeoutError, retries, sync nodes rejected
import asyncio
from datetime import timedelta

from typing_extensions import TypedDict

from langgraph.errors import NodeTimeoutError
from langgraph.graph import END, START, StateGraph
from langgraph.types import RetryPolicy, TimeoutPolicy

attempts = {"slow": 0}


class State(TypedDict):
    out: str


async def slow(state: State):
    attempts["slow"] += 1
    await asyncio.sleep(5)                       # stands in for a model or API call that hangs
    return {"out": "finished"}


async def fast(state: State):
    await asyncio.sleep(0.01)
    return {"out": "finished in time"}


def build(node, **options):
    return StateGraph(State).add_node("n", node, **options).add_edge(START, "n").add_edge("n", END).compile()


async def main():
    # 1. a number is a hard run timeout in seconds; the error says which clock fired
    try:
        await build(slow, timeout=0.2).ainvoke({"out": ""})
    except NodeTimeoutError as error:
        print("1.", type(error).__name__, "| node:", error.node, "| kind:", error.kind, "| timeout:", error.timeout,
              "| elapsed >= timeout:", error.elapsed >= error.timeout, "| is a built-in TimeoutError:", isinstance(error, TimeoutError))
        print("   message:", str(error))

    # 2. a node that finishes in time is untouched; timedelta and TimeoutPolicy are accepted too
    print("2.", (await build(fast, timeout=timedelta(seconds=1)).ainvoke({"out": ""}))["out"],
          "|", (await build(fast, timeout=TimeoutPolicy(run_timeout=1, idle_timeout=0.5)).ainvoke({"out": ""}))["out"])

    # 3. the default retry rule RETRIES a timeout, and every attempt gets a fresh timer
    attempts["slow"] = 0
    g = build(slow, timeout=0.1, retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False))
    try:
        await g.ainvoke({"out": ""})
    except NodeTimeoutError:
        print("3. attempts before giving up:", attempts["slow"])

    # 4. values must be positive
    for bad in (0, -1):
        try:
            build(fast, timeout=bad)
        except ValueError as error:
            print(f"4. timeout={bad} ->", error)


asyncio.run(main())


# 5. a SYNC node cannot have a timeout: Python cannot safely cancel a running thread
def sync_node(state: State):
    return {"out": "x"}


try:
    build(sync_node, timeout=1)
except Exception as error:
    print("5.", type(error).__name__, "-", error)
Output · the elapsed time in the message differs from run to run7 lines
1. NodeTimeoutError | node: n | kind: run | timeout: 0.2 | elapsed >= timeout: True | is a built-in TimeoutError: False
   message: Node 'n' exceeded its run timeout of 0.200s (elapsed: 0.202s).
2. finished in time | finished in time
3. attempts before giving up: 3
4. timeout=0 -> run_timeout must be greater than 0
4. timeout=-1 -> run_timeout must be greater than 0
5. ValueError - Node timeouts are only supported for async nodes because sync Python execution cannot be safely cancelled in-process. Node 'n' is sync.
  1. The error is langgraph.errors.NodeTimeoutError with node, timeout, elapsed, kind ("run" or "idle"), idle_timeout and run_timeout. It does not subclass the built-in TimeoutError (which is an OSError), on purpose, so the default retry rule retries it.
  2. A node that finishes in time is unaffected, and a bare number, a timedelta and a TimeoutPolicy are all accepted.
  3. Each attempt gets a fresh timer and a timed-out attempt's writes are cleared. With the default retry rule a timeout is retried, so a node with timeout=0.1 and three attempts ran three times (and the total wait is up to the sum). Use a custom retry_on if a timeout should not be retried.
  4. Zero and negative values are rejected with ValueError: run_timeout must be greater than 0.
  5. Timeouts are async only. A sync node, task or entrypoint with a timeout is rejected when you build the graph, because Python cannot safely cancel running synchronous code in-process. Wrap blocking calls with asyncio.to_thread inside an async node.

8.3 Blocking calls defeat the timeout#

python
# t03_blocking_send.py: blocking calls defeat timeouts; asyncio.to_thread keeps the loop free; Send(timeout=)
import asyncio
import operator
import time
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.errors import NodeTimeoutError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send, TimeoutPolicy


class State(TypedDict):
    out: str


async def blocking(state: State):
    time.sleep(0.8)                           # BAD: blocks the whole event loop, nothing can cancel it
    return {"out": "done"}


async def offloaded(state: State):
    await asyncio.to_thread(time.sleep, 0.8)  # the loop stays free, so the timeout can fire
    return {"out": "done"}


def build(node):
    return StateGraph(State).add_node("n", node, timeout=0.2).add_edge(START, "n").add_edge("n", END).compile()


async def timed(label, node):
    started = time.perf_counter()
    try:
        await build(node).ainvoke({"out": ""})
        outcome = "finished"
    except NodeTimeoutError:
        outcome = "NodeTimeoutError"
    print(f"{label:26s}-> {outcome} after {time.perf_counter() - started:.1f}s (timeout was 0.2s)")


# per-push timeouts: each Send can carry its own policy
class Fan(TypedDict):
    items: list[str]
    results: Annotated[list[str], operator.add]


class Work(TypedDict):
    item: str


async def worker(state: Work):
    await asyncio.sleep(0.5 if state["item"] == "slow" else 0.01)
    return {"results": [f"{state['item']} ok"]}


def fan_out(state: Fan):
    return [Send("worker", {"item": item}, timeout=TimeoutPolicy(run_timeout=0.2)) for item in state["items"]]


async def main():
    await timed("blocking time.sleep", blocking)
    await timed("asyncio.to_thread", offloaded)

    g = (StateGraph(Fan).add_node("worker", worker).add_conditional_edges(START, fan_out, ["worker"])
         .add_edge("worker", END).compile())
    try:
        await g.ainvoke({"items": ["a", "slow"], "results": []})
    except NodeTimeoutError as error:
        print("Send with a timeout: the 'slow' push failed with", type(error).__name__, "| kind:", error.kind)


asyncio.run(main())
Output3 lines
blocking time.sleep       -> finished after 0.8s (timeout was 0.2s)
asyncio.to_thread         -> NodeTimeoutError after 0.2s (timeout was 0.2s)
Send with a timeout: the 'slow' push failed with NodeTimeoutError | kind: run

The node that called time.sleep(0.8) inside an async def blocked the whole event loop: the 0.2-second timeout could not fire, the node finished after 0.8 seconds, and no error was raised. The node that offloaded the same sleep with asyncio.to_thread was cancelled at 0.2 seconds. One more caveat: cancelling the awaiting node does not stop the worker thread that to_thread started; the blocking call itself keeps running until it returns, so give blocking clients their own timeouts too. The last line shows a per-push policy on Send: only the slow push timed out. How timeouts behave with Send inside nested subgraphs was not verified for this lesson.

8.4 Idle timeouts, progress and heartbeats#

A run timeout is a blunt tool for a node that legitimately works for a long time but should never go quiet (a long model call that streams tokens, a loop over batches). The idle timeout allows that: it fires only after a stretch of no progress. With refresh_on="auto" the idle clock resets on state writes, yielded stream chunks, child-task scheduling, stream_writer calls and any LangChain callback event (model tokens, tool calls, chain start and end), according to the docs. With refresh_on="heartbeat" only explicit runtime.heartbeat() calls reset it, for nodes whose own work you want to prove is alive.

python
# t02_idle_heartbeat.py: idle timeouts: what counts as progress, and runtime.heartbeat()
import asyncio

from typing_extensions import TypedDict

from langgraph.errors import NodeTimeoutError
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from langgraph.types import TimeoutPolicy


class State(TypedDict):
    out: str


async def silent_worker(state: State):
    await asyncio.sleep(0.6)                      # no state writes, no stream output, no callbacks: no progress
    return {"out": "done"}


async def chatty_worker(state: State, runtime: Runtime):
    for _ in range(6):                            # six 0.1 s batches, 0.6 s in total
        await asyncio.sleep(0.1)
        runtime.heartbeat()                       # "I am alive": resets the idle clock when refresh_on="heartbeat"
    return {"out": "done"}


async def streaming_worker(state: State, runtime: Runtime):
    for i in range(6):
        await asyncio.sleep(0.1)
        runtime.stream_writer({"progress": i})    # a custom stream chunk counts as progress under refresh_on="auto"
    return {"out": "done"}


def build(node, policy):
    return StateGraph(State).add_node("n", node, timeout=policy).add_edge(START, "n").add_edge("n", END).compile()


async def attempt(label, node, policy, **run_kwargs):
    g = build(node, policy)
    try:
        # consume the stream so custom chunks are really emitted
        async for _ in g.astream({"out": ""}, stream_mode="custom", **run_kwargs):
            pass
        print(f"{label:46s} -> finished")
    except NodeTimeoutError as error:
        print(f"{label:46s} -> NodeTimeoutError kind={error.kind!r}")


async def main():
    idle = TimeoutPolicy(idle_timeout=0.3)
    await attempt("idle 0.3s, silent 0.6s worker", silent_worker, idle)
    await attempt("idle 0.3s, worker writes to the stream", streaming_worker, idle)
    await attempt("idle 0.3s refresh_on=heartbeat, stream only", streaming_worker, TimeoutPolicy(idle_timeout=0.3, refresh_on="heartbeat"))
    await attempt("idle 0.3s refresh_on=heartbeat, heartbeats", chatty_worker, TimeoutPolicy(idle_timeout=0.3, refresh_on="heartbeat"))
    await attempt("run 0.3s (idle never refreshes a run clock)", chatty_worker, TimeoutPolicy(run_timeout=0.3, idle_timeout=0.3, refresh_on="heartbeat"))


asyncio.run(main())
Output5 lines
idle 0.3s, silent 0.6s worker                  -> NodeTimeoutError kind='idle'
idle 0.3s, worker writes to the stream         -> finished
idle 0.3s refresh_on=heartbeat, stream only    -> NodeTimeoutError kind='idle'
idle 0.3s refresh_on=heartbeat, heartbeats     -> finished
run 0.3s (idle never refreshes a run clock)    -> NodeTimeoutError kind='run'

Reading the five lines: a silent worker hit the idle limit; a worker that writes to the stream kept resetting it under "auto"; the same stream writes did not count under "heartbeat"; calling runtime.heartbeat() did; and a run_timeout fires no matter how much progress there is. The sample did not test the LangChain-callback refresh (it needs a model); the list above is from the docs. runtime.heartbeat() does nothing outside an idle-timed attempt. An alpha release note once showed a yield-based heartbeat; the current docs and the package use runtime.heartbeat().

8.5 Layers of timeouts#

A node timeout is one of several, and they compose. The HTTP client has a connect and read timeout (03.8), the provider may enforce its own, and your web server cuts requests at some limit. Set the inner timeouts shorter than the outer ones so the most specific layer reports the failure, and give each node a timeout that is longer than its client's. A node timeout without a client timeout still leaves the underlying request running after the node has moved on.


Part 9: Node caching#

Deep-dive

9.1 What it does#

A node whose result depends only on its input can be cached: the next call with the same input skips the node and reuses the saved result. It is memoization across runs and threads, keyed on the node's input, with an optional time to live. Typical uses are an expensive lookup that many threads repeat (a policy table, an embedding of a fixed text, a model call over a static prompt) and development loops where you rerun a graph a hundred times.

You need both halves: a cache_policy on the node (or via set_node_defaults) and a cache on compile().

python
from langgraph.cache.memory import InMemoryCache
from langgraph.types import CachePolicy

builder.add_node("expensive_node", expensive_node, cache_policy=CachePolicy(ttl=3))   # ttl in seconds; None = never expires
graph = builder.compile(cache=InMemoryCache())

CachePolicy(key_func=default_cache_key, ttl=None): the default key function pickles the node's input; a custom key_func receives the node input and returns a str or bytes. @task(cache_policy=...) and @entrypoint(cache=..., cache_policy=...) exist for the Functional API.

9.2 A run#

python
# c01_cache.py: node caching: CachePolicy, InMemoryCache, ttl, key_func, clear_cache
import time

from typing_extensions import TypedDict

from langgraph.cache.memory import InMemoryCache
from langgraph.graph import END, START, StateGraph
from langgraph.types import CachePolicy

runs = {"expensive": 0, "lookup": 0}


class State(TypedDict):
    x: int
    user: str
    result: int


def expensive_node(state: State):
    runs["expensive"] += 1                      # a hit skips the node, so this counter does not move
    return {"result": state["x"] * 2}


builder = StateGraph(State)
builder.add_node("expensive_node", expensive_node, cache_policy=CachePolicy(ttl=1))
builder.add_edge(START, "expensive_node").add_edge("expensive_node", END)
graph = builder.compile(cache=InMemoryCache())

print("1. first call :", graph.invoke({"x": 5, "user": "ana", "result": 0}, stream_mode="updates"))
print("   second call:", graph.invoke({"x": 5, "user": "ana", "result": 0}, stream_mode="updates"))
print("   different input:", graph.invoke({"x": 6, "user": "ana", "result": 0}, stream_mode="updates"))
print("   node body ran", runs["expensive"], "times for 3 calls")
time.sleep(1.2)
graph.invoke({"x": 5, "user": "ana", "result": 0})
print("   after the ttl expired, node body ran", runs["expensive"], "times")

# 2. the cache key is the node INPUT: a custom key_func can ignore parts of it
def lookup(state: State):
    runs["lookup"] += 1
    return {"result": len(state["user"])}


builder = StateGraph(State)
builder.add_node("lookup", lookup, cache_policy=CachePolicy(key_func=lambda state: str(state["x"])))   # user is NOT in the key
builder.add_edge(START, "lookup").add_edge("lookup", END)
g2 = builder.compile(cache=InMemoryCache())
g2.invoke({"x": 1, "user": "ana", "result": 0})
g2.invoke({"x": 1, "user": "bartholomew", "result": 0})          # different user, same key: served from the cache
print("\n2. key_func ignoring 'user': node ran", runs["lookup"], "time(s); second answer was", g2.invoke({"x": 1, "user": "bartholomew", "result": 0})["result"], "(len('ana') = 3)")

# 3. a policy without a cache on the graph does nothing, and clear_cache needs a cache
builder = StateGraph(State)
builder.add_node("expensive_node", expensive_node, cache_policy=CachePolicy())
builder.add_edge(START, "expensive_node").add_edge("expensive_node", END)
no_cache_graph = builder.compile()
runs["expensive"] = 0
no_cache_graph.invoke({"x": 1, "user": "a", "result": 0}); no_cache_graph.invoke({"x": 1, "user": "a", "result": 0})
print("3. policy but no cache on compile(): node ran", runs["expensive"], "times for 2 identical calls")
try:
    no_cache_graph.clear_cache()
except ValueError as error:
    print("   clear_cache() ->", error)

# 4. clearing: all nodes, or named nodes
runs["expensive"] = 0
graph.invoke({"x": 9, "user": "a", "result": 0}); graph.invoke({"x": 9, "user": "a", "result": 0})
graph.clear_cache()
graph.invoke({"x": 9, "user": "a", "result": 0})
print("4. identical calls: hit, then cleared, then miss -> node ran", runs["expensive"], "times (expected 2)")
Output10 lines
1. first call : [{'expensive_node': {'result': 10}}]
   second call: [{'expensive_node': {'result': 10}, '__metadata__': {'cached': True}}]
   different input: [{'expensive_node': {'result': 12}}]
   node body ran 2 times for 3 calls
   after the ttl expired, node body ran 3 times

2. key_func ignoring 'user': node ran 1 time(s); second answer was 3 (len('ana') = 3)
3. policy but no cache on compile(): node ran 2 times for 2 identical calls
   clear_cache() -> No cache is set for this graph. Cannot clear cache.
4. identical calls: hit, then cleared, then miss -> node ran 2 times (expected 2)
  1. The second identical call came back in the updates stream with '__metadata__': {'cached': True} and the node body did not run (the counter did not move). A different input is a different key. After the ttl expired the node ran again.
  2. The key is the node input, not the whole state, and a key_func can narrow it: keying on x alone meant a different user got the first user's answer. That is exactly right for a policy table keyed by tier and exactly wrong for anything that depends on the user. Put everything the result depends on into the key.
  3. A cache_policy without a cache on compile() does nothing, silently: the node ran twice for two identical calls. And clear_cache() on a graph with no cache raises ValueError: No cache is set for this graph. Cannot clear cache.
  4. graph.clear_cache() empties the cache for all nodes; pass nodes=[...] to clear named ones (aclear_cache is the async form).

9.3 What is safe to cache#

Cache it Do not cache it
Pure lookups and transformations of the input Anything with a side effect (a cache hit skips the node, so the email is not sent again, which may or may not be what you want)
A policy or catalogue lookup keyed by the right fields A node that reads the clock, a random number or live data not in its input
Embeddings of fixed text; static model calls Per-user data under a key that omits the user
Slow steps in a dev loop Anything where a stale answer costs more than the call

9.4 Backends#

Backend Import Package Lifetime
InMemoryCache langgraph.cache.memory langgraph-checkpoint Process only
SqliteCache(path=...) langgraph.cache.sqlite langgraph-checkpoint-sqlite A file; survives restarts
RedisCache(redis, prefix=...) langgraph.cache.redis module present in langgraph-checkpoint 4.3.2 A shared server; the docs do not list it, so check them before relying on it
python
# c02_sqlite_cache.py: a SQLite-backed node cache survives a restart (needs langgraph-checkpoint-sqlite)
import os
import tempfile

from typing_extensions import TypedDict

from langgraph.cache.sqlite import SqliteCache
from langgraph.graph import END, START, StateGraph
from langgraph.types import CachePolicy

runs = {"n": 0}


class State(TypedDict):
    x: int
    result: int


def expensive(state: State):
    runs["n"] += 1
    return {"result": state["x"] * 2}


def build(path):
    b = StateGraph(State)
    b.add_node("expensive", expensive, cache_policy=CachePolicy(ttl=60))
    b.add_edge(START, "expensive").add_edge("expensive", END)
    return b.compile(cache=SqliteCache(path=path))


path = os.path.join(tempfile.mkdtemp(), "node-cache.db")
build(path).invoke({"x": 21, "result": 0})
print("first process : node ran", runs["n"], "time(s)")
build(path).invoke({"x": 21, "result": 0})           # a brand-new graph and cache object on the same file
print("second 'process': node ran", runs["n"], "time(s) in total (the answer came from the file)")
print("cache file exists:", os.path.exists(path))
Output3 lines
first process : node ran 1 time(s)
second 'process': node ran 1 time(s) in total (the answer came from the file)
cache file exists: True

A new graph and a new cache object on the same file reused the stored result, so the node body ran once in total. RedisCache was not run for this lesson (it needs a Redis server).


Part 10: Cancellation, graceful shutdown and hard limits#

Deep-dive

Stopping a run has three different meanings, and LangGraph gives each its own tool.

10.1 Graceful shutdown: drain#

You are deploying, or the platform sent SIGTERM. You want running graphs to stop at a safe point, with a saved checkpoint, so another process can resume them. That is a drain. Create one RunControl per run, pass it as control=, and call request_drain(reason) from your signal handler.

python
# k01_drain.py: graceful shutdown: ask a run to stop at the next super-step boundary, then resume it
import threading
import time

from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphDrained
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import RunControl, Runtime

log: list[str] = []


class State(TypedDict):
    steps: list[str]


def step(name: str, seconds: float = 0.0):
    def node(state: State, runtime: Runtime):
        log.append(f"{name} started (drain requested: {runtime.drain_requested})")
        time.sleep(seconds)
        return {"steps": state["steps"] + [name]}
    node.__name__ = name
    return node


builder = StateGraph(State)
builder.add_node(step("fetch", 0.3)).add_node(step("transform", 0.1)).add_node(step("publish"))
builder.add_edge(START, "fetch").add_edge("fetch", "transform").add_edge("transform", "publish").add_edge("publish", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "job-1"}}

control = RunControl()                                       # one per run
threading.Timer(0.1, lambda: control.request_drain("deploy")).start()   # stands in for a SIGTERM handler

try:
    graph.invoke({"steps": []}, config, control=control)
    print("finished normally")
except GraphDrained as drained:
    print("drained, reason:", drained.reason)
    snapshot = graph.get_state(config)
    print("state saved    :", snapshot.values, "| next:", snapshot.next)

print("log so far     :", log)

# after the restart: resume the SAME thread with input None and a fresh control object
result = graph.invoke(None, config)
print("resumed result :", result)
print("log at the end :", log)
Output5 lines
drained, reason: deploy
state saved    : {'steps': ['fetch']} | next: ('transform',)
log so far     : ['fetch started (drain requested: False)']
resumed result : {'steps': ['fetch', 'transform', 'publish']}
log at the end : ['fetch started (drain requested: False)', 'transform started (drain requested: False)', 'publish started (drain requested: False)']

The drain was requested 0.1 seconds into the 0.3-second fetch node. fetch ran to completion (it was never interrupted), the run stopped at the boundary before transform, GraphDrained("deploy") was raised to the caller, and the saved state shows fetch done and transform next. The later invoke(None, config) on the same thread continued exactly there, in the same process here, but it could as well be a new one.

The rules:

  • Drain is cooperative and happens between super-steps. A node, and its retries, finish first. Inside a node you can read runtime.drain_requested and runtime.drain_reason to skip expensive optional work.
  • If the graph finishes on the same step, invoke returns normally (check control.drain_requested to know a drain had been asked for). If more steps remain, GraphDrained is raised; a subgraph's drain reaches the parent at its next boundary.
  • request_drain() is thread-safe, so it can be called from a signal handler or another thread. It does not cancel asyncio tasks or kill threads: pair it with a timeout (Part 8) when you need a hard bound.
  • Use a new RunControl for each run: one that has been drained stays drained. control= is accepted by invoke, stream and stream_events(version="v3").
  • It needs a checkpointer to be resumable (08F.11).

10.2 Abandoning a stream, and a node that cancels itself#

When a client disconnects you should stop spending money on its run. Streams from stream_events(..., version="v3") are context managers: leaving the with block, or calling abort(), closes the graph iterator and cancels in-flight nodes and subgraphs. abort() is idempotent.

python
# k02_abort.py: abandoning a v3 stream, and what a node's own CancelledError becomes
import asyncio
import time
import warnings

from typing_extensions import TypedDict

from langgraph.errors import NodeCancelledError
from langgraph.graph import END, START, StateGraph

warnings.filterwarnings("ignore")        # the v3 API prints a beta warning; hide it for a clean demo

log: list[str] = []


class State(TypedDict):
    steps: list[str]


def step(name):
    def node(state: State):
        log.append(name)
        time.sleep(0.05)
        return {"steps": state["steps"] + [name]}
    node.__name__ = name
    return node


b = StateGraph(State)
for n in ("one", "two", "three", "four"):
    b.add_node(step(n))
b.add_edge(START, "one").add_edge("one", "two").add_edge("two", "three").add_edge("three", "four").add_edge("four", END)
graph = b.compile()

# 1. leaving the `with` block aborts the run: later nodes never start
with graph.stream_events({"steps": []}, version="v3") as stream:
    for count, event in enumerate(stream):
        if count == 1:
            break                        # a client disconnected after the first node had finished
time.sleep(0.5)
print("1. nodes that ran after an early exit from the with-block:", log)

# 2. abort() can also be called by hand, and is idempotent
log.clear()
stream = graph.stream_events({"steps": []}, version="v3")
iterator = iter(stream)
next(iterator), next(iterator)           # pull two events: the run advances only as far as you read
stream.abort()
stream.abort()
time.sleep(0.5)
print("2. nodes that ran after abort():", log)


# 3. a CancelledError raised inside a node's own body does not look like a silent success
async def cancels_itself(state: State):
    raise asyncio.CancelledError()


g = StateGraph(State).add_node("n", cancels_itself).add_edge(START, "n").add_edge("n", END).compile()
try:
    asyncio.run(g.ainvoke({"steps": []}))
except BaseException as error:
    print("3.", type(error).__name__, "| is NodeCancelledError:", isinstance(error, NodeCancelledError), "|", error)
Output3 lines
1. nodes that ran after an early exit from the with-block: ['one']
2. nodes that ran after abort(): ['one']
3. NodeCancelledError | is NodeCancelledError: True | Node 'n' raised asyncio.CancelledError

In both cases only one had run: the run advances as far as you read the stream, and abandoning the stream stopped it. The v3 stream API is beta, so check the docs for the current names (08F.14). Line 3 shows a related guard: an asyncio.CancelledError raised from inside a node's own body is converted into NodeCancelledError, so the run reports an error instead of silently succeeding. Cancellation initiated by the framework (for example when a sibling branch fails) is a quiet teardown.

10.3 What is not cancelled#

  • A running node cannot be stopped by a drain. A timeout can stop an async node at its next await, but not blocking synchronous code (8.3).
  • Threads started by asyncio.to_thread or your own executor keep running after the awaiting task is cancelled.
  • External side effects that have been started (a payment request in flight, a model call that is already billed) are not recalled by any of this. Idempotency (7.4) is the only protection.

10.4 Hard backstops#

Limit What it bounds Where
recursion_limit Total super-steps in a run (default 10,007 in 1.2.22; raises GraphRecursionError) 08F.10, Part 11
ModelCallLimitMiddleware and ToolCallLimitMiddleware Model or tool calls in an agent run 08F.8, 7.5
max_concurrency (a config key) Parallel nodes and Send workers at once 08F.10, 7.4
retry_policy.max_attempts Attempts per node 7.2
Node timeout Wall-clock time of one async attempt Part 8
Drain Which super-step the run stops at, on request 10.1

A stuck thread (a run that paused in a state that can no longer be resumed, such as after a renamed node) can be repaired by editing its checkpoint with update_state or by forking from an earlier checkpoint (08F.11 owns time travel).


Part 11: Putting it together: a refund workflow#

One workflow that uses every feature of this lesson, with no model and no network, so you can run it and test it. A customer asks for a refund. The workflow loads the refund limit for the customer's tier (cached, since many cases share a tier), auto-approves small amounts, and for large amounts pauses for a manager whose answer is validated (response_schema). The refund call to a payment gateway has a timeout, retries on connection problems and timeouts, an idempotency key, and an error handler that routes a failed refund to a person instead of failing the run.

flowchart TD
    S(["START"]) --> L["load_policy (cached by tier)"]
    L --> A["assess"]
    A -- "within the limit" --> I
    A -- "above the limit" --> M["ask_manager (interrupt, typed answer)"]
    M -- "approved, amount" --> I["issue_refund (timeout, retry, idempotency key)"]
    M -- "declined" --> C["close"]
    I -- "done" --> C
    I -- "failed for good (error handler)" --> C
    C --> E(["END"])

11.1 The graph (refund_flow.py)#

python
# refund_flow.py: a refund workflow with an approval pause, retries, a timeout, a cache and a compensation path
import asyncio
import operator
from typing import Annotated, Literal

from pydantic import BaseModel, Field
from typing_extensions import TypedDict

from langgraph.cache.memory import InMemoryCache
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import NodeError, NodeTimeoutError
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from langgraph.types import CachePolicy, Command, RetryPolicy, TimeoutPolicy, interrupt

POLICY_LIMITS = {"standard": 100.0, "gold": 500.0}        # stands in for a policy table in a database


class ManagerDecision(BaseModel):
    """What the manager's UI must send back. The schema is validated before the node continues."""
    approved: bool
    amount: float = Field(gt=0, description="Amount to refund in EUR")
    reason: str = ""


class State(TypedDict):
    order_id: str
    tier: str
    requested: float
    limit: float
    approved_amount: float
    status: str
    log: Annotated[list[str], operator.add]


class FakeGateway:
    """A payment API stand-in. `lose_acks`: the first N calls move the money but raise ConnectionError.
    `down`: every call raises before any money moves. `hang`: every call stalls."""

    def __init__(self, lose_acks: int = 0, down: bool = False, hang: bool = False):
        self.lose_acks, self.down, self.hang = lose_acks, down, hang
        self.calls = 0
        self.refunds: dict[str, float] = {}        # idempotency key -> amount that really moved

    async def refund(self, key: str, amount: float) -> None:
        self.calls += 1
        if self.hang:
            await asyncio.sleep(30)
        if self.down:
            raise ConnectionError("gateway unreachable")
        self.refunds.setdefault(key, amount)       # the gateway deduplicates on the key
        if self.calls <= self.lose_acks:
            raise ConnectionError("acknowledgement lost")


class PolicyDb:
    def __init__(self):
        self.lookups = 0

    def limit_for(self, tier: str) -> float:
        self.lookups += 1
        return POLICY_LIMITS.get(tier, 0.0)


def build_graph(gateway: FakeGateway, policy_db: PolicyDb, cache: InMemoryCache | None = None):
    def load_policy(state: State):
        return {"limit": policy_db.limit_for(state["tier"]), "log": [f"policy loaded for tier {state['tier']}"]}

    def assess(state: State) -> Command[Literal["ask_manager", "issue_refund"]]:
        if state["requested"] <= state["limit"]:
            return Command(update={"approved_amount": state["requested"], "log": ["auto-approved"]}, goto="issue_refund")
        return Command(update={"log": ["above the limit: manager needed"]}, goto="ask_manager")

    def ask_manager(state: State) -> Command[Literal["issue_refund", "close"]]:
        # No side effect before the interrupt: this node restarts from its first line on resume.
        decision = interrupt(
            {"question": "Approve this refund?", "order_id": state["order_id"],
             "requested": state["requested"], "limit": state["limit"]},
            response_schema=ManagerDecision,
        )
        if not decision.approved:
            return Command(update={"status": "declined", "log": [f"declined: {decision.reason or 'no reason given'}"]}, goto="close")
        return Command(update={"approved_amount": decision.amount, "log": [f"manager approved {decision.amount:.2f}"]},
                       goto="issue_refund")

    async def issue_refund(state: State, runtime: Runtime):
        key = f"refund:{state['order_id']}"        # derived from durable state, identical on every attempt
        await gateway.refund(key, state["approved_amount"])
        return {"status": "refunded",
                "log": [f"refunded {state['approved_amount']:.2f} (attempt {runtime.execution_info.node_attempt})"]}

    def refund_failed(state: State, error: NodeError) -> Command[Literal["close"]]:
        reason = f"{type(error.error).__name__}: {error.error}"
        return Command(update={"status": "needs_manual_refund", "log": [f"automatic refund failed ({reason})"]}, goto="close")

    def close(state: State):
        return {"log": [f"case closed with status {state['status']}"]}

    builder = StateGraph(State)
    builder.add_node("load_policy", load_policy,
                     cache_policy=CachePolicy(key_func=lambda s: s["tier"], ttl=300))      # keyed on the tier only
    builder.add_node("assess", assess)
    builder.add_node("ask_manager", ask_manager)
    builder.add_node("issue_refund", issue_refund,
                     retry_policy=RetryPolicy(max_attempts=3, initial_interval=0.01, jitter=False,
                                              retry_on=(ConnectionError, NodeTimeoutError)),
                     timeout=TimeoutPolicy(run_timeout=0.2),                                # 30 or more in production
                     error_handler=refund_failed)
    builder.add_node("close", close)
    builder.add_edge(START, "load_policy")
    builder.add_edge("load_policy", "assess")
    builder.add_edge("issue_refund", "close")
    builder.add_edge("close", END)
    return builder.compile(checkpointer=InMemorySaver(), cache=cache or InMemoryCache())


def new_case(order_id: str, tier: str, requested: float) -> State:
    return {"order_id": order_id, "tier": tier, "requested": requested, "limit": 0.0,
            "approved_amount": 0.0, "status": "open", "log": []}

Design notes, matching what you learned:

  • assess and ask_manager route with Command(goto=...), so they have no static outgoing edges and carry Command[Literal[...]] annotations (08F.10, Part 6).
  • ask_manager has no side effect before interrupt(), because it restarts on resume (1.6, 4.4). Its answer is a validated ManagerDecision, so decision.amount is already a positive float.
  • The idempotency key refund:<order_id> comes from state, so it is the same on every attempt (7.4).
  • retry_on=(ConnectionError, NodeTimeoutError) is explicit: a timeout is retried, and nothing else is. The default rule would also retry unknown exceptions, which for a payment call is more than you want.
  • The error handler returns Command(goto="close"), because a dict would end the branch without reaching close (7.5).
  • The timeout is 0.2 seconds so the demo finishes quickly; production values depend on the gateway's latency distribution.
  • The cache key is the tier only (key_func=lambda s: s["tier"]): the policy depends on nothing else, and keying on the whole state would never hit, since the state carries the order id and amount.
  • The graph is compiled with InMemorySaver() and InMemoryCache() so it runs anywhere; both are replaced in production (a database checkpointer, 08F.11, and a shared cache).

11.2 Running five cases (refund_demo.py)#

python
# refund_demo.py: five cases through the refund workflow (run: uv run python refund_demo.py)
import asyncio

from langgraph.cache.memory import InMemoryCache
from langgraph.types import Command

from refund_flow import FakeGateway, PolicyDb, build_graph, new_case


def show(title, result, gateway):
    print(f"\n{title}")
    for line in result["log"]:
        print("   -", line)
    print(f"   status={result['status']} | gateway calls={gateway.calls} | money moved={gateway.refunds}")


async def main():
    db = PolicyDb()
    cache = InMemoryCache()        # shared, so every case after the first of a tier skips the policy lookup

    # 1. small refund: auto-approved, no human involved
    gateway = FakeGateway()
    graph = build_graph(gateway, db, cache)
    config = {"configurable": {"thread_id": "case-1"}}
    show("1. small refund", await graph.ainvoke(new_case("A-1", "standard", 40.0), config), gateway)

    # 2. big refund: the run pauses; the manager approves a smaller amount
    gateway = FakeGateway()
    graph = build_graph(gateway, db, cache)
    config = {"configurable": {"thread_id": "case-2"}}
    paused = await graph.ainvoke(new_case("A-2", "standard", 480.0), config)
    print("\n2. big refund paused; the manager UI receives:", paused["__interrupt__"][0].value)
    result = await graph.ainvoke(Command(resume={"approved": True, "amount": 300.0}), config)
    show("   after the manager approved 300.00", result, gateway)

    # 3. big refund, manager declines
    gateway = FakeGateway()
    graph = build_graph(gateway, db, cache)
    config = {"configurable": {"thread_id": "case-3"}}
    await graph.ainvoke(new_case("A-3", "standard", 480.0), config)
    result = await graph.ainvoke(Command(resume={"approved": False, "amount": 1.0, "reason": "outside the 30-day window"}), config)
    show("3. manager declines", result, gateway)

    # 4. the gateway acknowledges too late twice: retried, and the idempotency key prevents a double refund
    gateway = FakeGateway(lose_acks=2)
    graph = build_graph(gateway, db, cache)
    show("4. lost acknowledgements", await graph.ainvoke(new_case("A-4", "gold", 450.0), {"configurable": {"thread_id": "case-4"}}), gateway)

    # 5. the gateway is down, then hangs: retries run out, the error handler routes to a person
    for title, gateway in [("5a. gateway down", FakeGateway(down=True)), ("5b. gateway hangs", FakeGateway(hang=True))]:
        graph = build_graph(gateway, db, cache)
        show(title, await graph.ainvoke(new_case("A-5", "gold", 450.0), {"configurable": {"thread_id": title}}), gateway)

    print("\npolicy table lookups for 6 cases (two tiers, cached per tier):", db.lookups)


asyncio.run(main())
Output46 lines
1. small refund
   - policy loaded for tier standard
   - auto-approved
   - refunded 40.00 (attempt 1)
   - case closed with status refunded
   status=refunded | gateway calls=1 | money moved={'refund:A-1': 40.0}

2. big refund paused; the manager UI receives: {'question': 'Approve this refund?', 'order_id': 'A-2', 'requested': 480.0, 'limit': 100.0}

   after the manager approved 300.00
   - policy loaded for tier standard
   - above the limit: manager needed
   - manager approved 300.00
   - refunded 300.00 (attempt 1)
   - case closed with status refunded
   status=refunded | gateway calls=1 | money moved={'refund:A-2': 300.0}

3. manager declines
   - policy loaded for tier standard
   - above the limit: manager needed
   - declined: outside the 30-day window
   - case closed with status declined
   status=declined | gateway calls=0 | money moved={}

4. lost acknowledgements
   - policy loaded for tier gold
   - auto-approved
   - refunded 450.00 (attempt 3)
   - case closed with status refunded
   status=refunded | gateway calls=3 | money moved={'refund:A-4': 450.0}

5a. gateway down
   - policy loaded for tier gold
   - auto-approved
   - automatic refund failed (ConnectionError: gateway unreachable)
   - case closed with status needs_manual_refund
   status=needs_manual_refund | gateway calls=3 | money moved={}

5b. gateway hangs
   - policy loaded for tier gold
   - auto-approved
   - automatic refund failed (NodeTimeoutError: Node 'issue_refund' exceeded its run timeout of 0.200s (elapsed: 0.202s).)
   - case closed with status needs_manual_refund
   status=needs_manual_refund | gateway calls=3 | money moved={}

policy table lookups for 6 cases (two tiers, cached per tier): 2

Read the cases in turn:

  1. A 40 EUR refund never reached a person.
  2. A 480 EUR refund paused, and the payload given to the manager's UI had the order, the amount and the limit. The manager approved 300, and the refund went out for the manager's amount, not the requested one.
  3. A decline went straight to close: no gateway call.
  4. The gateway moved the money and then lost its acknowledgement twice. The node was retried until the third attempt succeeded, and the gateway shows one refund of 450 for the key, not three.
  5. With the gateway down, the three attempts failed and the handler routed to needs_manual_refund. With the gateway hanging, each attempt was cut off by the timeout, and the retries and the handler followed in the same way; the message in the log is the NodeTimeoutError text.

The last line shows the cache: six cases over two tiers did two policy lookups.

11.3 Tests that need no model (test_refund_flow.py)#

Everything above is plain Python, so you can test the graph with the gateway and policy table passed in (build_graph takes them as parameters for exactly this reason). The tests assert on the behaviours that matter: no pause for small amounts, a pause with the right facts for large ones, a refused answer that leaves the pause answerable, no double refund after lost acknowledgements, and a clean manual-handling path.

python
# test_refund_flow.py: tests for the refund workflow, no model and no network (run: uv run --with pytest pytest -q)
import asyncio

from langgraph.types import Command

from refund_flow import FakeGateway, PolicyDb, build_graph, new_case


def run(coro):
    return asyncio.run(coro)


def cfg(name):
    return {"configurable": {"thread_id": name}}


def test_small_refund_never_asks_a_human():
    gateway = FakeGateway()
    result = run(build_graph(gateway, PolicyDb()).ainvoke(new_case("T-1", "standard", 40.0), cfg("t1")))
    assert "__interrupt__" not in result
    assert result["status"] == "refunded"


def test_large_refund_pauses_and_the_pause_carries_the_facts():
    graph = build_graph(FakeGateway(), PolicyDb())
    paused = run(graph.ainvoke(new_case("T-2", "standard", 480.0), cfg("t2")))
    payload = paused["__interrupt__"][0].value
    assert payload["requested"] == 480.0 and payload["limit"] == 100.0
    assert graph.get_state(cfg("t2")).next == ("ask_manager",)


def test_invalid_manager_answer_is_refused_and_the_pause_survives():
    graph = build_graph(FakeGateway(), PolicyDb())
    run(graph.ainvoke(new_case("T-3", "standard", 480.0), cfg("t3")))
    try:
        run(graph.ainvoke(Command(resume={"approved": True, "amount": -1}), cfg("t3")))
        raise AssertionError("a negative amount must be refused")
    except Exception as error:
        assert type(error).__name__ == "ValidationError"
    assert graph.get_state(cfg("t3")).next == ("ask_manager",)


def test_lost_acknowledgements_do_not_double_refund():
    gateway = FakeGateway(lose_acks=2)
    result = run(build_graph(gateway, PolicyDb()).ainvoke(new_case("T-4", "gold", 450.0), cfg("t4")))
    assert gateway.calls == 3
    assert gateway.refunds == {"refund:T-4": 450.0}
    assert result["status"] == "refunded"


def test_gateway_down_routes_to_manual_handling():
    gateway = FakeGateway(down=True)
    result = run(build_graph(gateway, PolicyDb()).ainvoke(new_case("T-5", "gold", 450.0), cfg("t5")))
    assert result["status"] == "needs_manual_refund"
    assert gateway.refunds == {}
Output · of uv run pytest -q2 lines
.....                                                                    [100%]
5 passed in 0.16s

11A.5 covers testing graphs further (fake models, in-memory checkpointers, update_state plus breakpoints, evaluation).


Part 12: Legacy names, and where the docs and the packages disagree#

Reference

12.1 Legacy names in old tutorials#

You will see What it is now Evidence
raise NodeInterrupt("why") interrupt("why") Still runs; emits LangGraphDeprecatedSinceV10
Interrupt.interrupt_id Interrupt.id Still runs; deprecation warning
HumanInterruptConfig, ActionRequest, HumanInterrupt from langgraph.prebuilt InterruptOnConfig and HITLRequest from langchain.agents.middleware.human_in_the_loop Per the migration guide; still importable, no warning in 1.2.22
interrupt_before=["tools"] as the approval for an agent interrupt() in the tool, or HumanInTheLoopMiddleware Docs: static interrupts are not recommended for human-in-the-loop
add_node(..., retry=RetryPolicy()), @task(retry=...) retry_policy= Still runs; warning
invoke(..., checkpoint_during=True) durability= (08F.11) Still runs; warning
try/except in every node, to retry or recover retry_policy, error_handler, set_node_defaults (1.2) Part 7
Removed Interrupt fields ns, when, resumable Gone since 0.6; use value and id Release notes
python
# d01_legacy.py: legacy names for interrupts and retries, and what Python says about each
import warnings

from typing_extensions import TypedDict


class State(TypedDict):
    x: int


def show(label, fn):
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        try:
            fn()
            status = "ran"
        except Exception as error:
            status = f"{type(error).__name__}: {str(error)[:90]}"
    first = f"{caught[0].category.__name__}: {str(caught[0].message)[:100]}" if caught else "no warning"
    print(f"{label:38s}| {status}\n{'':38s}| {first}")


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


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


def checkpoint_during():
    from langgraph.checkpoint.memory import InMemorySaver
    from langgraph.graph import END, START, StateGraph
    g = StateGraph(State).add_node("a", lambda s: s).add_edge(START, "a").add_edge("a", END).compile(checkpointer=InMemorySaver())
    g.invoke({"x": 1}, {"configurable": {"thread_id": "1"}}, checkpoint_during=True)


def interrupt_id():
    from langgraph.types import Interrupt
    Interrupt(value="q", id="abc").interrupt_id


def human_interrupt():
    from langgraph.prebuilt.interrupt import HumanInterrupt  # noqa: F401


def prebuilt_config():
    from langgraph.prebuilt.interrupt import HumanInterruptConfig  # noqa: F401


for label, fn in [("NodeInterrupt(...)", node_interrupt), ("add_node(..., retry=RetryPolicy())", retry_kwarg),
                  ("invoke(..., checkpoint_during=True)", checkpoint_during), ("Interrupt.interrupt_id", interrupt_id),
                  ("langgraph.prebuilt HumanInterrupt", human_interrupt),
                  ("langgraph.prebuilt HumanInterruptConfig", prebuilt_config)]:
    show(label, fn)
Output12 lines
NodeInterrupt(...)                    | ran
                                      | LangGraphDeprecatedSinceV10: NodeInterrupt is deprecated. Please use `langgraph.types.interrupt` instead. Deprecated in LangGraph
add_node(..., retry=RetryPolicy())    | ran
                                      | LangGraphDeprecatedSinceV05: `retry` is deprecated and will be removed. Please use `retry_policy` instead. Deprecated in LangGrap
invoke(..., checkpoint_during=True)   | ran
                                      | LangGraphDeprecatedSinceV10: `checkpoint_during` is deprecated and will be removed. Please use `durability` instead. Deprecated i
Interrupt.interrupt_id                | ran
                                      | LangGraphDeprecatedSinceV10: `interrupt_id` is deprecated. Use `id` instead. Deprecated in LangGraph V1.0 to be removed in V2.0.
langgraph.prebuilt HumanInterrupt     | ran
                                      | no warning
langgraph.prebuilt HumanInterruptConfig| ran
                                      | no warning

The four deprecated names still ran and warned; the two langgraph.prebuilt types still import silently, so grep for them yourself when you migrate. 08F.15 collects migration patterns for the packages.

12.2 Where the docs and the packages disagree#

Topic The docs say What this lesson found and teaches
stream_events(version="v3") "The recommended way" to drive a graph that may interrupt The package prints LangChainBetaWarning ... experimental. Teach invoke and stream as the base and v3 as beta
Default retry rule Lists the excluded exceptions ConnectionError is retried first despite OSError; every requests.HTTPError from raise_for_status() is retried (7.2)
Error handler return A dict or a Command A dict ends the branch; use Command(goto=...) to continue (7.5)
interrupt_after with a string One testing page passes interrupt_after="node3" A bare string raises TypeError at compile; pass a list (5.3)
__interrupt__ shape Shown as a tuple in some places A list in the default invoke result in 1.2.22; a tuple in stream chunks (updates) and on GraphOutput.interrupts (08F.14, 6.1). Do not depend on the container type: index it and read .value and .id
Command(resume=None) Not mentioned Raises UnboundLocalError in 1.2.22 (2.3)
Strict resume mode Not documented Exists in source behind an internal key; treat as internal (2.3)
The interrupt id Older docs show reprs with no id Interrupt has value, id and response_schema in 1.2.22

Reference

13.1 A decision in six questions#

  1. Does a person have to decide something mid-run? Use interrupt(), in a node (a hand-written graph), in a tool (approval travels with the tool), or through HumanInTheLoopMiddleware (a create_agent agent). Not static breakpoints.
  2. Can the answer be wrong in shape? Add a response_schema. Validate meaning (does the order exist?) with a conditional-edge loop.
  3. Can a step fail transiently? Give it a RetryPolicy, with an explicit retry_on for anything expensive or not idempotent, and an idempotency key for every side effect.
  4. What if the retries run out? Add an error_handler that returns a Command to a recovery path, or let the run fail if a developer must fix it.
  5. Can a step hang? Make it async, give it a timeout, and give the client its own shorter timeout.
  6. Is a step slow, pure and repeated? Cache it, with a key that holds everything the result depends on.
Symptom Cause Fix
The node never pauses and takes the fallback value A bare except around interrupt() 4.1
Resume raises RuntimeError: Cannot use Command(resume=...) without checkpointer No checkpointer; the first call looked fine Compile with a checkpointer (1.5)
ValueError: Checkpointer requires one or more of the following 'configurable' keys No thread_id Pass config={"configurable": {"thread_id": ...}}
Emails or charges happen twice for one approval Side effect above interrupt() 1.6, 4.4
The reviewer's answer lands on the wrong question Interrupt order changed between pause and resume 4.2
RuntimeError: When there are multiple pending interrupts... One value for several pending interrupts Resume by id (3.5)
UnboundLocalError ... resume_is_map Command(resume=None) Resume with True or a dict (2.3)
A resume on a wrong thread id: the run pauses at the first question again, or returns the old state No validation of the id Check the thread exists first (2.3)
I resumed with {id: answer} and the graph asked the same question again The id matches no pending interrupt (stale, mistyped or from another thread); the map is silently ignored Read the pending id from get_state(config).interrupts before resuming (2.3, 3.5)
After an interrupt_after the app thinks the run finished Static breakpoints have no __interrupt__ Check get_state(config).next (5.3)
TypeError: can only concatenate list (not "str") at compile A bare string as a breakpoint name Pass a list (5.3)
Tool or middleware sees None context after approval context= not passed again 6.2
A bug was retried three times with backoff A custom Exception subclass, or requests.HTTPError Explicit retry_on (7.2)
A customer was charged twice after a timeout No idempotency key, or a key generated inside the node 7.4
The handler ran but the graph stopped A dict-returning handler ends the branch Return Command(goto=...) (7.5)
TypeError: <lambda>() missing 1 required positional argument: 'error' Handler without the NodeError annotation Annotate error: NodeError (7.5)
ValueError: Node timeouts are only supported for async nodes timeout= on a sync node Make it async; offload blocking calls (8.2)
The timeout did not fire Blocking call inside an async def asyncio.to_thread (8.3)
Wrong cached answer for another user key_func omits the user 9.2, 9.3
The cache never hits cache_policy but no cache= on compile(), or the key includes a changing field 9.2
A deploy killed jobs half way No drain handler 10.1

Common misconceptions#

Misconception Reality
"interrupt() waits in memory until the answer arrives." It ends the run; invoke returns. The state is saved and a later call resumes it, possibly in another process (1.1).
"Execution continues from the line after interrupt()." The node restarts from its first line; interrupt() returns the answer the second time. Code above it runs twice (1.6).
"I can use interrupt() without a checkpointer in a demo." The first call works; the resume raises RuntimeError. A pause with no saved state cannot be resumed (1.5).
"try/except Exception makes my node more robust." Around interrupt() it swallows the pause (4.1).
"Answers are matched to questions." They are matched by position in the node. Reordering questions misroutes answers silently (4.2).
"A dict resume value is a map of answers." Only if every key is an interrupt id. Otherwise it is one value (2.3).
"Command(resume=None) means continue." It fails in 1.2.22. Resume with True or a dict (2.3).
"Static breakpoints are how you do approvals." The docs recommend interrupt() for human-in-the-loop; breakpoints are for debugging (Part 5).
"A retry policy retries every error." The default skips probable bugs (ValueError, KeyError, RuntimeError and others) and retries ConnectionError, 5xx httpx errors, every requests.HTTPError (4xx included) and unknown exceptions (7.2).
"max_attempts=3 means three retries." It counts the first attempt: one try and two retries (7.2).
"Retries make my payment node safe." Retries make it at-least-once. Without an idempotency key they cause duplicates (7.4).
"An error handler continues the graph." A dict-returning handler ends the branch; return Command(goto=...) to continue (7.5).
"Timeouts work on any node." Async nodes only, and not on blocking code inside them (Part 8).
"A timeout is never retried." NodeTimeoutError is retried by the default rule (8.2).
"The node cache is like the checkpointer." The cache memoizes results across threads by input; checkpoints are per-thread resume points (9.3).
"A cache hit still runs my node's side effects." It skips the node entirely (9.2).
"Draining a graph stops it immediately." It stops at the next super-step boundary; the running node finishes (10.1).
"context= is saved with the thread." It is not restored on resume; pass it again (6.2).

Key takeaways#

  1. interrupt() is a durable pause. It ends the run, saves the state and returns the question; Command(resume=...) on the same thread continues it, later and anywhere. It needs a checkpointer, a thread id and a serializable payload.
  2. The node restarts on resume. Put interrupt() first, side effects after it or idempotent, and keep the number and order of interrupt calls in a node fixed.
  3. Never catch the pause. No bare except around interrupt(); answers are matched by position; several pending interrupts are answered by id with a resume map.
  4. Validate at the boundary. response_schema (1.2.12 and later) validates and types the answer and leaves the interrupt answerable on bad input; loops with one interrupt per node run handle validation that needs state.
  5. Read pauses everywhere they appear: __interrupt__ in invoke and updates, .interrupts on GraphOutput, and get_state() in another process; static breakpoints appear only in get_state().next.
  6. Use the right pause. Middleware for agent tool calls, interrupt() in a tool or a node for custom flows, a human-as-a-tool for model-chosen questions, static breakpoints for debugging only. Run-time context is not restored on resume.
  7. Failures have owners. Transient errors go to retry_policy, failures that survive retries go to an error_handler, model- and user-fixable errors go back to the model or to interrupt(), bugs fail the run.
  8. Know the default retry rule. It retries ConnectionError, 5xx and unknown exceptions (including your own subclasses and every requests.HTTPError raised by raise_for_status() in this version) and skips probable bugs. Write an explicit retry_on for anything that matters.
  9. Retries are at-least-once. Derive idempotency keys from durable state; a key generated inside the failing node protects nothing. Do not stack retries across layers.
  10. Handlers need a Command to continue. NodeError is injected by annotation; a dict return ends the branch. Defaults come from set_node_defaults and are not inherited by subgraphs.
  11. Timeouts are for async nodes. Run versus idle, heartbeats, and blocking code defeating them; every attempt gets a fresh timer and a timeout is retried by default.
  12. Cache pure, repeated work. Both cache_policy and cache= are required, the key is the node input, and everything the result depends on belongs in the key. A cache hit skips the node.
  13. Stop gracefully. RunControl and GraphDrained stop at super-step boundaries with a saved checkpoint; abort streams to cancel work nobody is waiting for; nothing here recalls a side effect already started.

Terms introduced in this lesson#

Term One-line definition
Human-in-the-loop (HITL) A workflow design in which a person approves, edits or answers at some step before the run continues
interrupt() A function that pauses a graph from inside a node, saves state and surfaces a question; its return value on resume is the answer
Interrupt The object describing one pending pause: value, id and response_schema
Resume Continuing a paused run by calling the graph again on the same thread with Command(resume=...)
Command(resume=...) The input that answers a pending interrupt; a dict of interrupt ids to values answers several
Resume map A dict {interrupt id: answer} that answers one or more pending interrupts
response_schema An interrupt() option (langgraph 1.2.12 and later) that types and validates the resume value
Re-execution rule On resume (and on retry) a node restarts from its first line, so code before interrupt() runs again
Static breakpoint A pause before or after a named node, set with interrupt_before or interrupt_after; meant for debugging
GraphInterrupt The internal exception interrupt() raises to pause a run; a bare except that catches it breaks the pause
RetryPolicy A node option with initial_interval, backoff_factor, max_interval, max_attempts, jitter and retry_on
default_retry_on The default retry predicate: retries ConnectionError, 5xx httpx errors, every requests.HTTPError and any unknown exception; skips probable programming errors and OSError
At-least-once execution The guarantee that a retried node body may run more than once, so side effects need deduplication
Idempotency key A value, the same on every attempt, sent with a side effect so the receiver can ignore repeats
error_handler A function attached to a node that runs only after retries are exhausted and returns an update or a Command
NodeError The injected failure description (node, error) given to an error handler
set_node_defaults A StateGraph method that sets default retry policy, cache policy, error handler and timeout for all nodes
Saga (compensation) A recovery design in which a later failure triggers steps that undo or mark earlier steps
TimeoutPolicy A node timeout with run_timeout (hard cap), idle_timeout (no-progress limit) and refresh_on
NodeTimeoutError The error a timed-out attempt raises; it does not subclass TimeoutError and is retried by default
Heartbeat An explicit runtime.heartbeat() call that resets the idle clock when refresh_on="heartbeat"
CachePolicy A node option with a key_func and a ttl that lets a node's result be reused, given a cache on compile()
Node cache A store (InMemoryCache, SqliteCache, RedisCache) that memoizes node results across runs by input
Drain (RunControl, GraphDrained) A cooperative request to stop a run at the next super-step boundary with a saved checkpoint

Exercises#

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

  1. Approve, reject, or approve with a corrected amount. Build a one-node graph where the reviewer's answer has a decision (approve or reject) and, for approvals, an optional positive amount. Use response_schema. Run the three cases and print the final state. What happens if the reviewer sends {"decision": "maybe"}?
  2. Fix the double email. The node below sends an email and then asks "Send it?". Run it and count the emails for one approval, then fix it so exactly one email is sent.
python
def broken(state):
    emails.append(f"mail to {state['customer']}")
    return {"status": "sent" if interrupt("Send it?") else "skipped"}
  1. Three reviewers, one at a time. Three parallel nodes (legal, finance, security) each interrupt with their own question. Answer them in the order security, legal, finance, printing who is still waiting after each answer.
  2. Predict the retries. For each of KeyError, ConnectionError, TimeoutError, sqlite3.OperationalError, a custom class OutOfStock(Exception) and NodeTimeoutError, say whether the default RetryPolicy retries it. Then check with default_retry_on.
  3. Retry rate limits. Write a retry_on function that also retries httpx.HTTPStatusError with status 429, retries 5xx, and still refuses a 404. Test it on 429, 503 and 404.
  4. A handler that continues. A node book_hotel always raises ConnectionError. Add an error handler that records status="needs_manual_booking" and still reaches a notify node. What goes wrong if the handler returns a plain dict?
  5. A cache key. A banner node depends on the customer's plan and language but not on the customer. Cache it so four customers produce three node runs when two of them share a plan and a language. Show which customers ran.
  6. A while True replay. Count how many times the body of a while True loop that calls interrupt() runs for ten answers (the tenth being "done"), and work out the formula. Rewrite it with a conditional edge.
  7. A drain plan. Your service runs graphs with a Postgres checkpointer. Describe, in six bullet points, what you do on SIGTERM: what you create, what you request, what you catch, what you store and how a new process continues.
  8. Translate an old tutorial. Rewrite this snippet with current names, and say what each changed line was replaced by:
python
from langgraph.errors import NodeInterrupt
from langgraph.prebuilt import HumanInterrupt, HumanInterruptConfig

def check(state):
    if state["amount"] > 100:
        raise NodeInterrupt("Needs approval")
    return state

builder.add_node("charge", charge, retry=RetryPolicy(max_attempts=3))
graph = builder.compile(checkpointer=saver, interrupt_before=["tools"])
Answers and hints
  1. The response_schema is a model with a Literal decision and an optional positive amount. All three cases ran on 14 November 2026. {"decision": "maybe"} raises ValidationError out of the resume call and the interrupt stays answerable (2.4).
python
# ex1_edit_amount.py: reviewer may approve, reject or approve with a corrected amount
from typing import Literal

from pydantic import BaseModel, Field
from typing_extensions import TypedDict

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


class Review(BaseModel):
    decision: Literal["approve", "reject"]
    amount: float | None = Field(default=None, gt=0)       # only meaningful for an approval


class State(TypedDict):
    requested: float
    final_amount: float
    status: str


def review(state: State):
    answer = interrupt({"requested": state["requested"]}, response_schema=Review)
    if answer.decision == "reject":
        return {"status": "rejected", "final_amount": 0.0}
    return {"status": "approved", "final_amount": answer.amount or state["requested"]}   # keep the request unless edited


g = StateGraph(State).add_node(review).add_edge(START, "review").add_edge("review", END).compile(checkpointer=InMemorySaver())
for n, answer in enumerate([{"decision": "approve"}, {"decision": "approve", "amount": 120}, {"decision": "reject"}]):
    config = {"configurable": {"thread_id": str(n)}}
    g.invoke({"requested": 480.0, "final_amount": 0.0, "status": ""}, config)
    print(answer, "->", g.invoke(Command(resume=answer), config))
Output3 lines
{'decision': 'approve'} -> {'requested': 480.0, 'final_amount': 480.0, 'status': 'approved'}
{'decision': 'approve', 'amount': 120} -> {'requested': 480.0, 'final_amount': 120.0, 'status': 'approved'}
{'decision': 'reject'} -> {'requested': 480.0, 'final_amount': 0.0, 'status': 'rejected'}
  1. The broken node sends the email above the interrupt, so one approval sends two. The fix decides first and acts once, after the answer (4.4).
python
# ex2_fix_double.py: move the side effect below the interrupt so it runs once
from typing_extensions import TypedDict

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

emails: list[str] = []


class State(TypedDict):
    customer: str
    status: str


def broken(state: State):
    emails.append(f"mail to {state['customer']}")           # runs on the first pass AND after the resume
    return {"status": "sent" if interrupt("Send it?") else "skipped"}


def fixed(state: State):
    if not interrupt("Send it?"):                            # decide first ...
        return {"status": "skipped"}
    emails.append(f"mail to {state['customer']}")            # ... act once, after the answer
    return {"status": "sent"}


for name, node in [("broken", broken), ("fixed", fixed)]:
    emails.clear()
    g = StateGraph(State).add_node("n", node).add_edge(START, "n").add_edge("n", END).compile(checkpointer=InMemorySaver())
    config = {"configurable": {"thread_id": name}}
    g.invoke({"customer": "Ana", "status": ""}, config)
    result = g.invoke(Command(resume=True), config)
    print(f"{name:7s} -> status={result['status']}, emails sent={len(emails)}")
Output2 lines
broken  -> status=sent, emails sent=2
fixed   -> status=sent, emails sent=1
  1. Collect the pending interrupts, map each question to its id, and resume with a one-entry map each time. After each answer the others are still waiting, and the answered branch keeps its result (3.5).
python
# ex3_resume_order.py: three reviewers answer one at a time, in a different order from the questions
import operator
from typing import Annotated

from typing_extensions import TypedDict

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


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


def reviewer(name: str):
    def node(state: State):
        return {"votes": [f"{name}: {interrupt(f'{name}, do you approve?')}"]}
    node.__name__ = name
    return node


b = StateGraph(State)
for name in ("legal", "finance", "security"):
    b.add_node(reviewer(name))
    b.add_edge(START, name).add_edge(name, END)
g = b.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "t"}}

pending = g.invoke({"votes": []}, config)["__interrupt__"]
id_of = {i.value.split(",")[0]: i.id for i in pending}          # "legal" -> interrupt id
for name in ("security", "legal", "finance"):                   # answer in a different order
    out = g.invoke(Command(resume={id_of[name]: "yes"}), config)
    waiting = sorted(i.value.split(",")[0] for i in out.get("__interrupt__", []))
    print(f"answered {name:9s} -> still waiting: {waiting}")
print("final votes:", sorted(out["votes"]))
Output4 lines
answered security  -> still waiting: ['finance', 'legal']
answered legal     -> still waiting: ['finance']
answered finance   -> still waiting: []
final votes: ['finance: yes', 'legal: yes', 'security: yes']
  1. KeyError: no (a LookupError). ConnectionError: yes (checked first, despite OSError). TimeoutError: no (an OSError). sqlite3.OperationalError: yes (not on the exclusion list). OutOfStock(Exception): yes ("everything else"), which is a reason to write retry_on. NodeTimeoutError: yes. The table in 7.2 shows the real results.
  2. Check the 429 case first and delegate everything else to the default:
python
# ex5_retry_429.py: retry rate limits (HTTP 429) too, but never other 4xx
import httpx

from langgraph.types import default_retry_on


def retry_on(exc: Exception) -> bool:
    if isinstance(exc, httpx.HTTPStatusError) and exc.response.status_code == 429:
        return True
    return default_retry_on(exc)


def status(code: int) -> httpx.HTTPStatusError:
    request = httpx.Request("GET", "https://api.example.com/x")
    return httpx.HTTPStatusError("boom", request=request, response=httpx.Response(code, request=request))


for code in (429, 503, 404):
    print(code, "default:", default_retry_on(status(code)), "| custom:", retry_on(status(code)))
Output3 lines
429 default: False | custom: True
503 default: True | custom: True
404 default: False | custom: False
  1. Give book_hotel a retry policy with retry_on=ConnectionError and an error_handler(state, error: NodeError) that returns Command(update={"status": "needs_manual_booking"}, goto="notify"). A plain dict would save the status but end the branch, so notify would never run (7.5).
  2. Key on plan and language only. The users ana and bo share a key, so bo is served from the cache:
python
# ex7_cache_key.py: a translation node cached by (tier, language) but NOT by user
from typing_extensions import TypedDict

from langgraph.cache.memory import InMemoryCache
from langgraph.graph import END, START, StateGraph
from langgraph.types import CachePolicy

calls = []


class State(TypedDict):
    user: str
    tier: str
    language: str
    banner: str


def build_banner(state: State):
    calls.append(state["user"])
    return {"banner": f"[{state['language']}] Welcome to the {state['tier']} plan"}


b = StateGraph(State)
b.add_node("banner", build_banner, cache_policy=CachePolicy(key_func=lambda s: f"{s['tier']}|{s['language']}", ttl=600))
b.add_edge(START, "banner").add_edge("banner", END)
g = b.compile(cache=InMemoryCache())

for user, tier, language in [("ana", "gold", "de"), ("bo", "gold", "de"), ("cy", "gold", "fr"), ("di", "free", "de")]:
    g.invoke({"user": user, "tier": tier, "language": language, "banner": ""})
print("node body ran for:", calls)
Output1 line
node body ran for: ['ana', 'cy', 'di']
  1. The first call runs the body once; resume number j re-enters it and replays j earlier iterations before the new question, so it takes j + 1 passes, except the last resume (the "done" answer) which takes n passes. For n answers that is 1 + 2 + ... + n plus n, which is n(n+1)/2 + n: 14 for the four answers of 3.4 and 65 for ten. The cost grows with the square of the number of answers. Rewrite it as a one-interrupt node with a conditional edge that loops back (3.3); then each answer costs one node run.
  2. Create a RunControl for each run and pass it as control=. In the SIGTERM handler call request_drain("sigterm") on every active control. Catch GraphDrained around invoke and record the thread id as "to resume". Let running nodes finish (put a timeout on anything that could hang). Exit when all runs have drained. The new process reads the recorded thread ids and calls graph.invoke(None, config) for each, with a fresh RunControl (10.1).
  3. NodeInterrupt becomes interrupt("Needs approval"), whose return value is the answer (so the node can use it); HumanInterrupt and HumanInterruptConfig become HITLRequest and InterruptOnConfig from langchain.agents.middleware.human_in_the_loop (or you drop them and use HumanInTheLoopMiddleware); retry= becomes retry_policy=; and interrupt_before=["tools"] as an approval becomes an interrupt in the tool or the middleware, with static breakpoints kept for debugging (Part 12).

Check yourself#

  1. What does interrupt() do from the caller's point of view, and what must exist for it to work?
  2. A node prints "starting", calls interrupt(), then prints "resumed". How many times does it print "starting" for one pause and one resume, and why?
  3. Name three ways to find out that a run is paused.
  4. Why does except Exception: around interrupt() break the pause, and what are two ways to avoid it?
  5. How are resume values matched to interrupt() calls in one node, and what goes wrong when a deploy reorders them?
  6. Two parallel branches both interrupt. What happens if you resume with a plain value, and what do you do instead?
  7. What does response_schema add, what happens on an invalid answer, and what does not get validated?
  8. Why are static breakpoints not recommended for human-in-the-loop, and when are they the right tool?
  9. What does HumanInTheLoopMiddleware call under the hood, and what are its four decision types?
  10. A graph's retry policy has max_attempts=3. How many times can the node run, and which of ValueError, ConnectionError, a custom Exception subclass and KeyError does the default rule retry?
  11. Why can a retried node double-charge a customer, and how does an idempotency key prevent it? Where must the key come from?
  12. In what order do the retry policy and the error handler act, and why does a dict-returning handler leave the graph stuck?
  13. Why can a node timeout be defeated by a call inside an async def node, and what is the fix?
  14. What two things must be present for a node to be cached, and what is the default cache key?
  15. What does a drain do to a running node, and what does it not do?

Further resources#

Official sources only. The LangGraph documentation is larger and moves faster than this lesson, and it is the reference for every option; where it is more complete, read it. 08F.17 is the closing lesson that says how.


← 08F.11: Persistence, Durable Execution and Memory | Module 08F overview | 08F.13: Subgraphs and Multi-Agent Systems →

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