Home/Tutorials/LangGraph Human-in-the-Loop Tutorial: Pause, Approve, and Resume AI Agents in Python
Intermediate DifficultyAgent Frameworks

LangGraph Human-in-the-Loop Tutorial: Pause, Approve, and Resume AI Agents in Python

Learn how to add Human-in-the-Loop controls to Python AI agents using LangGraph, SQLite checkpointing, and Gemini 3.5 Flash Lite. Includes a working cross-process refund approval CLI, real-world use cases, and benchmarks showing how to avoid duplicate LLM calls on resume.

LangGraph Human-in-the-Loop Tutorial: Pause, Approve, and Resume AI Agents in Python

Letting an AI agent issue a $185.00 refund on its own is a fast way to wake up to a bad billing report. Blocking every $18.00 mouse refund or PDF invoice request behind a manager queue is just as bad, because support leads stop reading prompts once the queue fills with noise.

I built a small Python customer support refund agent using LangGraph (langgraph==1.2.24), SQLite checkpointing (langgraph-checkpoint-sqlite==3.1.3), and Gemini 3.5 Flash Lite (gemini-3.5-flash-lite via langchain-google-genai==4.5.3) to see how cleanly interrupt(), Command, and SqliteSaver handle cross-process pause, approve, edit, and reject workflows. Before writing any code, I wrote down two concrete questions I wanted to measure: whether local SQLite checkpoint overhead stays under 50 ms compared to model latency, and what happens to your token bill when you put an LLM call above interrupt() inside the same node.

Every command, output, and number below comes from running this project on Ubuntu 24.04.5 LTS with Python 3.14.5, an Intel Core i3-1315U, 15.2 GiB of RAM, and uv 0.11.16.

Where pause, approve, and resume fit in real systems

Human-in-the-loop (HITL) control sounds simple until you look at how real software runs. In a notebook prototype, pausing an agent means waiting on a blocking input loop while the Python process stays open in your terminal. In production, a customer submits a ticket, the backend worker finishes in a few seconds and exits, and a human reviewer clicks a button in a web dashboard or Slack message hours later on a completely different worker process.

That time gap between proposing an action and executing it is where persistent pause and resume earn their keep. Here are five real-life systems where I would wire this pattern in before giving an agent write access:

  • Financial refunds and payouts: An agent reads a support ticket, checks the order date and item price, and drafts a refund. Low-value requests under a policy cap (such as $50.00 in our project) clear automatically. High-value refunds pause until a billing lead approves the full amount, trims it to a partial refund, or rejects the claim.
  • Production deployments and schema migrations: An operations agent investigates an alert, generates a migration or rollback plan, and pauses with the exact diff inside the interrupt payload. An on-call engineer reviews that diff and resumes execution only when the risk looks acceptable.
  • Customer-facing and legal communication: Drafting an apology email or compliance notice is cheap, while sending the wrong promise to a customer is expensive. Pausing lets a reviewer read the draft, edit two sentences, and resume delivery with the edited copy instead of regenerating everything.
  • Healthcare, HR, and account security changes: Changing permissions, closing accounts, or updating payroll records needs an audit trail of who signed off. Resuming through a structured Command stores the reviewer name alongside the state transition.
  • Policy exceptions outside standard rules: When a refund request arrives 47 days after delivery against a 30-day return window, the agent should escalate rather than guess. If the human rejects the exception, the graph can still branch into a rejection node that writes a polite explanation without touching the payment ledger.

Conditional routing matters just as much as pausing. Pause every ticket and reviewers start clicking approve without reading. In this project, reply_only requests and refunds below APPROVAL_THRESHOLD = 50.0 bypass human review and execute right away, while refunds at or above $50.00 or tickets marked escalate pause cleanly.

Architecture and setup with Gemini 3.5 Flash Lite

The project is a self-contained uv package (hitl-agent) with five sample orders in data/orders.json, a local JSON ledger and sent-email log in src/hitl_agent/store.py, a four-node LangGraph workflow in src/hitl_agent/graph.py, and a cross-process CLI in src/hitl_agent/cli.py.

Running uv sync resolved 58 packages in 2.60 s and locked these exact versions:

python 3.14.5
langgraph==1.2.24
langgraph-checkpoint==4.3.2
langgraph-checkpoint-sqlite==3.1.3
langchain-google-genai==4.5.3
google-genai==3.6.1
pydantic==2.14.4
pytest==9.2.0

The graph splits work across four nodes: triage_and_draft, human_review, execute_action, and handle_rejection. Keeping triage_and_draft separate from human_review was deliberate. My starting hypothesis was that isolating the Gemini 3.5 Flash Lite call in its own node would avoid duplicate LLM calls on resume. The token comparison later in this walkthrough tests that directly.

