9  Human in the Loop

Every graph so far ran from START to END on its own, no questions asked. That is what you don’t want when a node is about to do something you can’t take back — delete a record, send a message, spend money. For those moments the graph needs to stop and ask a person first.

It takes little new machinery. Underneath is the checkpointing from Chapter 8: there, a run crashed and invoke(None, …) resumed it from the saved checkpoint; here, a node stops on purpose (with interrupt()), and a person’s answer resumes it (with Command(resume=…)).

interrupt() pauses the graph mid-run and hands a question to a human. Command(resume=…) continues from the saved checkpoint, replaying the paused node until interrupt() returns the human’s answer. A paused graph is nothing more than a saved checkpoint — the durability is the previous chapter’s; only interrupt() and Command are new.

A second later or a day later, a human sends back a decision and the graph resumes. That round-trip is human-in-the-loop (HITL).

9.1 What we’re building

We give the doc-bot a consequential power and then fence it off. The bot plans a destructive maintenance action — deleting the production knowledge base — but it isn’t allowed to just do it. A human_approval node sits in the middle and interrupts to ask a person for sign-off. Answer yes and an execute node performs the deletion; answer no and it cancels. Either way the graph resumes from the pause and finishes.

flowchart LR
    START([START]) --> plan(plan)
    plan --> approval(human_approval)
    approval -.->|interrupt: ask| human{{human}}
    human -.->|Command resume| approval
    approval --> execute(execute) --> END([END])

The solid line is the ordinary flow; the dotted hop out to the human and back is the interrupt/resume round-trip, and it returns to the same node: human_approval is where the graph pauses and, later, continues.

9.2 The state

Three fields, one per step: the caller’s question, the human’s verdict, and the outcome.

from typing import NotRequired, TypedDict


class State(TypedDict):
    question: str                # input, set by the caller
    approved: NotRequired[bool]  # written by human_approval, from the human's answer
    result: NotRequired[str]     # written by execute: what actually happened

approved is the interesting one. Its value comes from outside — a human’s answer, carried in when they resume — and human_approval turns that answer into the boolean the graph acts on.

9.3 Planning the action

The plan node stands in for the bot’s judgment — it decides a destructive action is warranted. No LLM yet; the decision is fixed, the way stand-in logic has been throughout Part I. It has no side effect of its own, so it returns an empty update (Chapter 3).

def plan_node(state: State) -> dict:
    print("[plan] the bot decided to delete the production knowledge base")
    return {}

9.4 The gate: pause for a human

The heart of the chapter is one call. The human_approval node hands interrupt() a payload describing what needs sign-off, and the run stops there.

from langgraph.types import interrupt, Command


def human_approval_node(state: State) -> dict:
    # This line runs EVERY time the node runs — including on resume, when the
    # node replays from the top. It only describes, so repeating it is
    # harmless.
    print("[human_approval] preparing the approval request")

    # interrupt(...) stops the graph right here:
    #   1) the payload is thrown out of the graph, for a human to look at
    #   2) a checkpoint is saved and invoke() returns, carrying __interrupt__
    #   3) on resume, interrupt() RETURNS the value passed to Command(resume=…)
    decision = interrupt(
        {
            "action": "delete the production knowledge base",
            "question": "Confirm? reply 'yes' or 'no'",
        }
    )

    # Not reached on the first pass; runs only after a human resumes.
    print(f"[human_approval] human decided: {decision}")
    return {"approved": decision == "yes"}

So interrupt() is two-faced. On the first pass it does not return: it raises a GraphInterrupt, which throws the run into a pause, and the lines below it never execute. On resume the same call returns, handing you the value the human passed to Command(resume=…). The call splits the node into a “before” that runs on every attempt and an “after” that runs only once a decision is in. Two rules follow from that, and both bite hard.

WarningGotcha: the resume contract

Never catch Exception around interrupt(). GraphInterrupt subclasses Exception, so the reflex try: … except Exception: of anyone who has just written a tool wrapper swallows the pause. The node returns normally, there is no __interrupt__, and the graph runs on into execute as if a decision had been made.

