Learning path: Agents with LangChain and LangGraph · Step 4 of 6
Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
A refund under 50 is approved by itself; 120 must wait for a person, maybe until tomorrow. interrupt pauses the graph and returns a question, SqliteSaver keeps the state in refunds.db after the program ends, and a brand new process resumes thread t-big with Command(resume="approve") at ask_human, not at the start.
What you will learn
- Pause a graph with interrupt and hand a question to the caller
- Save state after every step with a checkpointer and a thread id
- Resume the same thread in a new process with Command(resume=...)
- Read a thread's history to see how a decision was reached
Before you start
- LangGraph Nodes, Edges and State
- Basic command-line Python
Some decisions an agent should never make alone. In this article a refund assistant approves small refunds by itself, but stops and asks a person for big ones, and keeps waiting even if the program is closed and started again tomorrow.
Three LangGraph pieces do it: interrupt, a checkpointer with a thread id, and Command(resume=...). We keep the steps as plain functions; a real agent would put a language model in the deciding step, and the pause and resume work exactly the same way.
The use case: three hidden needs
A refund of 25 comes in. It's under 50, so the assistant approves it by itself. A refund of 120 is 50 or more, so the assistant must stop and ask a person. That sounds simple, but it hides three needs:
- The graph must pause in the middle of its work.
- It must survive a restart, because the person may answer in an hour, or tomorrow.
- When the answer arrives, it must continue from the same step, not start again.
A save point
Think of a video game. You walk up to the boss door, and the game saves. You switch it off and go to sleep. The next day you pick your save slot, and you're standing at the same door. In our refund, the save is the checkpointer, the name of the slot is the thread id, and the door where everything waits is interrupt.
The state and the first steps
"""Refund assistant as a LangGraph graph. Plain functions, no LLM."""
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt
LIMIT = 50
class RefundState(TypedDict):
order_id: str
amount: float
decision: str
def check_amount(state: RefundState) -> dict:
return {"decision": "checking"}
def route(state: RefundState) -> str:
return "auto_approve" if state["amount"] < LIMIT else "ask_human"
def auto_approve(state: RefundState) -> dict:
return {"decision": "approved automatically"}
RefundState has three slots: the order id, the amount, and the decision so far. check_amount sets the decision to "checking". route compares the amount with LIMIT: 120 is not under 50, so it says ask_human. auto_approve needs no person.
interrupt: stop and ask
def ask_human(state: RefundState) -> dict:
answer = interrupt({"order": state["order_id"], "amount": state["amount"],
"question": "Approve this refund?"})
return {"decision": "approved by human" if answer == "approve" else "rejected by human"}
def finish(state: RefundState) -> dict:
return {}
When the graph reaches interrupt, it stops right there. The small dictionary we pass in, with the order, the amount and a question, goes out to whoever called the graph. That's the message for the person. Later, when the person's answer comes back, interrupt returns that answer. "approve" gives "approved by human"; anything else becomes "rejected by human".
Keep code before interrupt free of side effects. On resume, this node runs again from its first line, and this time interrupt gives back the answer instead of stopping. Anything above it, like sending an email or charging a card, would happen twice.
Wiring the graph, with a checkpointer
def build_graph(checkpointer):
g = StateGraph(RefundState)
g.add_node("check_amount", check_amount)
g.add_node("auto_approve", auto_approve)
g.add_node("ask_human", ask_human)
g.add_node("finish", finish)
g.add_edge(START, "check_amount")
g.add_conditional_edges("check_amount", route, ["auto_approve", "ask_human"])
g.add_edge("auto_approve", "finish")
g.add_edge("ask_human", "finish")
g.add_edge("finish", END)
return g.compile(checkpointer=checkpointer)
Four nodes, a conditional edge from check_amount, and plain edges to finish and END (the same building blocks as in LangGraph Nodes, Edges and State). The new part is compile(checkpointer=checkpointer). That's what saves the state after every step. Without it, a pause would have nowhere to be kept.
The save slot: app.py
"""Command line for the refund graph. State lives in refunds.db between runs.
python app.py start <thread_id> <order_id> <amount>
python app.py resume <thread_id> <approve|reject>
python app.py history <thread_id>
"""
import sys
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command
from refund_graph import build_graph
def show(result):
if "__interrupt__" in result:
print("PAUSED, waiting for a person:", result["__interrupt__"][0].value)
else:
print("DONE:", result["decision"])
def main():
cmd, thread_id, *rest = sys.argv[1:]
config = {"configurable": {"thread_id": thread_id}}
with SqliteSaver.from_conn_string("refunds.db") as saver:
graph = build_graph(saver)
if cmd == "start":
order_id, amount = rest
state = {"order_id": order_id, "amount": float(amount), "decision": ""}
show(graph.invoke(state, config))
elif cmd == "resume":
show(graph.invoke(Command(resume=rest[0]), config))
elif cmd == "history":
for snap in reversed(list(graph.get_state_history(config))):
print(f"step {snap.metadata['step']:>2} next={snap.next} decision={snap.values.get('decision', '-')!r}")
main()
- The
configholds the thread id, the name of the save slot. Each refund gets its own. SqliteSaveropensrefunds.db, so the saved state lives in a file that outlives the program.- To resume, call
invokewithCommand(resume=...)and the same thread id. get_state_historyreads back every step saved under that thread.
Two refunds
python app.py start t-small A-1001 25
python app.py start t-big A-2001 120
DONE: approved automatically
PAUSED, waiting for a person: {'order': 'A-2001', 'amount': 120.0, 'question': 'Approve this refund?'}
The 25 refund never stopped, because it's under the limit. The 120 refund didn't fail; it paused. Check_amount ran and was saved, route said ask_human, the graph reached interrupt and that step was saved too. The payload is exactly what you'd show the person, in a screen or a message. Then the program simply ends. Nothing is running any more, but thread t-big is still there, in the file.
Memory or a file
With an in-memory saver, one program can pause and resume:
"""Same graph with an in-memory checkpointer: pause and resume inside one process."""
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
from refund_graph import build_graph
graph = build_graph(InMemorySaver())
config = {"configurable": {"thread_id": "demo-1"}}
paused = graph.invoke({"order_id": "A-2001", "amount": 120.0, "decision": ""}, config)
print("paused:", "__interrupt__" in paused)
print("waiting at:", graph.get_state(config).next)
done = graph.invoke(Command(resume="approve"), config)
print("after resume:", done["decision"])
It prints that it's paused, waiting at ask_human, and after the resume, "approved by human". But when that program ends, the memory is gone, and so is the thread. So for real waits we use the SQLite saver. In a brand new process, started after the first one ended:
python app.py resume t-big approve
DONE: approved by human
The thread id found the saved state, and the graph continued at ask_human, not at the beginning. The other answer works the same way: refund A-3001 for 80 on thread t-no pauses too, a new process resumes it with reject, and it prints DONE: rejected by human. The project's three tests (a small refund, an approve, a reject) pass.
The history
Because every step is saved, python app.py history t-big reads the whole history of the thread:
| Step | Next | Decision | What it is |
|---|---|---|---|
| -1 | __start__ | - | The input arrived; nothing has run yet |
| 0 | check_amount | '' | The input is in the state |
| 1 | ask_human | 'checking' | The save point where the graph waited for the person |
| 2 | finish | 'approved by human' | The person said approve |
| 3 | (nothing) | 'approved by human' | Nothing left to run |
Each row is the whole state at one moment, which is very handy when you need to see how a decision was reached.
Common mistakes
- Compiling without a checkpointer.
interruptneeds somewhere to keep the paused state. - Using the in-memory saver for real approvals. When the process ends, every waiting thread is lost.
- Reusing one thread id for different refunds. Each case needs its own save slot.
- Side effects before
interrupt. The node re-runs from its first line on resume. - Calling a pause a failure. A paused thread is waiting, not broken; show the payload to a person.
Quick recap
| Piece | Job |
|---|---|
interrupt({...}) | Stops the graph and hands a question to the caller; returns the answer on resume |
Checkpointer (SqliteSaver) | Saves the whole state after every step, in a file |
| Thread id | The name of the save slot, one per case |
Command(resume=...) | Continues the same thread from the step where it stopped |
get_state_history | Every saved step, for an audit trail |
Try it yourself
Start a refund of 49 and one of 50 and predict which one pauses. Then start a 120 refund on a new thread, close the terminal, open a new one, and resume it with reject. Finally, run history on that thread and compare it with the table above.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.