First, src/hitl_agent/models.py defines the Pydantic schema Gemini 3.5 Flash Lite must populate alongside the SupportState dictionary that SQLite checkpoints at every step:

class TriageDecision(BaseModel):
    action: Literal["reply_only", "issue_refund", "escalate"] = Field(
        ...
    )
    refund_amount: float = Field(
        ge=0.0,
        ...
    )

In src/hitl_agent/llm.py, GeminiSupportLLM sets MODEL_ID = "gemini-3.5-flash-lite" (documented on the Google AI Studio model page), initializes ChatGoogleGenerativeAI, and chains with_structured_output using include_raw=True:

        self.model = model
        self._client = ChatGoogleGenerativeAI(model=model)
        self._triage_chain = self._client.with_structured_output(
            TriageDecision, include_raw=True
        )
        self._rejection_chain = self._client.with_structured_output(
            RejectionDraft, include_raw=True
        )

Passing include_raw=True is a small detail that pays off fast. LangChain returns both the validated Pydantic model (response["parsed"]) and the raw message (response.get("raw")), which carries usage_metadata so we record exact input_tokens, output_tokens, and total_tokens for every live call. The same module provides MockSupportLLM behind a --mock flag so pytest and offline re-runs can exercise the full LangGraph state machine and SQLite database without GOOGLE_API_KEY.

How interrupt(), Command, and SqliteSaver fit together

According to the LangGraph interrupts documentation, calling interrupt() pauses a node, saves the current state through the attached checkpointer, and waits for a later call: "When you're ready to continue, you resume execution by re-invoking the graph using Command, which then becomes the return value of the interrupt() call from inside the node."

One version behavior caught my eye immediately in langgraph==1.2.24. Many older tutorials wrap graph.invoke() in a try/except block expecting a GraphInterrupt exception. In langgraph==1.2.24, graph.invoke() does not raise GraphInterrupt to the caller. Instead, it returns a normal dictionary with an "__interrupt__" key holding a list of Interrupt objects. Checking if "__interrupt__" in result: is all the caller needs to detect a pause.

Inside src/hitl_agent/graph.py, the conditional edge sends low-risk tickets straight to execute_action and high-risk tickets to human_review:

APPROVAL_THRESHOLD = 50.0

    def route_after_triage(
        state: SupportState,
    ) -> Literal["execute_action", "human_review"]:
        action = state["action"]
        amount = float(state.get("refund_amount", 0.0))
        if action == "reply_only":
            return "execute_action"
        if action == "issue_refund" and amount < APPROVAL_THRESHOLD:
            return "execute_action"
        return "human_review"

When a ticket reaches human_review, the node builds a JSON-serializable review payload and passes it to interrupt(payload). Because human_review returns a Command with both goto and update, one node handles approving, editing, and rejecting cleanly without an extra router downstream:

    def human_review(
        state: SupportState,
    ) -> Command[Literal["execute_action", "handle_rejection"]]:
        payload = {
            "order_id": state["order_id"],
            "proposed_action": state["action"],
            "proposed_refund": state["refund_amount"],
            "reason": state["reason"],
            "draft_email": state["draft_email"],
            "allowed_decisions": ["approve", "edit", "reject"],
        }
        decision = interrupt(payload)
        ...
        if choice == "approve":
            return Command(
                goto="execute_action",
                update={
                    "approval_status": "approved",
                    "reviewer": reviewer,
                },
            )
        if choice == "edit":
            return Command(
                goto="execute_action",
                update={
                    "approval_status": "edited",
                    "reviewer": reviewer,
                    "refund_amount": edited_amount,
                    "draft_email": edited_email,
                },
            )
        if choice == "reject":
            return Command(
                goto="handle_rejection",
                update={
                    "approval_status": "rejected",
                    "reviewer": reviewer,
                    "rejection_reason": decision.get("reason", "Rejected by reviewer"),
                },
            )

Look at the edit branch. When a reviewer decides a sticky keyboard warrants a $60.00 partial refund instead of the $120.00 full refund Gemini proposed, update replaces refund_amount and draft_email before execute_action runs. The ledger never sees the unedited draft. On the reject branch, goto="handle_rejection" skips execute_action, calls Gemini 3.5 Flash Lite to draft a polite denial grounded in the reviewer's reason, and keeps ledger_entry as None.

To make pauses survive process exit, each CLI command opens SqliteSaver.from_conn_string(str(db_path)) inside a context manager and passes the same thread_id inside config = {"configurable": {"thread_id": args.thread}}. That thread_id links submit, inspect, and resume across completely separate Python processes.

Running pause, inspect, approve, edit, and reject live

I ran four live tickets through the CLI against gemini-3.5-flash-lite to watch every path work across separate terminal invocations.