On resume, the node re-runs from the top. Resuming does not drop you back at the line after interrupt(); LangGraph replays the interrupted node from the beginning, up to the interrupt() call, and this time lets it return. Everything above the call executes a second time — you can see it in the output, where [human_approval] preparing the approval request prints twice in every scenario.

That is fine for a print and fatal for a real side effect. Had we deleted the knowledge base before the interrupt(), resuming would delete it again — and would delete it even on no, since the replay reaches that line before the human’s answer is known. So put irreversible work after interrupt() — which is why the deletion here lives in a separate execute node downstream, reached only once the approval has come back.

A flag will not rescue work placed before the pause. if not state["done"]: effect(); state["done"] = True, set before interrupt(), is never committed at the pause. The interrupted node has not returned its update, so the resume replays the node from the top, re-runs effect(), and sets the flag again.

And approval is only about whether the work may run. Moving it past the gate stops unapproved execution and the replay above; it does not make the work safe to repeat after an arbitrary crash. That is where idempotency, which the book has deferred until now, comes due.

Idempotent means that doing an operation twice has the same external effect as doing it once — so a retry after a crash is harmless. A graph does not make a POST idempotent. The usual way to get there is an idempotency key: the caller attaches an identifier to the operation that stays the same across retries, and the party that actually performs the side effect — the payment service, the mail server, the database — uses it to recognise a request it has already handled and return the earlier result instead of acting again. The guarantee lives on that side; a key the receiver ignores is a decoration. Where there is no cooperating receiver, the alternative is an atomic check-and-act on your own store, so the “have I done this?” test and the doing cannot be split by a crash. A genuinely external side effect needs one of the two to be exactly-once, and this chapter’s gate provides neither. The details belong with persistence and failure (Chapter 26, Chapter 21).

Dynamic interrupt() is the tool you reach for here — the node decides, at runtime, to stop and ask. It has a static cousin. Compiling with interrupt_before=["execute"] (or interrupt_after=[…]) tells the runtime to pause at a node’s edge every time, no code inside required. That’s a debugging aid — a breakpoint to inspect state between steps — not a data-driven gate. We use dynamic interrupt() because the pause is part of the bot’s logic.

9.5 Executing the decision

The deletion itself is an ordinary node. It reads approved and acts — the print stands in for the real, irreversible operation — and because it lives downstream of the interrupt, it runs once per run. (A real external action still wants an idempotency key so a crash-and-resume can’t repeat it, but that safeguard is a Part III concern (Chapter 21); here the lesson is the replay.)

def execute_node(state: State) -> dict:
    if state["approved"]:
        print("[execute] approved → deleting the knowledge base")
        return {"result": "knowledge base deleted"}
    print("[execute] rejected → operation cancelled")
    return {"result": "operation cancelled"}

9.6 Wiring and resuming

The wiring is three plain edges — the interrupt lives inside a node, so the graph shape has nothing special about it. The one requirement is the checkpointer. Without it there is nowhere to save the pause for the resume to read back. (Forget it and the failure is a step later than you’d expect — the first invoke still pauses and returns __interrupt__; it is the resume that dies with RuntimeError: Cannot use Command(resume=...) without checkpointer.)

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

builder = StateGraph(State)
builder.add_node("plan", plan_node)
builder.add_node("human_approval", human_approval_node)
builder.add_node("execute", execute_node)

builder.add_edge(START, "plan")
builder.add_edge("plan", "human_approval")
builder.add_edge("human_approval", "execute")
builder.add_edge("execute", END)

# HITL REQUIRES a checkpointer: the pause IS a saved checkpoint, and resume
# reads it back. Without one the first invoke still pauses, but the resume
# fails: "RuntimeError: Cannot use Command(resume=...) without checkpointer".
graph = builder.compile(checkpointer=InMemorySaver())

flowchart TD
    START(["START"]) --> plan("plan") --> approval("human_approval")
    approval -.->|interrupt| human{{"human"}}
    human -.->|Command resume| approval
    approval --> execute("execute") --> END(["END"])

Driving it is two invoke() calls that share one config. The first starts the run and comes back paused; the second resumes it with the human’s answer.

def run_demo(thread_id: str, human_decision: str | None = None) -> None:
    config = {"configurable": {"thread_id": thread_id}}

    if human_decision is None:
        print("\n===== scenario: waiting for a real human at the keyboard =====")
    else:
        print(f"\n===== scenario: the human will answer '{human_decision}' =====")

    # 1) Start the run. It flows until human_approval calls interrupt(), then
    #    pauses. invoke() returns the state so far — plus __interrupt__.
    result = graph.invoke({"question": "Clean up old data"}, config=config)

    # 2) The pause surfaces as __interrupt__: a list of Interrupt objects. Read
    #    .value to see what the graph is asking a human to decide.
1    pending = result["__interrupt__"][0]
    print("[paused] the graph stopped and is asking:")
    print("        ", pending.value)

    # 3) Inspect where it parked. .next is the node it will resume into.
    snapshot = graph.get_state(config)
2    print("[paused] parked at node:", snapshot.next)

    # 4) Get the human's decision. A scripted answer resumes at once; with none,
    #    this is a REAL pause — the run sits on a saved checkpoint and we block on
    #    input() until a person types.
    if human_decision is None:
        decision = input("        your answer ('yes'/'no'): ").strip()
    else:
        decision = human_decision

    # 5) Resume from the interrupt point; the decision becomes the return value
    #    of interrupt() inside the node.
3    final = graph.invoke(Command(resume=decision), config=config)
    print("[done] result:", final["result"])
1
The pause comes back as __interrupt__, a list of Interrupt objects; .value is the payload passed to interrupt(). That is the default result shape. Pass version="v2" to invoke and the same information comes back typed, as GraphOutput(value, interrupts) — out.interrupts — which Chapter 18 picks up; this chapter stays on the default.
2
get_state(config).next shows where it parked: at human_approval, waiting to resume into that node.
3
Command(resume=decision) gets the answer back in. Whatever is in resume becomes the return value of interrupt() when the node replays — on the same thread_id, so the second invoke lands on the checkpoint the first one left behind.

The one branch is where decision comes from. Pass a human_decision and it resumes immediately — that keeps the two scenarios below reproducible. Pass nothing (human_decision=None) and step 4 drops to input(). The graph actually stops and waits for a person at the keyboard. The resume path is identical either way; the graph cannot tell a scripted answer from a typed one.

NoteDeep Dive: more than one gate

Real workflows gate more than one action. Three shapes come up:

  • Serial gates. Two interrupt() calls in different nodes, one after the other. Each pauses and resumes on its own Command(resume=…), carrying only its decision. You don’t re-supply the earlier answer; the checkpoint already remembers it, so the second resume picks up with the first decision intact.
  • Several interrupts in one node. Call interrupt() twice in the same node and each replay advances past the ones already answered. LangGraph matches answers to interrupt() calls by their order in the node, so an earlier answer isn’t asked again, which also means the calls must happen in the same order on every replay: don’t reorder them, and don’t put one behind an if that an earlier answer can change.
  • Parallel gates. If two branches interrupt in the same superstep, a single invoke() returns both pending interrupts in the __interrupt__ list at once. You then resume with Command(resume=…) carrying a mapping keyed by each interrupt’s id — a bare value is refused while more than one interrupt is pending (RuntimeError: When there are multiple pending interrupts, you must specify the interrupt id when resuming). You can answer them all in one Command, or answer a subset and leave the rest pending for a later resume — natural when different people sign off on different gates.

Each resume adds one decision; the checkpoint already holds the rest.

9.7 Running it

main runs the two scripted scenarios on two threads — one answers yes, one answers no — then a third thread with no scripted answer that waits for a real person.

import sys  # stdlib: we only need it to ask "is stdin a terminal?"

if __name__ == "__main__":
    # Two scripted threads make the yes/no split reproducible.
    run_demo(thread_id="approve-case", human_decision="yes")
    run_demo(thread_id="reject-case", human_decision="no")

    # A third thread with no scripted answer: the graph really stops and waits
    # for you to type. Guarded by isatty() so a piped/CI run skips the prompt.
    if sys.stdin.isatty():
        run_demo(thread_id="interactive-case")
    else:
        print("\n(skipping interactive scenario: stdin is not a terminal)")

===== scenario: the human will answer 'yes' =====
[plan] the bot decided to delete the production knowledge base
[human_approval] preparing the approval request
[paused] the graph stopped and is asking:
         {'action': 'delete the production knowledge base', 'question': "Confirm? reply 'yes' or 'no'"}
[paused] parked at node: ('human_approval',)
[human_approval] preparing the approval request
[human_approval] human decided: yes
[execute] approved → deleting the knowledge base
[done] result: knowledge base deleted

===== scenario: the human will answer 'no' =====
[plan] the bot decided to delete the production knowledge base
[human_approval] preparing the approval request
[paused] the graph stopped and is asking:
         {'action': 'delete the production knowledge base', 'question': "Confirm? reply 'yes' or 'no'"}
[paused] parked at node: ('human_approval',)
[human_approval] preparing the approval request
[human_approval] human decided: no
[execute] rejected → operation cancelled
[done] result: operation cancelled

(skipping interactive scenario: stdin is not a terminal)

The replay the Gotcha warned about is right there in the transcript. [human_approval] preparing the approval request prints twice in each scenario, while [plan] prints once: a completed upstream node isn’t replayed. From the identical pause point the two threads diverge on the human’s one word: yes deletes, no cancels. The decision came from outside the graph, and the graph never noticed the gap.

9.8 Stopping for a real person

Scripting the answer keeps that transcript reproducible, but it also hides the point: with human_decision hard-coded, the “pause” is just two invoke() calls back to back. Drop the script — run_demo with no decision — and the gate does what a gate is for. It blocks on input() until a person actually types:

===== scenario: waiting for a real human at the keyboard =====
[plan] the bot decided to delete the production knowledge base
[human_approval] preparing the approval request
[paused] the graph stopped and is asking:
         {'action': 'delete the production knowledge base', 'question': "Confirm? reply 'yes' or 'no'"}
[paused] parked at node: ('human_approval',)
        your answer ('yes'/'no'): yes
[human_approval] preparing the approval request
[human_approval] human decided: yes
[execute] approved → deleting the knowledge base
[done] result: knowledge base deleted

While that prompt waits, the run is a saved checkpoint parked on human_approval, the same pause as Chapter 8’s crash, held open by a person instead.

With a checkpointer that outlives the process (Chapter 26), a different process can pick that pause up: build the same graph, call graph.invoke(Command(resume=decision), config) on the same thread_id, and it continues from this interrupt.

With this file as written that cannot work. Kill the process at the prompt, restart on the same thread_id, and nothing resumes, because InMemorySaver died with the process. The other way to get it wrong is to restart by calling invoke with the input again, which starts a second run on the thread with a new interrupt id rather than continuing the first. The restart has to resume, with Command(resume=…) or invoke(None, config) to re-enter the pause, against a durable saver.

The sys.stdin.isatty() guard is for automated runs, piped stdin or CI, which skip the blocking prompt instead of hanging on it; that is the skipping interactive scenario line you saw a moment ago.

input() is only the simplest answer channel. interrupt() throws its payload out of the graph, so you can route it anywhere a decision gets made (a Jira ticket, a pull-request review, a Slack button) and, when the answer comes back, call graph.invoke(Command(resume=decision), config) on the same thread_id from whatever process received it: a webhook, a poller, a cron job, seconds or days later. The answer need not come from a human either: a policy check or a more capable model can supply the resume value, and the graph pauses the same way whoever answers. Swap input() for your approval system; the rest of the graph stays as it is.

One thing does change outside it. Command(resume=…) carries no identity, so whoever can reach that thread_id is the approver — and in a real deployment the id travels through a Slack payload or a webhook URL. Authenticate the channel that carries the answer back the way you would authenticate the action itself; a gate anyone can open is decoration.

TipTry it: move the side effect before the interrupt

Move the deletion before the interrupt: add a print("[human_approval] DELETING now") line above the interrupt() call and re-run. It fires on the first pass and again on resume — the deletion you were trying to gate now happens twice, and it happens in the no scenario too, before the human ever answered.

Then delete that line and confirm execute still runs once.

9.9 The same shape elsewhere

“On resume the node re-runs from the top” is not a LangGraph quirk. It is at-least-once delivery, the contract an SQS standard queue gives its consumers, and it comes with the same remedy: make the side effect idempotent, or move it past the point of no return. If you have ever put an idempotency key on a payment handler, you have solved this chapter’s hardest problem in another building.

The causes differ, and the difference is worth keeping straight. A queue redelivers because an acknowledgement was lost. A node re-runs because Python cannot freeze a half-finished function and thaw it later — there is no continuation to restore, so the runtime restarts the call and lets it reach interrupt() again. Different mechanism, identical discipline.

9.10 What we learned

  • interrupt() pauses the graph and hands control to a human. It stops the run inside a node, saves a checkpoint, and surfaces as __interrupt__, a list of Interrupt objects whose .value holds the payload you raised.
  • Command(resume=value) continues from the saved pause, on the same thread_id. Script it with Command(resume="yes") in a test or read the answer from input() to wait on a person; the graph resumes identically.
  • A checkpointer is mandatory. Without compile(checkpointer=…) the first invoke still pauses, but the resume fails with RuntimeError: Cannot use Command(resume=...) without checkpointer.
  • On resume the node re-runs from the top. Put irreversible work after interrupt(), or in a later node, so the replay cannot run it twice. That settles the replay, not every repeat: an external side effect still needs its own idempotency key to survive a crash (the note earlier in this chapter).
  • The gate has a name in LangChain 1.x. For agents built with create_agent (Chapter 13) it ships as HumanInTheLoopMiddleware — the name to recognize; the mechanism is what this chapter built by hand.

The graph can now stop for a person and pick up right where it left off. So far, though, only one node has run at a time. In the next chapter we let several run at once — a fan-out — and discover that when parallel branches all write to the same field, they collide. Reducers are how we teach the state to merge those concurrent updates instead of clobbering them.

New pieces in this chapter

Piece Usage
Type
Command From langgraph.types; passed as invoke’s input, resume= carries the decision back in. graph.invoke(Command(resume=decision), config=config); the value becomes interrupt()’s return — same thread_id
Value
__interrupt__ Result key in the returned state holding the pending Interrupt objects while the run is paused. result["__interrupt__"][0].value; it’s a list — parallel gates can surface several at once
API
interrupt() From langgraph.types; pauses the run inside a node and throws a payload out for a human. decision = interrupt({"action": …, "question": …}); on resume the node replays from the top — put side effects after it

Code in this chapter

File What it runs
code/ch07_human_in_the_loop.py interrupt() parks the graph before the irreversible step; Command(resume=...) restarts the node with the human’s answer.

Challenge

🥉 Bronze — resume with a decision, not just a word

Have the human resume with a structured decision, {"approved": True, "scope": "only stale entries"}, and let execute act on the narrowed scope instead of a blanket yes/no. Have human_approval fold the structured decision into state, and execute read the narrowed scope from there.

Whatever you pass to resume becomes the return value of interrupt(), and it can be any serializable value. The same goes for the payload you hand to interrupt(): both are written into the checkpoint, so keep both to plain JSON-style data.

office hours Worked solution with tests: code/answers/ch07_rich_resume.py.

🥈 Silver — two gates in a row

Build the Deep Dive’s serial gates: one node interrupts to approve the plan, and a later node interrupts to approve the execution.

Drive it on one thread with two separate Command(resume=…) calls, never re-supplying the first answer.

Verify each resume advances one gate. Bonus: route so that rejecting the plan skips the second gate entirely.

office hours Worked solution with tests: code/answers/ch07_serial_gates.py.