Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

Interrupting Before a Risky Tool Call

Implement interrupt patterns in stateful agent graphs to pause execution before risky tool invocations, persist pending actions, and await external authorization.

Contentsand lesson path

On this page

  1. The Challenge of Pre-Action Interception
  2. Graph Interruption Mechanics and Lifecycle
  3. Verify Your Understanding
  4. Apply it
  5. Review Prompt

Lessons of Human-in-the-Loop Control

  1. Which Actions Need a Human? Concept · 15 min
  2. Interrupting Before a Risky Tool Call Worked example · 20 min
  3. Lab: Approve, Edit or Reject, Then Resume Lab · 25 min
  4. Approval Design and Approval Fatigue Concept · 15 min
  5. Escalation Paths and Override Metrics Worked example · 15 min
  6. Check: Human Oversight Scenarios Knowledge check · 8 questions

What you will learn

  • Implement interrupt-and-resume so a run pauses before a risky tool call, persists its state, and continues after approve, edit or reject, even after a restart.

Prerequisites: Agent Loops & ReAct

01. The Challenge of Pre-Action Interception

Some tool calls change the world outside the agent: issuing a refund, dropping a database column, sending an email to a customer. Before such a call you often want a person to say yes. A plain agent loop that waits for that reply has to keep a worker busy the whole time, and a reply can take hours or days.

Worse, if the server restarts while it waits, the pending action lived only in memory and is lost: nobody knows whether the refund should still happen. Graph frameworks such as LangGraph solve this with an interrupt: the graph saves its state, including the pending action, to a checkpoint store, stops, and returns. Nothing has to keep running while the person decides; a later call resumes from the saved state.

02. Graph Interruption Mechanics and Lifecycle

An approval pause in a graph has four steps:

1. Checking the call against a policy. Before any tool runs, the graph passes through a policy node. This node compares the tool name and its arguments with the risk limits you set, for example a refund above $50. If the call is safe, the graph goes straight to the tool. Because this check is plain code, not a model call, the many harmless lookups run without waiting for a person.

2. Raising the graph interrupt. When a high-risk action is detected, the review node calls interrupt(payload) (in LangGraph, from langgraph.types import interrupt). This is a dynamic interrupt inside a node: the run pauses at that call, and the payload (the proposed tool name, its arguments, a reason and the required reviewer role) is returned to the caller under result["__interrupt__"]. Put the risky tool call after the approval check, in the same node after interrupt() returns or in the next node, so nothing is sent before a person decides. LangGraph also has static breakpoints (interrupt_before at compile time), but its documentation recommends them for debugging, not for human-in-the-loop flows.

3. Saving the state and pausing. When the node calls interrupt(), the checkpointer saves the current state to its storage (SQLite or PostgreSQL for a run that must survive restarts). The invoke call then returns with the payload, so the worker process can finish its request and move on: nothing has to stay running while the reviewer decides. How long a person takes to answer then no longer decides how many workers you need.

4. Resuming the run. When the reviewer submits a decision, your service invokes the graph again with the same thread_id and Command(resume=decision). The runtime loads the saved state and re-runs the interrupted node from its first line; this time interrupt() returns the decision instead of pausing. Only graph state is restored, not local variables or the point inside the function. So keep code before interrupt() free of side effects (or idempotent): a notification sent or a ticket created above the call would be sent or created again on every resume.

Python · refund_graph.py (tested with langgraph 1.2.24 and langgraph-checkpoint-sqlite 3.1.3)
# Requires: pip install "langgraph>=1.0" langgraph-checkpoint-sqlite
import sqlite3
from pprint import pprint
from typing import Any, Dict, TypedDict

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


class RefundState(TypedDict, total=False):
    account_id: str
    refund_cents: int  # money as integer cents, never a float
    decision: Dict[str, Any]
    status: str


def review_refund(state: RefundState) -> dict:
    # On resume this node runs again from its first line, so nothing above
    # interrupt() may have side effects (no emails, no ticket creation).
    if state["refund_cents"] <= 5000:  # $50.00
        return {"decision": {"type": "approve", "by": "policy"}}
    decision = interrupt({
        "action": "refund_customer_account",
        "args": {"account_id": state["account_id"],
                 "amount_cents": state["refund_cents"]},
        "reason": "refund above the $50 autonomous limit",
        "requires_approval_by": "finance_lead",
    })
    return {"decision": decision}  # the value passed to Command(resume=...)


def execute_refund(state: RefundState) -> dict:
    if state["decision"]["type"] != "approve":
        return {"status": "REJECTED"}
    # Call the payments API here, with an idempotency key (see lesson 03)
    return {"status": "REFUNDED"}


builder = StateGraph(RefundState)
builder.add_node("review_refund", review_refund)
builder.add_node("execute_refund", execute_refund)
builder.add_edge(START, "review_refund")
builder.add_edge("review_refund", "execute_refund")
builder.add_edge("execute_refund", END)
conn = sqlite3.connect("hitl.db", check_same_thread=False)
graph = builder.compile(checkpointer=SqliteSaver(conn))

config = {"configurable": {"thread_id": "refund-42"}}
result = graph.invoke({"account_id": "acct-9", "refund_cents": 120000}, config)
pprint(result["__interrupt__"][0].value)  # what the reviewer sees; run is paused

# Later, possibly in a new process after a restart:
result = graph.invoke(Command(resume={"type": "approve", "by": "lead-7"}), config)
print(result["status"])
Terminal (Python 3.12 or later)
python3 -m venv .venv && . .venv/bin/activate
pip install "langgraph>=1.0" langgraph-checkpoint-sqlite
python3 refund_graph.py
Expected output
{'action': 'refund_customer_account',
 'args': {'account_id': 'acct-9', 'amount_cents': 120000},
 'reason': 'refund above the $50 autonomous limit',
 'requires_approval_by': 'finance_lead'}
REFUNDED

The first invoke stops at interrupt() and returns the payload, which is the dict printed above; the second, with Command(resume=...), continues the same thread and prints REFUNDED. You can also split the script at the # Later comment and run the two halves as separate processes: the second still prints REFUNDED, because the paused state is in hitl.db. The state keeps money as integer cents, so no float rounding creeps into the amount (lesson 01 uses Decimal for the same reason). Older code raised NodeInterrupt for this; it is deprecated in favour of interrupt(), and it could not hand the reviewer's decision back to the node. Because the state is checkpointed in SQLite or PostgreSQL, the reviewer can take seconds or days, and the paused run survives process restarts and redeploys, as long as the state schema stays compatible. Lab: Approve, Edit or Reject, Then Resume runs a flow like this one with LangGraph and SqliteSaver, including a restart of the Python process between pause and resume.

Because the paused run lives in the checkpoint store, a worker does not need to hold a database transaction or connection open while it waits for the reviewer. Close them when invoke returns. On resume, whichever worker handles the request opens a fresh connection, loads the state by thread_id and continues from the interrupted node.

03. Verify Your Understanding

Practice check · 3 questions

Graph Interruption Patterns Knowledge Check

Three questions on when to interrupt, what `interrupt()` returns on resume and why a checkpointer is needed.

Q1. Why must the approval check run before the tool call that changes the outside world?
Q2. The host resumes a paused run with `Command(resume={"type": "edit", "args": {"amount": 40}})`. When the node runs again, what does `decision = interrupt(payload)` put in `decision`?
Q3. You call `interrupt()` in a graph compiled without a checkpointer. Why can the run not be resumed later?
Practice only: not graded, not saved, not evidence.

04. Apply it

Add an approval pause to a different risky tool, such as delete_customer_data or publish_release, and check your design against these points:

  • The tool call after the pause has an idempotency key. A crash after the call but before the checkpoint is saved makes the node run again, and the key stops a second refund or charge.
  • Reviewers are told when a request waits, for example by a Slack or Teams message with a link to the approval page.
  • A pending request has a deadline, such as 24 hours. When it passes, the graph moves to an escalation or "not done" path instead of staying paused forever.
  • The resume endpoint checks who is calling: only a person with the required role can approve, and the check happens before the decision is read.
  • Every decision is logged with the reviewer, the time, the decision and the original arguments, in a log that cannot be edited.
  • Checkpoints are kept apart by tenant, so a reviewer for one customer organisation never sees the paused runs of another.
  • A late approval checks the record again before acting. If support already settled the claim by hand two days ago, the refund must not run a second time.

05. Review Prompt

Without looking back, explain what interrupt() does to the run, where the pending action is kept while the person decides, and what happens to the interrupted node on resume. Then explain why a reviewer who takes two days does not tie up a worker, why a refund call still needs an idempotency key, and what should happen to a request that nobody answers.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check