First, a low-risk $18.00 wireless mouse refund (ORD-1001) cleared without pausing because $18.00 is below our $50.00 cap. It finished in 5.72 s using 394 tokens (259 input, 135 output):

uv run hitl-agent submit --thread live-low-1001 --order ORD-1001 --message 'My wireless mouse scroll wheel stopped working after 2 days. Please refund $18.'
STATUS: COMPLETED (thread_id=live-low-1001)
APPROVAL: auto_approved
ACTION: issue_refund | REFUND: $18.00
LLM_CALLS: 1 | TOKENS: {'input_tokens': 259, 'output_tokens': 135, 'total_tokens': 394}

Next came a high-risk $185.00 cracked monitor claim (ORD-4821). Submitting the ticket called Gemini 3.5 Flash Lite, routed into human_review, wrote the checkpoint to SQLite, printed the review payload, and exited in 4.86 s:

uv run hitl-agent submit --thread live-approve-4821 --order ORD-4821 --message 'My 27-inch IPS Monitor arrived with a cracked screen. Please refund $185.'
STATUS: PAUSED (thread_id=live-approve-4821)
INTERRUPT_ID: 945852f10b8b110babeb83a6966f882c
{
  "order_id": "ORD-4821",
  "proposed_action": "issue_refund",
  "proposed_refund": 185.0,
  ...
  "allowed_decisions": ["approve", "edit", "reject"]
}

At that point, the Python process had exited. Nothing stayed in memory, and ledger.json had no refund for ORD-4821. In a second process, I ran uv run hitl-agent inspect --thread live-approve-4821 to simulate a reviewer queue querying SQLite via graph.get_state(config) and graph.get_state_history(config). That took 0.75 s including CLI startup and returned NEXT_NODES: ('human_review',), CHECKPOINTS: 3, and PENDING_INTERRUPTS: 1.

In a third process, I approved the refund via Command(resume=...). Because triage_and_draft was already checkpointed, resuming never called Gemini again. It finished in 1.20 s (almost all CLI startup), kept LLM_CALLS: 1, and wrote the $185.00 refund to disk:

uv run hitl-agent resume --thread live-approve-4821 --decision approve --reviewer ops-lead
STATUS: COMPLETED (thread_id=live-approve-4821)
APPROVAL: approved by ops-lead
REFUND: $185.00 | LEDGER_WRITTEN: True
LLM_CALLS: 1 | TOKENS: {'input_tokens': 269, 'output_tokens': 143, 'total_tokens': 412}

Then I tested editing and rejecting on two more high-risk tickets.

For ORD-5102 (a $120.00 mechanical keyboard with two sticking keys), Gemini 3.5 Flash Lite proposed a full $120.00 refund and paused in 7.76 s. On resume, I passed --decision edit --amount 60.00 with a custom email offering a partial refund so the customer could keep the keyboard. That resumed in 1.27 s, logged REFUND: $60.00 | LEDGER_WRITTEN: True, stayed at LLM_CALLS: 1, and sent the edited email verbatim.

For ORD-6309 ($240.00 headphones delivered 47 days ago, outside our 30-day window), Gemini 3.5 Flash Lite flagged the policy gap, set proposed_action to escalate, and paused in 4.57 s. Resuming with --decision reject took 3.23 s because handle_rejection made a second Gemini call (LLM_CALLS: 2, 601 total tokens) to draft an empathetic denial grounded in the reviewer's note:

STATUS: REJECTED (thread_id=live-reject-6309)
APPROVAL: rejected by ops-lead
REFUND: $240.00 | LEDGER_WRITTEN: False
LLM_CALLS: 2 | TOKENS: {'input_tokens': 379, 'output_tokens': 222, 'total_tokens': 601}

Running uv run hitl-agent ledger afterward confirmed the audit trail: three refunds written (ORD-1001 for $18.00 auto-approved, ORD-4821 for $185.00 approved, and ORD-5102 for $60.00 edited), zero refund written for ORD-6309, and all four outgoing emails recorded with matching thread IDs.

Two traps I verified in code

Reading docs is helpful, but measuring a bug in tokens makes it stick. I wrote two targeted checks to verify the mistakes that break LangGraph HITL workflows most often.

The first trap is node re-execution on resume. The LangGraph interrupts documentation states it plainly: "On a later resume, the node still restarts from the beginning, so any code before interrupt() runs again." Put an LLM call or an HTTP POST above interrupt() inside the same node, and LangGraph runs that code once before pausing and a second time when Command(resume=...) resumes the node.

To measure the real cost against gemini-3.5-flash-lite, experiments/reexecution_trap.py sends the same ORD-4821 refund ticket through two minimal graphs wrapped in a CountingLLM tracker: naive_single_node (LLM call and interrupt() inside one node) versus separated_two_nodes (LLM call in triage_node, pause in approval_node). Here is the live output:

uv run python experiments/reexecution_trap.py
Re-execution trap comparison (mode=gemini-3.5-flash-lite)
  naive_single_node    | before_resume=1 | after_resume=2 | tokens=834 (in=538, out=296)
  separated_two_nodes  | before_resume=1 | after_resume=1 | tokens=408 (in=269, out=139)

The single-node version burned 834 tokens across 2 Gemini calls for one approval, versus 408 tokens across 1 call when the nodes were split. That is 2.04x the tokens (426 wasted tokens) per ticket. Worse, the second LLM call can draft slightly different wording than the email the human reviewer just approved. Keep every LLM call outside your interrupt() node, and place any irreversible side effect strictly after interrupt() returns.

The second trap is leaving InMemorySaver in place after prototyping. InMemorySaver holds checkpoints in process RAM. In tests/test_hitl_workflow.py, test_in_memory_saver_loses_state_on_new_instance pauses a thread, creates a fresh InMemorySaver to simulate a new process, and calls get_state(cfg): snap.values returns {} and snap.next returns (). Switching to SqliteSaver solves cross-process survival on a single machine. All 8 tests in uv run pytest -v passed in 3.78 s, and reproduce.sh passed in a clean clone with a scrubbed environment (clean_rerun.sh, exit 0).

Gemini 3.5 Flash Lite numbers and what I would ship

To test schema reliability and compare local SQLite overhead against live Gemini 3.5 Flash Lite latency, I ran experiments/benchmark.py --runs 5. Part 1 ran all five distinct tickets (ORD-1001, ORD-4821, ORD-5102, ORD-6309, ORD-7210) once. All five validated cleanly against TriageDecision with zero parsing errors and took the expected route (ORD-1001 and ORD-7210 auto-executed; the other three paused).

Part 2 ran the ORD-4821 pause, inspect, and approve cycle five times from scratch, opening a fresh SqliteSaver connection at every phase:

=== Part 2: 5-run Pause -> Inspect -> Approve benchmark (mode=gemini-3.5-flash-lite) ===
  run 1/5 (cold) | submit=2.00 s | inspect=7.4 ms | resume=14.4 ms | db=40.0 KiB | tokens=407 (in=269, out=138)
  ...
  run 5/5 (warm) | submit=1.41 s | inspect=8.2 ms | resume=16.4 ms | db=40.0 KiB | tokens=396 (in=269, out=127)

Summary (all runs, n=5):
  submit : median 5.78 s (range 1.41-6.70 s)
  inspect: median 8.0 ms (range 4.6-8.2 ms)
  resume : median 14.4 ms (range 13.6-17.9 ms)
  db_size: median 40.0 KiB (range 40.0-40.0 KiB)
  tokens : median 405 (range 396-415; in 269-269, out 127-146)
  warm submit (n=4): median 5.95 s (range 1.41-6.70 s)

One result contradicted my starting expectation. I expected the cold first run to be the slowest because of client setup and TLS negotiation. Instead, run 1 finished in 2.00 s while the four warm runs had a median of 5.95 s, and submit time swung 4.75x from 1.41 s to 6.70 s across identical prompts. Remote API jitter completely drowned out local startup on this machine.

Local SQLite overhead stayed tiny across all five runs. Median inspect took 8.0 ms (range 4.6-8.2 ms) and median resume took 14.4 ms (range 13.6-17.9 ms). Together, those 22.4 ms stay far below my 50 ms target and equal 0.39% of the 5.78 s median submit time. Each completed thread produced a 40.0 KiB SQLite database file, and token counts stayed steady at a median of 405 tokens (269 input tokens every run, 127-146 output tokens).

One minor wart appeared on Python 3.14.5: pytest printed 17 DeprecationWarning messages from langsmith referencing asyncio.iscoroutinefunction ahead of Python 3.16. Nothing failed, though strict warning filters will flag it until upstream updates.

On the strength of these runs, I would ship LangGraph's interrupt() and Command(resume=...) pattern with gemini-3.5-flash-lite today for single-service approval queues and internal ops tools, as long as interrupt() lives in its own node and low-risk traffic skips human review. I would not run SqliteSaver behind multiple concurrent containers. The LangGraph persistence documentation draws that exact boundary: "Use a persistent checkpointer for production: PostgresSaver: PostgreSQL with async support; SqliteSaver: Local file-based storage for development". Before letting a refund agent like this move real money, add PostgresSaver for concurrent workers, enforce reviewer authentication on your resume endpoint, and attach an idempotency key to record_refund so a retried payment call cannot issue a duplicate refund.

You can clone the complete Python project, tests, and benchmark scripts from the companion repository:

View Project on GitHub

Share this guide: