Human-in-the-Loop
Pause a graph with interrupt(), show a person the proposed action, and resume with their decision - approve, edit or reject - even from another process.
What you will be able to do
- Explain what Human-in-the-Loop adds to an agent, and where it belongs
- Pause a node with interrupt() and resume it with Command(resume=...)
- Route on the human’s answer: approve, edit or reject
- Resume a paused approval from a different process using a checkpointer
- Put an approval step in front of ToolNode
- Design the approval endpoint: authorization, idempotency, validation, audit
The idea, in plain English
Human-in-the-loop (HITL) means a person is one step of an automatic workflow. The agent researches and drafts on its own. But before something important happens - an email is sent, money is refunded, data is deleted - the graph stops and waits for a person to decide.
LangGraph does this with interrupt(). A node calls it, the run pauses, and the checkpointer from Lesson 3.6 saves the paused run. Later - seconds or days - your app sends the answer with Command(resume=...), and the run continues.
Everything below was run on LangGraph 1.2.14, with llama3 drafting the email.
Worked example: Approve before sending an email: llama3 drafts, a reviewer edits, the graph sends.
1 - The agent drafts
Process 1 invokes the graph on thread email-approval-123. The draft node asks llama3 for the email body.
A real run with SqliteSaver: llama3 drafts in process 1, the graph pauses, a reviewer edits the draft and resumes it from process 2.
Words you will see in this lesson
A few words about pausing a graph.
Human-in-the-loop (HITL)A person is a step in the workflow - usually to approve something.interrupt(payload)Pauses the run inside a node and sends the payload (what to review) to your app.Command(resume=answer)Continues a paused run. interrupt() then returns the answer.__interrupt__The key in the result that holds the payload of a paused run.Side effectA change outside the graph: an email sent, money moved, a row deleted.Audit trailA record of who approved what, and when.An everyday example: a manager’s signature
- An employee prepares a purchase order on their own - prices, quantities, supplier. (The agent drafts.)
- Before it goes out, it waits on the manager’s desk for a signature. (interrupt() - the run is paused and saved.)
- The manager may be away for two days. The order simply waits. (The checkpoint keeps it.)
- The manager signs, corrects the quantity, or rejects it. (approve / edit / reject.)
- Only a signed order is sent to the supplier. (The router sends the run to the action or to END.)
Where to put a human
Let the agent do the thinking. Ask a person before actions that are hard to undo:
- Do not ask for approval at every step. People who must approve everything soon approve without reading.
- One meaningful check before the side effect is better than five before small things.
Research, search, summarizeAutomatic.Draft an email, a reply, a SQL queryAutomatic - the draft is what gets reviewed.Send email, post publiclyApproval: external communication.Refund, transfer, purchaseApproval: money moves.DELETE, deploy, change permissionsApproval: hard to undo.Low confidence, policy exceptionAsk a human to decide.How interrupt() works
- First run: the node calls interrupt(payload). The run stops. invoke() returns the state so far plus __interrupt__ with the payload. get_state(config).next shows the paused node.
- Your app shows the payload to a person and collects the answer.
- Resume: graph.invoke(Command(resume=answer), config) with the SAME thread_id.
- The paused node runs AGAIN from its first line. This time interrupt() does not pause - it returns the answer.
- Nodes before it (like draft) are NOT run again.
- You need a checkpointer. Without one, the pause worked, but resuming failed: "RuntimeError: Cannot use Command(resume=...) without checkpointer".
Watch out: Everything before interrupt() in the node runs twice: once to pause, once on resume. Our approval node printed "started" twice for one approval. Keep that part free of side effects - draft in an earlier node, send in a later one.
Example 1 - approve an email before it is sent
Three nodes: draft -> approval -> send_email. Read them in order:
- draft: llama3 writes the email body. No side effects.
- approval: calls interrupt() with the recipient, subject and body. The answer is a small dict: {"decision": "approve" | "edit" | "reject", "body": ...}.
- It cleans the decision (strip().lower()) and treats anything unknown as reject. Without this, "Approve" with a capital A counted as a rejection.
- edit: the reviewer’s new body replaces the draft, and the email is approved.
- A conditional edge: approve -> send_email, anything else -> END.
- SqliteSaver keeps the pause in a file, so start and resume can be different processes.
- The resume branch first checks that something is really waiting (state.tasks has an interrupt).
import sqlite3
import sys
from typing import TypedDict
from langchain_ollama import ChatOllama
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
llm = ChatOllama(model="llama3", temperature=0)
class EmailState(TypedDict, total=False):
request: str
recipient: str
subject: str
body: str
decision: str
def draft(state: EmailState):
print(" drafting with llama3")
reply = llm.invoke(
"Write a two-sentence email body (no greeting, no sign-off) for this request: "
+ state["request"]
)
return {"subject": "Deployment completed", "body": reply.content.strip()}
def approval(state: EmailState):
# Runs twice: once to pause, once on resume - no side effects here.
answer = interrupt({"to": state["recipient"], "subject": state["subject"], "body": state["body"]})
decision = str(answer.get("decision", "")).strip().lower()
if decision == "edit":
return {"decision": "approve", "body": answer["body"]}
return {"decision": decision if decision in ("approve", "reject") else "reject"}
def send_email(state: EmailState):
print(f" SENDING to {state['recipient']}: {state['body']}")
return {}
builder = StateGraph(EmailState)
builder.add_node("draft", draft)
builder.add_node("approval", approval)
builder.add_node("send_email", send_email)
builder.add_edge(START, "draft")
builder.add_edge("draft", "approval")
builder.add_conditional_edges("approval", lambda s: "send" if s["decision"] == "approve" else "stop",
{"send": "send_email", "stop": END})
builder.add_edge("send_email", END)
conn = sqlite3.connect("approvals.db", check_same_thread=False)
graph = builder.compile(checkpointer=SqliteSaver(conn))
config = {"configurable": {"thread_id": "email-approval-123"}}
if sys.argv[1] == "start":
result = graph.invoke({"request": "Tell John the v2.5 deployment finished",
"recipient": "john@example.com"}, config)
print(" waiting for:", result["__interrupt__"][0].value)
else:
state = graph.get_state(config)
pending = [i for task in state.tasks for i in task.interrupts]
if not pending:
print(" nothing waiting for approval on this thread")
sys.exit()
print(" waiting at:", state.next)
answer = {"decision": sys.argv[2]}
if sys.argv[2] == "edit":
answer["body"] = sys.argv[3]
result = graph.invoke(Command(resume=answer), config)
print(" decision:", result["decision"], "| next:", graph.get_state(config).next)$ python approve_email.py start
drafting with llama3
waiting for: {'to': 'john@example.com', 'subject': 'Deployment completed',
'body': 'Here is a two-sentence email body:\n\nThe v2.5 deployment has
successfully completed and is now live. All systems are functioning as
expected, and we are ready to move forward with the next steps.'}
$ python approve_email.py resume edit "The v2.5 deployment has completed and is live. All systems are working as expected."
waiting at: ('approval',)
SENDING to john@example.com: The v2.5 deployment has completed and is live. All systems are working as expected.
decision: approve | next: ()
$ python approve_email.py resume approve
nothing waiting for approval on this thread
On a fresh thread: resume reject -> decision: reject | next: () (nothing sent)Reading Example 1
- Process 1 drafted with llama3 and paused. Notice the draft starts with "Here is a two-sentence email body:" - exactly why a human should look before it is sent.
- Process 2 - a fresh Python process - found the run waiting at approval, applied the edit, and sent the corrected text.
- Process 3 tried to approve again: nothing was waiting, so nothing was sent twice.
- Reject on a fresh thread ended the run without sending.
First invoke
result keys: ['recipient', 'subject', 'body', '__interrupt__']
get_state(config).next: ('approval',)
stream_mode="updates": {'prepare': {...}} then {'__interrupt__': (Interrupt(value={...}),)}
One approval, counted
prepare ran 1 time, approval ran 2 times (pause + resume), send ran 1 time
Resume values
Command(resume="approve") -> approved True, email sent
Command(resume="reject") -> approved False, END
Command(resume="Approve") -> approved False (decision == "approve" is case-sensitive)
Edge cases
no checkpointer, invoke -> pauses, returns __interrupt__
no checkpointer, Command(resume=..) -> RuntimeError: Cannot use Command(resume=...) without checkpointer
resume a finished thread -> returns final state, nothing re-sent
resume an unknown thread_id -> runs from START with no input -> KeyError: 'recipient'
new input on a paused thread -> starts over, pending approval discardedExample 2 - approval in front of ToolNode
With a tool agent (Lesson 3.5), the action to approve is the tool call. Put a review node between the agent and ToolNode:
- review calls interrupt() with the tool name and its arguments.
- Approve -> Command(goto="tools"): ToolNode runs the call as it is.
- Edit -> Command(goto="tools", update=...) with a new AIMessage that has the SAME id (so it replaces the old one) and the new arguments.
- Reject -> Command(goto="agent", update=...) with a ToolMessage saying why. The model learns it was rejected.
- destinations=("tools", "agent") on add_node tells LangGraph where review may go, so it can draw the graph.
from langchain_core.messages import AIMessage, ToolMessage
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.types import Command, interrupt
OUTBOX = []
@tool
def send_email(to: str, body: str) -> str:
"""Send an email."""
OUTBOX.append((to, body))
return f"sent to {to}"
# agent: the Lesson 3.5 agent node - a model bound to [send_email]
def review(state: MessagesState):
request = state["messages"][-1]
call = request.tool_calls[0]
answer = interrupt({"tool": call["name"], "args": call["args"]})
if answer["decision"] == "approve":
return Command(goto="tools")
if answer["decision"] == "edit": # same message id -> replaces it
edited = AIMessage(content="", id=request.id,
tool_calls=[{**call, "args": {**call["args"], **answer["args"]}}])
return Command(goto="tools", update={"messages": [edited]})
rejected = ToolMessage(content=f"Rejected by reviewer: {answer.get('reason', '')}",
tool_call_id=call["id"])
return Command(goto="agent", update={"messages": [rejected]})
def needs_review(state: MessagesState):
return "review" if state["messages"][-1].tool_calls else END
builder = StateGraph(MessagesState)
builder.add_node("agent", agent)
builder.add_node("review", review, destinations=("tools", "agent"))
builder.add_node("tools", ToolNode([send_email]))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", needs_review, ["review", END])
builder.add_edge("tools", "agent")
graph = builder.compile(checkpointer=InMemorySaver())paused with {'tool': 'send_email', 'args': {'to': 'john@example.com', 'body': 'Deployment complete.'}}
approve human -> ai send_email(...) -> tool 'sent to john@example.com' -> ai 'Done: sent to john@example.com'
outbox: ('john@example.com', 'Deployment complete.')
edit {"args": {"body": "Deployment of v2.5 complete."}}
outbox: ('john@example.com', 'Deployment of v2.5 complete.')
reject {"reason": "wrong recipient"}
tool 'Rejected by reviewer: wrong recipient' -> agent outbox: unchanged
graph: __start__ --> agent; agent -.-> review; agent -.-> __end__;
review -.-> tools; review -.-> agent; tools --> agent;Tip: For a simple fixed pause before a node, compile(interrupt_before=["tools"]) also works: the run stops before that node and invoke(None, config) continues. interrupt() inside a node is more flexible - it carries a payload and receives an answer.
Paused for days
- An approval can wait over lunch, overnight, or across a deploy. The checkpoint keeps it.
- With SqliteSaver, a different process resumed the run (Example 1). With InMemorySaver, the pause would disappear with the process.
- In production use Postgres, so whichever server handles the reviewer’s click can see the paused run.
- Keep your own table of pending approvals - thread_id, who must approve, what was proposed, when it expires - so a dashboard can list them and old requests can expire.
Resuming safely
LangGraph trusts the thread_id. So your approval endpoint must check things first:
- Is the user logged in, and allowed to approve THIS thread?
- Is the thread really waiting? (get_state(config).tasks has an interrupt.) Resuming an unknown thread started the graph from START and failed with KeyError: 'recipient'.
- Is it a resume? Sending new input instead of Command(resume=...) restarted the run and threw away the pending approval.
- Is the answer valid? Accept only the fields you allow - never an arbitrary state update.
- Two clicks at the same time can both pass a simple check. Mark the approval as used in your own database first, and make the action safe to repeat (an idempotency key on the email or refund).
- Keep an audit trail: thread, action, proposal, approver, time, decision, result.
- Approve what was shown: store the exact proposal with a version, and reject an approval of an older version.
The recipe
- 1. Do the work (draft) in one node.
- 2. In the next node, call interrupt(payload) - nothing with side effects before it.
- 3. Compile with a checkpointer.
- 4. Your app shows the payload, collects the answer, checks it, and calls invoke(Command(resume=answer), config).
- 5. A router sends the run to the action (approve / edit) or to END (reject).
- 6. Do the side effect in its own node, after approval.
Human-in-the-loop at a glance
PauseStop inside a node and hand a payload to the app.
answer = interrupt({"body": state["body"]})Detect the pauseinvoke() returns an __interrupt__ list.
result["__interrupt__"][0].value
Is it waiting?Pending interrupts on the thread.
graph.get_state(config).tasks[0].interrupts
Resumeinterrupt() returns the answer this time.
graph.invoke(Command(resume=answer), config)
Route from the nodeChoose the next node and update state at once.
return Command(goto="tools", update={...})Static pauseStop before a node; continue with None.
compile(checkpointer=cp, interrupt_before=["tools"])
ImportBoth live in langgraph.types.
from langgraph.types import interrupt, Command
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Put a print at the top of the approval node, pause and resume, and count how many times it prints.”
“Resume with {"decision": "reject"} and confirm send_email never runs.”
“Run start in one terminal and resume edit in another. Then swap SqliteSaver for InMemorySaver.”
“Resume with "Approve", {}, and {"decision": "yes"}. Make every one of them end safely.”
“Add the review node in front of ToolNode in your Lesson 3.5 graph, and reject one call with a reason.”
What usually goes wrong
The node re-runs from its first line on resume, so anything above interrupt() happens twice.
✗ def approval(state):
notify_slack(state["body"])
answer = interrupt(...)✓ def notify(state): notify_slack(...) # its own node
def approval(state): answer = interrupt(...)Without a checkpointer you cannot resume at all; with InMemorySaver the pause is lost on restart. Approvals wait for hours - use a database.
✗ builder.compile()✓ builder.compile(checkpointer=PostgresSaver(...))The client sends a request, not a fact. The backend authenticates, checks the user may approve this thread, checks it is still waiting, then resumes.
✗ if request.json["approved"]: send_email(...)✓ thread = approvals.get_pending(thread_id, approver=user.id)
graph.invoke(Command(resume=validated_answer), config)Accept a small schema - decision plus the fields that may be edited - and normalize it. Unknown means reject.
✗ return answer # whatever the client sent becomes state✓ decision = str(answer.get("decision", "")).strip().lower()Double clicks and retries happen. Mark the approval used before resuming, and give the side effect an idempotency key.
Approval on every search and calculation trains people to click without reading. Approve side effects, not reasoning.
Key points
- HITL puts a person at a defined point in the workflow, before actions with consequences.
- interrupt(payload) pauses the run; invoke() returns __interrupt__ with the payload.
- Command(resume=answer) on the same thread continues; interrupt() returns the answer.
- The paused node runs again from its start - nothing with side effects before interrupt().
- A checkpointer is required to resume; a database keeps the pause through restarts.
- Route on a validated answer: approve, edit or reject - unknown means reject.
- Approval is not authorization: the backend checks the user, the thread and its status.
- Make side effects idempotent and keep an audit trail of what was proposed and approved.
Quick check before you move on
Quiz
- 1.
The approval node logs "approval requested" before calling interrupt(). One approval later, how many log lines are there?
- 2.
The reviewer clicks Approve and the client sends "Approve". The node checks decision == "approve". What happens?
- 3.
What happens if you call Command(resume=...) on a graph compiled without a checkpointer?
- 4.
A reviewer rejects a send_email tool call. How does the agent find out?
- 5.
Which is safer: Browser -> execute tool, or Browser -> backend -> authorization -> LangGraph resume -> tool?
Interview questions
How would you implement human approval in a LangGraph agent?
Model approval as a node that calls interrupt() with the proposed action. Compile with a durable checkpointer so the paused run survives restarts. The application shows the payload to an authorized user, then resumes the same thread with Command(resume=decision); a conditional edge or Command(goto=...) routes to the action or to END. Around it: authorization, validation, idempotency, audit logging and expiry.
What should you watch for inside a node that calls interrupt()?
The node re-executes from the beginning on resume, so code before interrupt() runs twice. Keep side effects out of it and put them in their own nodes.
How do you let a reviewer edit an agent’s tool call?
Interrupt with the tool name and arguments, accept edited arguments in a fixed schema, and return an AIMessage with the same id and the new arguments - the messages reducer replaces it - then go to ToolNode.
How do you prevent duplicate execution after approval?
Record the approval in your own database and mark it used atomically before resuming, check the thread is still waiting, and pass an idempotency key to the side effect so a repeat is a no-op.
How would you secure the approval endpoint?
Authenticate the user, check they are allowed to approve that thread and tenant, verify the approval matches the exact proposal version shown, validate the answer schema, and log who decided what and when.
How do you handle approvals that stay pending for days?
Durable checkpoints keep the run; your own pending-approvals table tracks owner and deadline, sends reminders, and expires or escalates - resuming with a reject when the deadline passes.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...