Pausing with interrupt() and resuming with Command

Topic 1 of 4 in Human-in-the-loop22 min readIntermediateFree course

Overview

Until now, most of our LangGraph applications have followed an autonomous execution model: provide an input, execute the appropriate nodes, update state, and return a result.

However, production agents frequently encounter situations where continuing without human involvement is inappropriate.

Consider an AI-powered personal assistant that can:

  • Draft and send emails to customers.
  • Approve financial transactions.
  • Modify records in a production database.
  • Publish content on behalf of an organization.
  • Request missing information from a user.

An agent might be capable of performing these operations, but capability does not automatically imply permission.

Human-in-the-loop (HITL) is an architectural approach that introduces human participation into an otherwise automated workflow. Humans can authorize actions, supply missing information, correct generated content, or resolve uncertainty.

In LangGraph, the fundamental mechanism for implementing this interaction is interrupt().

Instead of forcing the agent to complete its entire workflow in one invocation, interrupts allow execution to be divided into multiple invocations separated by human decisions.

In the previous lesson, you built a personal assistant that remembers information across interactions. That project introduced the persistence concepts that make resumable execution possible.

Here, we extend persistence beyond remembering information. The graph must also remember its execution progress and which decision it is waiting for.

The execution lifecycle

The following diagram illustrates the lifecycle of a human-assisted graph.

Overview diagram: START to Prepare action; Prepare action to Call interrupt; Call interrupt to Checkpoint; Call interrupt to Human review; Human review to Resume command; Checkpoint to Replay node; Resume command to Replay node; Replay node to Continue workflow; Continue workflow to END.

Notice that human interaction happens outside the graph invocation.

The graph pauses, returns control to the application, and preserves the information required to continue later. The application might display an approval dialog, create a review task, or notify an authorized employee.

The reviewer could respond immediately or several days later.

Unlike Python’s input() function, an interrupt does not require a terminal or keep a worker occupied while someone considers a decision.

This distinction is essential when building distributed, web-based AI applications.

Pausing execution with interrupt()

Environment setup

Install LangGraph 1.x:

Terminal
pip install -U "langgraph>=1.0,<2"

All core examples in this lesson use deterministic Python functions rather than an LLM. This makes execution behavior easier to observe and requires no model API key.

The APIs have been checked against the current LangGraph documentation. The example outputs describe expected behavior; the examples have not been executed in the lesson-authoring environment.

The interrupt function

Import the function from langgraph.types:

Python
from langgraph.types import interrupt

Conceptually, its interface is simple:

Python
response = interrupt(payload)

The payload describes what the external application needs to know. The response represents the information supplied when execution resumes.

On the first execution, the assignment does not complete. LangGraph suspends the task and exposes the payload to the caller.

On resumed execution, the interrupt receives the supplied response and the assignment completes.

Three elements are required for a resumable human interaction:

  1. A node containing an interrupt() call.
  2. A graph compiled with a checkpointer.
  3. A configuration containing a persistent thread ID.

The checkpointer maintains execution information, while the thread ID identifies which workflow instance should be continued.

Your first interrupt

The following complete example asks a human reviewer for feedback on a generated email draft.

Python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt

class State(TypedDict, total=False):
    draft: str
    feedback: str

def prepare_draft(state: State) -> dict:
    return {
        "draft": "Thank you for contacting our support team."
    }

def collect_feedback(state: State) -> dict:
    feedback = interrupt({
        "type": "feedback_request",
        "draft": state["draft"],
        "question": "What should we improve?"
    })

    return {"feedback": feedback}

builder = StateGraph(State)
builder.add_node("prepare", prepare_draft)
builder.add_node("feedback", collect_feedback)

builder.add_edge(START, "prepare")
builder.add_edge("prepare", "feedback")
builder.add_edge("feedback", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "feedback-001"}
}

result = graph.invoke({}, config)

pending = result["__interrupt__"][0]

print("Interrupt ID:", pending.id)
print("Payload:", pending.value)
print("Feedback collected:", "feedback" in result)

Expected output, excluding the generated interrupt ID:

Text
Payload: {'type': 'feedback_request',
          'draft': 'Thank you for contacting our support team.',
          'question': 'What should we improve?'}
Feedback collected: False

The prepare node has completed successfully, but the feedback node has not finished.

The returned Interrupt object contains two particularly useful attributes:

  • id: An identifier used to associate a response with the pending interrupt.
  • value: The original payload supplied to interrupt().

The __interrupt__ entry is runtime-generated metadata. You do not need to declare it in your graph state schema.

These examples use the default dictionary-returning invoke() interface. When explicitly using version="v2", the corresponding GraphOutput exposes interrupts through .interrupts and state through .value.

Designing interrupt payloads

An interrupt payload acts as a communication contract between the graph and the surrounding application.

A string is sufficient for a demonstration, but structured dictionaries are generally more useful in production.

For example:

Python
payload = {
    "type": "payment_approval",
    "schema_version": 1,
    "request_id": "PAY-1024",
    "amount": 750,
    "currency": "USD",
    "question": "Authorize this payment?",
    "expected_response": "boolean"
}

A frontend can use these fields to choose an appropriate form or approval interface.

The expected_response field is application metadata; it does not automatically enforce validation.

Avoid putting database connections, functions, model instances, or other complex runtime objects in interrupt payloads. Use data that can be represented reliably as JSON.

Resuming execution with Command

An interrupt is only half of the interaction. The other half is returning the human’s response to the graph.

LangGraph provides Command for this purpose:

Python
from langgraph.types import Command

result = graph.invoke(
    Command(resume="Make the email more friendly."),
    config
)

The value supplied to resume becomes the result of the interrupted expression.

The same thread ID identifies the existing workflow, allowing LangGraph to restore its execution information.

A complete approval workflow

The following example simulates an email agent that prepares a draft, waits for authorization, and proceeds only after approval.

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

class State(TypedDict, total=False):
    recipient: str
    draft: str
    approved: bool
    status: str

def prepare(state: State) -> dict:
    print("Preparing email")

    return {
        "draft": "Your order has been shipped."
    }

def review(state: State) -> dict:
    print("Entering review node")

    decision = interrupt({
        "type": "email_approval",
        "recipient": state["recipient"],
        "draft": state["draft"]
    })

    if type(decision) is not bool:
        raise ValueError("Approval must be a boolean.")

    return {"approved": decision}

def deliver(state: State) -> dict:
    if state.get("approved") is not True:
        return {"status": "cancelled"}

    print("Simulated email delivery")
    return {"status": "sent"}

builder = StateGraph(State)
builder.add_node("prepare", prepare)
builder.add_node("review", review)
builder.add_node("deliver", deliver)

builder.add_edge(START, "prepare")
builder.add_edge("prepare", "review")
builder.add_edge("review", "deliver")
builder.add_edge("deliver", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "email-001"}
}

paused = graph.invoke({
    "recipient": "customer@example.com"
}, config)

print("Waiting:", paused["__interrupt__"][0].value)

snapshot = graph.get_state(config)
print("Pending nodes:", snapshot.next)

result = graph.invoke(Command(resume=True), config)

print("Final status:", result["status"])
print("Remaining nodes:", graph.get_state(config).next)

Expected output:

Text
Preparing email
Entering review node
Waiting: {'type': 'email_approval',
          'recipient': 'customer@example.com',
          'draft': 'Your order has been shipped.'}
Pending nodes: ('review',)
Entering review node
Simulated email delivery
Final status: sent
Remaining nodes: ()

Notice that Entering review node appears twice, while Preparing email appears only once.

This is a crucial property of resumable LangGraph execution.

What happens internally?

LangGraph preserves the workflow’s logical position, not Python’s original call stack.

When the first invocation encounters the interrupt, a special control-flow exception communicates the suspension to the runtime.

The runtime records the workflow state and pending execution information through the checkpointer.

When the application submits a resume command:

  1. LangGraph retrieves the checkpoint associated with the thread.
  2. It associates the supplied answer with the pending interrupt.
  3. It executes the interrupted node again from its beginning.
  4. The previously interrupted expression receives the stored answer.
  5. Execution proceeds through the remaining node logic and downstream graph.

This replay-based design allows an interrupted workflow to continue even when the original Python process no longer exists, provided a suitable persistent checkpointer was used.

Note: Resuming exactly where a workflow left off means restoring its logical execution progress. It does not mean restoring the original Python stack frame or skipping every statement before interrupt().

Inspecting paused execution

The following methods are particularly useful when developing HITL applications.

API Purpose
graph.invoke(inputs, config) Submit graph input and execute
graph.invoke(Command(resume=value), config) Answer a dynamic interrupt
graph.get_state(config) Inspect the latest checkpoint
snapshot.values Read checkpointed state
snapshot.next Inspect scheduled nodes
snapshot.interrupts Inspect pending interrupts in the latest state
graph.get_state_history(config) Examine checkpoint history

Use ordinary input dictionaries to submit new graph inputs. Use Command(resume=...) to answer an existing interrupt.

Do not substitute Command(update=...) for a human response. Updating state and supplying an interrupt’s return value are different operations.

The rules of interrupts

Replay-based execution introduces several important constraints. Ignoring them can cause duplicated operations, incorrect decisions, or unexpected workflow behavior.

Rule 1: Keep operations before interrupts replay-safe

Consider this unsafe implementation:

Python
def unsafe_review(state):
    charge_customer(state["amount"])
    approved = interrupt("Approve this transaction?")
    return {"approved": approved}

This implementation has two problems.

First, the financial operation occurs before authorization. Second, resuming the node may execute the charge again.

A better architecture separates preparation, authorization, and execution.

The following diagram shows the recommended separation.

The rules of interrupts diagram: START to Prepare transaction; Prepare transaction to Request approval; Request approval to Approved?; Approved? to Execute transaction (Yes); Approved? to Cancel transaction (No); Execute transaction to END; Cancel transaction to END.

Perform expensive model calls and data preparation in earlier nodes, then persist their results in graph state.

Place the interrupt in a dedicated review node.

Execute external side effects only after authorization has been obtained.

Even downstream operations should use idempotency keys where possible, because crashes and retries can also cause repeated execution.

Rule 2: Do not swallow the interrupt exception

Avoid broad exception handling around an interrupt:

Python
def unsafe_node(state):
    try:
        answer = interrupt("Continue?")
    except Exception:
        return {"approved": False}

    return {"approved": answer}

The exception is part of LangGraph’s execution control mechanism. Catching and consuming it can prevent the runtime from processing the pause correctly.

Keep interrupt calls outside broad try/except blocks. Catch specific application exceptions around operations that genuinely require error handling.

Rule 3: Preserve interrupt order

A node can ask more than one question.

LangGraph tracks the answers for that particular task and reuses them during replay. Interrupts that have already received answers must be encountered in a consistent order.

The following runnable example collects a user’s name and then their department.

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

class State(TypedDict, total=False):
    name: str
    department: str

def collect_details(state: State) -> dict:
    print("Entering collection node")

    name = interrupt("Enter your name.")
    department = interrupt("Enter your department.")

    return {
        "name": name,
        "department": department
    }

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

config = {
    "configurable": {"thread_id": "onboarding-001"}
}

first = graph.invoke({}, config)
print(first["__interrupt__"][0].value)

second = graph.invoke(Command(resume="Alex"), config)
print(second["__interrupt__"][0].value)

final = graph.invoke(Command(resume="Engineering"), config)
print(final)

Expected output:

Text
Entering collection node
Enter your name.
Entering collection node
Enter your department.
Entering collection node
{'name': 'Alex', 'department': 'Engineering'}

The node executes three times. During the final execution, both interrupt expressions receive their corresponding answers.

Do not reorder or conditionally skip previously encountered interrupts based on random values, changing database contents, or the current time.

Conditional interrupts are valid, but the condition must remain consistent across replay. For example, an approval threshold based on checkpointed expense data is usually safe.

Rule 4: Validate human input

Human-provided responses are external inputs and must be treated accordingly.

For example, "false" is a nonempty Python string and is therefore truthy. Using bool("false") would incorrectly authorize an operation.

A payment approval expecting a boolean should validate that it actually receives a boolean.

For richer feedback, validate required fields, allowed values, and size limits. Also verify reviewer permissions outside the graph before accepting the resume request.

Newer LangGraph 1.x releases, starting with 1.2.12, additionally support the response_schema argument to interrupt() for typed response validation.

Rule 5: Do not rely on local variables for persistence

A local Python variable exists only during a particular execution of a node.

If a node generates a random identifier or calls an LLM before interrupting, replay can produce a different value.

Generate important identifiers and outputs in an earlier node and return them into graph state before entering the review node.

The reviewed content must match the content that is eventually executed.

Multiple pending interrupts

Sequential interrupts within one node are different from simultaneous interrupts across parallel graph branches.

Imagine a procurement workflow requiring both finance and security approval. Neither review needs to wait for the other.

LangGraph can expose multiple pending interrupts from the same execution step.

Scenario Resume strategy
One pending interrupt Supply a single resume value
Sequential interrupts Answer each new interrupt as it appears
Multiple parallel interrupts Map interrupt IDs to response values
Static breakpoint Resume using None

Resuming parallel approvals

The following example runs two independent review nodes in parallel and waits for both decisions before determining the final outcome.

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

class State(TypedDict, total=False):
    purchase: str
    finance_approved: bool
    security_approved: bool
    status: str

def finance_review(state: State) -> dict:
    answer = interrupt({
        "department": "finance",
        "purchase": state["purchase"]
    })

    return {"finance_approved": answer is True}

def security_review(state: State) -> dict:
    answer = interrupt({
        "department": "security",
        "purchase": state["purchase"]
    })

    return {"security_approved": answer is True}

def finalize(state: State) -> dict:
    approved = (
        state["finance_approved"]
        and state["security_approved"]
    )

    return {
        "status": "approved" if approved else "rejected"
    }

builder = StateGraph(State)
builder.add_node("finance", finance_review)
builder.add_node("security", security_review)
builder.add_node("finalize", finalize)

builder.add_edge(START, "finance")
builder.add_edge(START, "security")

builder.add_edge(["finance", "security"], "finalize")
builder.add_edge("finalize", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "purchase-001"}
}

paused = graph.invoke({
    "purchase": "Cloud monitoring platform"
}, config)

pending = paused["__interrupt__"]

decisions = {
    "finance": True,
    "security": False
}

responses = {
    item.id: decisions[item.value["department"]]
    for item in pending
}

print("Pending reviews:", len(pending))

result = graph.invoke(
    Command(resume=responses),
    config
)

print("Finance:", result["finance_approved"])
print("Security:", result["security_approved"])
print("Final status:", result["status"])

Expected output:

Text
Pending reviews: 2
Finance: True
Security: False
Final status: rejected

The list-based edge into finalize creates a synchronization point. Both review nodes must finish before finalization begins.

Each parallel node writes to a different state field, avoiding concurrent writes to the same unreduced field.

If both nodes needed to append to a shared list, that field would require an appropriate reducer.

Never associate parallel responses by their position in the returned interrupt collection. Associate them with their IDs and business meaning instead.

The application can also answer selected pending interrupts and leave others awaiting responses.

Static breakpoints for debugging

Dynamic interrupts represent application decisions. Static breakpoints serve a different purpose: inspecting execution at predetermined node boundaries.

Configure them when compiling the graph:

Python
graph = builder.compile(
    checkpointer=InMemorySaver(),
    interrupt_before=["validate"],
    interrupt_after=["calculate"]
)

A breakpoint does not ask a business question or require a human response value.

Debugging a graph step by step

This complete example pauses before calculation and after calculation, allowing inspection of intermediate state.

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

class State(TypedDict, total=False):
    amount: float
    total: float
    status: str

def calculate(state: State) -> dict:
    print("Calculating total")

    return {
        "total": round(state["amount"] * 1.18, 2)
    }

def validate(state: State) -> dict:
    print("Validating total")

    return {"status": "validated"}

builder = StateGraph(State)
builder.add_node("calculate", calculate)
builder.add_node("validate", validate)

builder.add_edge(START, "calculate")
builder.add_edge("calculate", "validate")
builder.add_edge("validate", END)

graph = builder.compile(
    checkpointer=InMemorySaver(),
    interrupt_before=["calculate"],
    interrupt_after=["calculate"]
)

config = {
    "configurable": {"thread_id": "debug-001"}
}

graph.invoke({"amount": 100}, config)
print("Before calculation:", graph.get_state(config).values)

graph.invoke(None, config)
print("After calculation:", graph.get_state(config).values)

final = graph.invoke(None, config)
print("Final:", final)

Expected output:

Text
Before calculation: {'amount': 100}
Calculating total
After calculation: {'amount': 100, 'total': 118.0}
Validating total
Final: {'amount': 100, 'total': 118.0, 'status': 'validated'}

Notice that static breakpoints resume with:

Python
graph.invoke(None, config)

This is different from supplying an answer through Command(resume=...).

Dynamic interrupts versus static breakpoints

Feature Dynamic interrupt Static breakpoint
Configuration Inside node logic Compilation or invocation
Trigger Application logic Node boundary
Custom payload Supported Not a business-response mechanism
Resume method Command(resume=value) invoke(None, config)
Primary purpose Human interaction Debugging
Conditional behavior Based on application data Based on configured nodes

LangSmith Studio also provides visual debugging tools for examining graph execution and state.

Production considerations

Durable checkpoint storage

InMemorySaver is convenient for demonstrations but loses data when the process terminates.

For local applications requiring persistence across restarts, install the SQLite checkpoint integration:

Terminal
pip install -U langgraph-checkpoint-sqlite

For production deployments, PostgreSQL is generally more appropriate:

Terminal
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"

Use PostgresSaver or AsyncPostgresSaver, initialize the checkpoint tables using .setup() or await .setup(), respectively, and manage connection lifetimes correctly.

For important checkpoints, consider durability="sync" to prioritize persistence before subsequent execution steps.

Tip: A checkpointer preserves workflow execution, whereas a store provides longer-lived application memory. An InMemoryStore does not replace a checkpointer for interrupt-based execution.

Integrating interrupts into a web application

A typical REST-based application exposes two operations:

  • A start endpoint that submits graph input and returns pending review requests.
  • A resume endpoint that authenticates the reviewer and submits their decision.

Persist the relationship between the business request, workflow thread, interrupt ID, and authorized reviewer.

A thread ID identifies execution state; it is not an authentication credential.

Additionally, implement review expiration, duplicate-response protection, concurrency control, and audit logging. LangGraph does not automatically decide when an unanswered business request should expire.

Testing and operational reliability

Test more than the successful approval path:

  • Rejection must prevent protected operations.
  • Invalid responses must never authorize execution.
  • Replaying an interrupted node must not duplicate external actions.
  • Separate threads must maintain independent execution state.
  • Parallel approvals must reach their correct destinations.
  • Pending workflows must remain resumable after a process restart when using durable storage.

When evolving graph code, consider existing paused workflows. Changing interrupt order, removing nodes, or introducing incompatible state schemas can disrupt their continuation.

The official LangGraph interrupts documentation, interrupt API reference, and invoke API reference provide version-specific implementation details.

Connecting to the next lesson

This lesson establishes the execution mechanism underlying human-assisted agents: checkpointed suspension, external decision collection, and replay-based continuation.

The next lesson, Approve, edit and reject patterns, builds on this mechanism by introducing structured decisions, controlled state modifications, and explicit routing based on reviewer feedback.

Later in this chapter, we will apply these patterns to tool-call reviews and escalation mechanisms before building an email drafting agent that requires human authorization before sending.

The architectural goal is to retain the productivity of autonomous agents while keeping consequential decisions under appropriate human control.

Exercise

Build an Expense Approval Workflow

Build a LangGraph workflow that automatically processes expense claims of $100 or less and pauses larger claims for human approval. Use interrupt() to present the expense details and Command to resume execution with the reviewer's decision. Ensure that rejected expenses are never processed and that each expense uses an independent thread.

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

class ExpenseState(TypedDict, total=False):
    expense_id: str
    amount: float
    description: str
    approved: bool
    status: str

def review_expense(state: ExpenseState) -> dict:
    # TODO: Automatically approve expenses of $100 or less.
    # TODO: Interrupt for larger expenses.
    # TODO: Return the approval decision.
    raise NotImplementedError

def process_expense(state: ExpenseState) -> dict:
    # TODO: Process only approved expenses.
    # TODO: Return the final status.
    raise NotImplementedError

builder = StateGraph(ExpenseState)

# TODO: Register nodes and connect edges.
# TODO: Compile with a checkpointer.

config = {
    "configurable": {"thread_id": "expense-001"}
}

expense = {
    "expense_id": "EXP-001",
    "amount": 250.0,
    "description": "Conference registration"
}

# TODO: Invoke the graph and inspect the interrupt.
# TODO: Resume with Command(resume=True).
# TODO: Test rejection using a different thread.
# TODO: Test automatic approval for a small expense.

Summary

  • Human-in-the-loop workflows allow agents to obtain external decisions before continuing sensitive or uncertain operations.
  • The interrupt() function pauses graph execution and exposes a JSON-serializable payload to the application.
  • Resumable interrupts require a checkpointer and a consistent thread ID across invocations.
  • Command(resume=value) supplies the value returned by interrupt() when the interrupted node executes again.
  • Interrupted nodes restart from their beginning, so operations preceding interrupts must be replay-safe.
  • Multiple pending interrupts can be resumed by mapping interrupt IDs to their corresponding response values.
  • Static breakpoints support debugging at node boundaries, while dynamic interrupts implement application-level human interaction.