Lab: Approve, Edit or Reject, Then Resume
Build a LangGraph refund flow that pauses with interrupt() before a risky tool call, survives a process restart in a SQLite checkpointer, resumes with approve, edit or reject, and writes every decision to an audit table.
Contentsand lesson path
On this page
Lessons of Human-in-the-Loop Control
- Which Actions Need a Human? Concept · 15 min
- Interrupting Before a Risky Tool Call Worked example · 20 min
- Lab: Approve, Edit or Reject, Then Resume Lab · 25 min
- Approval Design and Approval Fatigue Concept · 15 min
- Escalation Paths and Override Metrics Worked example · 15 min
- 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.
- Design approval requests that show the proposed action, its arguments, the reason and the expected effect, and record every decision in an audit log.
Prerequisites: Agent Loops & ReAct
01. Beyond Binary Approvals
A simple approval gate offers two buttons: approve or deny. That is often too blunt. Suppose an agent proposes a $1,450 refund, but the reviewer knows the right amount is $1,200. With only "deny", the whole run is thrown away and someone has to start again.
A useful gate offers three decisions. Approve runs the proposed call as it is. Edit changes some arguments and then runs the call. Reject stops the call and gives the agent a written reason, so it can try a different plan. In this lab you build that gate with LangGraph, the graph framework from Interrupting Before a Risky Tool Call, and you prove that the paused run survives a restart of the Python process.
02. Goal and Setup
By the end you will have a graph with three nodes. propose stands in for the model choosing a tool call. review checks the proposal and, above a $50 limit, calls interrupt() to pause. execute calls a fake refund tool, so everything runs offline. A conditional edge after review goes to execute only when the outcome is APPROVED.
The pieces of LangGraph you use:
StateGraphdefines the nodes and edges, andcompile(checkpointer=...)turns them into a runnable graph.SqliteSaver(packagelanggraph-checkpoint-sqlite) is the checkpointer: it saves the state after each step in a SQLite file, so a paused run lives on disk, not in memory.- The config
{"configurable": {"thread_id": ...}}names the run. The same thread id later finds the same saved state. interrupt(payload)pauses the run.invokereturns the payload under"__interrupt__".Command(resume=decision)continues the run, and inside the nodeinterrupt()then returnsdecision.
You need Python 3.12 or later. The lab was tested with Python 3.12, langgraph 1.2.22 and langgraph-checkpoint-sqlite 3.1.3.
mkdir hitl-lab && cd hitl-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "langgraph==1.2.22" "langgraph-checkpoint-sqlite==3.1.3"Save the two files below in hitl-lab. Read review closely, because it holds the key rule of this lab: when the run resumes, LangGraph runs the interrupted node again from its first line. Local variables are not restored. The second time, interrupt() returns the decision instead of pausing. So any code above interrupt() runs twice. Here it only prints and validates, which is safe to repeat. A side effect above the call, such as sending an email or opening a ticket, would happen twice, so it must be idempotent (safe to repeat) or move below the call or into its own node.
The same rule shapes the audit log. The resume command gives each decision an id, and the id travels inside the resume value. If the node is re-run after a crash, the insert finds the same id and INSERT OR IGNORE keeps one row per decision. The fake refund tool does the same with an idempotency key built from tenant, thread and refund id: a retried call adds no second ledger row.
The model's proposal is untrusted input. Prompt injection can steer tool arguments, so review validates the proposal before it applies the $50 limit: amounts such as -1450.00 or 1E+1 end as REJECTED instead of being auto-approved.
"""The refund graph, the decision checks, the audit log and a fake refund tool."""
import hashlib
import json
import re
import sqlite3
from datetime import datetime, timezone
from decimal import Decimal
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt
DB = "hitl.db" # audit log + fake payments ledger; checkpoints live in their own file
REVIEWERS = {"jane": {"role": "finance_lead", "limit_usd": Decimal("1500")},
"omar": {"role": "support", "limit_usd": Decimal("0")}}
EDITABLE = {"amount_usd"}
AMOUNT = re.compile(r"\d{1,6}(\.\d{1,2})?") # plain dollars and cents only
MAX_REFUND = Decimal("100000.00")
AUTO_LIMIT = Decimal("50.00")
TRACE = True # print when nodes run; the tests turn it off
class InvalidDecision(ValueError):
"""Bad reviewer input: refused, and the run stays paused."""
class RefundState(TypedDict, total=False):
owner: str
thread: str
pending: dict
outcome: str
final_args: dict
feedback: str
status: str
tx: str
def validate_args(args):
if not isinstance(args.get("account_id"), str) or not args["account_id"]:
raise InvalidDecision("account_id must be a non-empty string")
raw = args.get("amount_usd")
if not isinstance(raw, str) or not AMOUNT.fullmatch(raw):
raise InvalidDecision(f"amount_usd must look like 1200.00, got {raw!r}")
amount = Decimal(raw).quantize(Decimal("0.01")) # normalise to cents
if not Decimal("0.01") <= amount <= MAX_REFUND:
raise InvalidDecision(f"amount_usd out of range: {amount}")
return {"account_id": args["account_id"], "amount_usd": str(amount)}
def apply_decision(original, decision):
reviewer = REVIEWERS.get(decision.get("reviewer"))
if reviewer is None or reviewer["role"] != "finance_lead":
raise InvalidDecision(f"{decision.get('reviewer')} may not approve refunds")
kind = decision.get("type")
if kind == "REJECT":
if not decision.get("notes"):
raise InvalidDecision("a rejection needs notes for the agent")
return "REJECTED", original
if kind not in ("APPROVE", "EDIT"):
raise InvalidDecision(f"unknown decision type {kind!r}")
edits = decision.get("edits", {}) if kind == "EDIT" else {}
if set(edits) - EDITABLE:
raise InvalidDecision(f"fields not editable: {sorted(set(edits) - EDITABLE)}")
final = validate_args({**original, **edits}) # merge, then validate
if Decimal(final["amount_usd"]) > reviewer["limit_usd"]:
return "ESCALATED", final # above this reviewer's authority
return "APPROVED", final
def connect():
db = sqlite3.connect(DB)
db.execute("CREATE TABLE IF NOT EXISTS audit (decision_id TEXT PRIMARY KEY, "
"decided_at TEXT, owner TEXT, thread TEXT, reviewer TEXT, type TEXT, "
"original TEXT, final TEXT, outcome TEXT)")
db.execute("CREATE TABLE IF NOT EXISTS ledger (idem_key TEXT PRIMARY KEY, "
"account_id TEXT, amount_usd TEXT, tx TEXT)")
return db
def audit(owner, thread, decision, original, final, outcome):
# The decision id travels inside the resume value, so a re-run of the node
# finds the same id and INSERT OR IGNORE keeps exactly one row per decision.
with connect() as db:
db.execute("INSERT OR IGNORE INTO audit VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(decision["id"], datetime.now(timezone.utc).isoformat(), owner,
thread, decision.get("reviewer"), decision.get("type"),
json.dumps(original), json.dumps(final), outcome))
def refund_customer_account(account_id, amount_usd, idem_key):
"""Fake payments API: one ledger row per idempotency key, so a retry is a no-op."""
tx = "TX-" + hashlib.sha256(idem_key.encode()).hexdigest()[:6]
with connect() as db:
db.execute("INSERT OR IGNORE INTO ledger VALUES (?, ?, ?, ?)",
(idem_key, account_id, amount_usd, tx))
return tx
def propose(state): # stands in for the model choosing a tool call
if TRACE:
print(" propose: node entered")
args = {"account_id": "ACC-774", "amount_usd": "1450.00"}
refund_id = "rf-" + hashlib.sha256(json.dumps(args).encode()).hexdigest()[:6]
return {"pending": {"tool": "refund_customer_account", "args": args,
"refund_id": refund_id}}
def review(state):
if TRACE:
print(" review: node entered") # printed again on resume: the node re-runs
try: # the model's proposal is untrusted input too: same checks as an edit
args = validate_args(state["pending"]["args"])
except InvalidDecision as exc:
return {"outcome": "REJECTED", "feedback": f"invalid proposal: {exc}"}
if Decimal(args["amount_usd"]) <= AUTO_LIMIT:
return {"outcome": "APPROVED", "final_args": args}
decision = interrupt({ # pauses here; on resume it returns the decision
"action": state["pending"]["tool"], "args": args,
"reason": "refund above the $50 autonomous limit",
"effect": f"sends ${args['amount_usd']} to {args['account_id']}; irreversible",
"requires_role": "finance_lead"})
outcome, final = apply_decision(args, decision)
audit(state["owner"], state["thread"], decision, args, final, outcome)
return {"outcome": outcome, "final_args": final,
"feedback": decision.get("notes", "")}
def after_review(state):
return "execute" if state["outcome"] == "APPROVED" else END
def idempotency_key(owner, thread, refund_id):
# JSON keeps the parts apart: ("a:x", "y") and ("a", "x:y") give different keys
parts = json.dumps([owner, thread, refund_id]).encode()
return "idem-" + hashlib.sha256(parts).hexdigest()[:24]
def execute(state):
args = state["final_args"]
key = idempotency_key(state["owner"], state["thread"],
state["pending"]["refund_id"])
tx = refund_customer_account(args["account_id"], args["amount_usd"], key)
if TRACE:
print(f" execute: refund {args['amount_usd']} to {args['account_id']}: {tx}")
return {"status": "COMPLETED", "tx": tx}
def build_graph(checkpointer, propose_node=propose):
builder = StateGraph(RefundState)
builder.add_node("propose", propose_node)
builder.add_node("review", review)
builder.add_node("execute", execute)
builder.add_edge(START, "propose")
builder.add_edge("propose", "review")
builder.add_conditional_edges("review", after_review, ["execute", END])
builder.add_edge("execute", END)
return builder.compile(checkpointer=checkpointer)The command-line tool plays the part of your API server. Three choices in it protect the paused run:
- Tenant-scoped thread ids. The LangGraph
thread_idis a hash of the authenticated tenant and the thread name. Another tenant who typest-1gets a different id and finds nothing. - No takeover.
startrefuses a thread that already has state, instead of overwriting a paused run. - Check before resume.
resumevalidates the decision before it calls the graph. A bad request is logged as REFUSED and the run stays paused.
"""Each command is a new Python process, so every resume follows a restart.
python hitl_lab.py start THREAD OWNER
python hitl_lab.py status THREAD OWNER
python hitl_lab.py resume THREAD OWNER REVIEWER APPROVE|EDIT|REJECT [VALUE]
python hitl_lab.py audit
VALUE is the new amount for EDIT and the notes for REJECT."""
import hashlib
import json
import sys
import uuid
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command
from refund_flow import InvalidDecision, apply_decision, audit, build_graph, connect
def config(owner, thread):
# The server derives the LangGraph thread_id from the authenticated tenant
# and the client's thread name, so a tenant cannot name another's thread.
key = hashlib.sha256(json.dumps([owner, thread]).encode()).hexdigest()[:16]
return {"configurable": {"thread_id": f"th-{key}"}}
def show(out):
if "__interrupt__" in out: # a list of Interrupt objects; .value is the payload
out = {"__interrupt__": [i.value for i in out["__interrupt__"]]}
print(json.dumps({k: v for k, v in out.items()
if k not in ("pending", "owner", "thread")}, indent=1))
def resume(graph, owner, thread, reviewer, kind, value):
cfg = config(owner, thread)
paused = graph.get_state(cfg).interrupts
if not paused:
return {"refused": f"no paused run for {owner}/{thread}"}
decision = {"id": uuid.uuid4().hex, "reviewer": reviewer, "type": kind}
if kind == "EDIT":
decision["edits"] = {"amount_usd": value[0]}
if kind == "REJECT" and value:
decision["notes"] = value[0]
args = paused[0].value["args"]
try: # check before resuming, so a bad request leaves the run paused
apply_decision(args, decision)
except InvalidDecision as exc:
audit(owner, thread, decision, args, args, "REFUSED")
return {"refused": f"InvalidDecision: {exc}"}
return graph.invoke(Command(resume=decision), cfg)
command, *rest = sys.argv[1:]
with SqliteSaver.from_conn_string("checkpoints.db") as saver:
graph = build_graph(saver)
if command == "start":
thread, owner = rest
cfg = config(owner, thread)
if graph.get_state(cfg).values: # never overwrite an existing thread
show({"refused": f"{owner}/{thread} already exists"})
else:
show(graph.invoke({"owner": owner, "thread": thread}, cfg))
elif command == "status":
snapshot = graph.get_state(config(rest[1], rest[0]))
print("next:", snapshot.next)
print("waiting for:", [i.value["action"] for i in snapshot.interrupts])
elif command == "resume":
thread, owner, reviewer, kind, *value = rest
show(resume(graph, owner, thread, reviewer, kind, value))
else:
rows = connect().execute("SELECT owner, thread, reviewer, type, original, "
"final, outcome FROM audit ORDER BY decided_at")
for owner, thread, who, kind, old, new, outcome in rows:
old, new = json.loads(old)["amount_usd"], json.loads(new)["amount_usd"]
print(f" {owner} {thread} {who} {kind}: {old} -> {new} = {outcome}")
ledger = connect().execute("SELECT account_id, amount_usd, tx FROM ledger")
print("ledger:", ledger.fetchall())03. Run the Lab
Step 1: start a run, then let the process end. The agent proposes a $1,450 refund for tenant acme. The review node pauses and the payload shows the action, its arguments, the reason and the expected effect: what a reviewer needs to decide. The arguments are the exact values the tool will receive, copied by code from the proposal. Do not show a summary written by the model instead: after a prompt injection, such a summary can describe a different call from the one that would run. When the command returns, the Python process has exited. Only checkpoints.db remembers the run.
python hitl_lab.py start t-1 acme propose: node entered
review: node entered
{
"__interrupt__": [
{
"action": "refund_customer_account",
"args": {
"account_id": "ACC-774",
"amount_usd": "1450.00"
},
"reason": "refund above the $50 autonomous limit",
"effect": "sends $1450.00 to ACC-774; irreversible",
"requires_role": "finance_lead"
}
]
}Step 2: inspect the paused run from a new process. graph.get_state(config) reads the latest checkpoint. next says which node will run on resume, and interrupts holds the pending payload.
python hitl_lab.py status t-1 acmenext: ('review',)
waiting for: ['refund_customer_account']Step 3: try to misuse the thread. Start t-1 again, resume it as another tenant, then resume it with a reviewer who lacks the finance role. All three are refused, and the run stays paused.
python hitl_lab.py start t-1 acme
python hitl_lab.py resume t-1 globex jane APPROVE
python hitl_lab.py resume t-1 acme omar APPROVE{
"refused": "acme/t-1 already exists"
}
{
"refused": "no paused run for globex/t-1"
}
{
"refused": "InvalidDecision: omar may not approve refunds"
}Step 4: edit and approve, in yet another process. Jane lowers the amount to $1,200, within her $1,500 authority. Look at the trace. review: node entered appears again, because the interrupted node re-ran from its first line. propose does not appear: nodes that finished before the pause are not run again. A second resume of the finished thread is refused.
python hitl_lab.py resume t-1 acme jane EDIT 1200.00
python hitl_lab.py resume t-1 acme jane APPROVE review: node entered
execute: refund 1200.00 to ACC-774: TX-347f0e
{
"outcome": "APPROVED",
"final_args": {
"account_id": "ACC-774",
"amount_usd": "1200.00"
},
"feedback": "",
"status": "COMPLETED",
"tx": "TX-347f0e"
}
{
"refused": "no paused run for acme/t-1"
}Step 5: an edit above the reviewer's authority. On a new thread, Jane edits the amount to $5,000. The merged arguments are valid, but the policy check runs again with her limit, so the outcome is ESCALATED and execute never runs.
python hitl_lab.py start t-2 acme > /dev/null # pauses as in step 1
python hitl_lab.py resume t-2 acme jane EDIT 5000 review: node entered
{
"outcome": "ESCALATED",
"final_args": {
"account_id": "ACC-774",
"amount_usd": "5000.00"
},
"feedback": ""
}Step 6: reject with feedback, then read the audit log. Every decision is recorded with the tenant, the thread, the reviewer, the original and the final arguments and the outcome, including the refused request from step 3. Each row also stores decided_at, a UTC timestamp, which the listing leaves out. The ledger shows that only one refund was paid.
python hitl_lab.py start t-3 acme > /dev/null
python hitl_lab.py resume t-3 acme jane REJECT "Customer already got an exchange"
python hitl_lab.py audit review: node entered
{
"outcome": "REJECTED",
"final_args": {
"account_id": "ACC-774",
"amount_usd": "1450.00"
},
"feedback": "Customer already got an exchange"
}
acme t-1 omar APPROVE: 1450.00 -> 1450.00 = REFUSED
acme t-1 jane EDIT: 1450.00 -> 1200.00 = APPROVED
acme t-2 jane EDIT: 1450.00 -> 5000.00 = ESCALATED
acme t-3 jane REJECT: 1450.00 -> 1450.00 = REJECTED
ledger: [('ACC-774', '1200.00', 'TX-347f0e')]Step 7: run the negative tests. They pin down the checks: an over-limit edit escalates, the account cannot be edited, bad amounts and reviewers without the role are refused, a rejection needs notes, a resume works through a brand-new connection, a re-run writes one audit row, a retried refund pays once, and the five injected proposals in the test never reach execute.
"""Negative tests: edits and model proposals are untrusted input into a money tool."""
import os
import tempfile
import unittest
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command
import refund_flow
from refund_flow import InvalidDecision, apply_decision, build_graph, connect
refund_flow.TRACE = False
ORIGINAL = {"account_id": "ACC-774", "amount_usd": "1450.00"}
CFG = {"configurable": {"thread_id": "th-test"}}
EDIT = {"id": "d-1", "reviewer": "jane", "type": "EDIT", "edits": {"amount_usd": "100"}}
class FlowTests(unittest.TestCase):
def setUp(self):
folder = tempfile.mkdtemp()
refund_flow.DB = os.path.join(folder, "hitl.db")
self.checkpoints = os.path.join(folder, "checkpoints.db")
def decide(self, **decision):
return apply_decision(ORIGINAL, {"reviewer": "jane", **decision})
def test_edit_above_reviewer_limit_is_escalated(self):
outcome, _ = self.decide(type="EDIT", edits={"amount_usd": "5000"})
self.assertEqual(outcome, "ESCALATED")
def test_edit_cannot_change_the_account(self):
with self.assertRaises(InvalidDecision):
self.decide(type="EDIT", edits={"account_id": "ACC-999"})
def test_edit_with_bad_amount_is_refused(self):
for amount in ("abc", "-5", None, "1E+3", "0.001", "1200.999", "0", 1200):
with self.assertRaises(InvalidDecision):
self.decide(type="EDIT", edits={"amount_usd": amount})
def test_reviewer_without_the_role_cannot_approve(self):
with self.assertRaises(InvalidDecision):
apply_decision(ORIGINAL, {"reviewer": "omar", "type": "APPROVE"})
def test_reject_needs_notes(self):
with self.assertRaises(InvalidDecision):
self.decide(type="REJECT")
def test_resume_works_with_a_new_connection(self):
with SqliteSaver.from_conn_string(self.checkpoints) as saver:
build_graph(saver).invoke({"owner": "acme", "thread": "t-1"}, CFG)
with SqliteSaver.from_conn_string(self.checkpoints) as saver: # "restart"
out = build_graph(saver).invoke(Command(resume=EDIT), CFG)
self.assertEqual(out["status"], "COMPLETED")
def test_audit_row_is_written_once_per_decision(self):
with SqliteSaver.from_conn_string(self.checkpoints) as saver:
graph = build_graph(saver)
graph.invoke({"owner": "acme", "thread": "t-1"}, CFG)
graph.invoke(Command(resume=EDIT), CFG)
refund_flow.audit("acme", "t-1", EDIT, ORIGINAL, ORIGINAL, "APPROVED") # re-run
rows = connect().execute("SELECT COUNT(*) FROM audit").fetchone()[0]
self.assertEqual(rows, 1)
def test_retried_refund_is_paid_once(self):
for _ in range(2):
refund_flow.refund_customer_account("ACC-774", "100.00", "idem-1")
rows = connect().execute("SELECT COUNT(*) FROM ledger").fetchone()[0]
self.assertEqual(rows, 1)
def test_bad_model_proposals_never_execute(self):
for amount in ("-1450.00", "-1E+9", "1E+1", "0.001", "20.005"):
def propose(state, amount=amount): # a model steered by injection
return {"pending": {"tool": "refund_customer_account",
"args": {"account_id": "ACC-1",
"amount_usd": amount},
"refund_id": "rf-x"}}
with SqliteSaver.from_conn_string(":memory:") as saver:
out = build_graph(saver, propose).invoke(
{"owner": "acme", "thread": "t-1"}, CFG)
self.assertEqual(out["outcome"], "REJECTED", amount)
self.assertNotIn("status", out) # execute never ran
if __name__ == "__main__":
unittest.main()python -m unittest test_flow.........
----------------------------------------------------------------------
Ran 9 tests in 1.482s
OK04. Verify Your Understanding
05. Apply It
Carry the lab into the skill's practice project, an agent that can send emails and issue refunds:
- Add a
send_emailtool with its own risk rule, and a second fake backend. Pause before every send to an address outside your domain. - After approval, change the arguments, the tool version or the user's permissions, and require a new decision when any of them differs from what was approved.
- Give each pending interrupt an expiry time, and test that a late resume is refused and escalated rather than run.
- Add the claim step from the troubleshooting list and test two resumes of the same thread.
- Route REJECTED back to
proposewith the reviewer's notes in state, and stop after a fixed number of rejections so the agent cannot loop for ever.
06. Review Prompt
Without looking back, explain what happens, step by step, when a run pauses at interrupt(), the process exits, and a new process resumes it with Command(resume=...). Which node runs again and from which line? Why must code above interrupt() be idempotent? Then list what an audit row for an edit must contain, and explain why the resume endpoint validates a decision before it calls the graph.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.