08A.12 Human-in-the-Loop and Approval Gates as a Pattern

Agents & multimodalLesson 12 of 157,133 words9 parts
Module 08A · 0 of 15 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15

An agent that can read is a research assistant. An agent that can write (refund a customer, send an email, delete a record) is an employee, and employees get limits. This lesson teaches the limit that matters most: the approval gate, a piece of ordinary code that sits between "the model proposed a tool call" and "the tool ran". You will build a complete gate in plain Python: risk tiers, an approval queue, approve, edit, deny and defer decisions, a run that pauses and resumes from saved state, timeouts that fail closed, a tamper-evident audit trail, and a policy that approves the boring cases so humans only see the interesting ones. It sits right after the raw tool loop (08A.2) and before any framework: LangGraph interrupts (08F.12) and Inspect approvers (10B.15 Part 8, optional) are two ways to implement the pattern you build here.

What you'll learn

  • Human-in-the-loop (HITL) as a framework-neutral pattern: a gate between proposal and execution, not a feature of one library
  • Risk tiers as a function of the tool and its arguments, and how a tier decides who approves
  • The four human decisions, approve, edit, deny, defer, and what each one does to the run
  • Pause and resume with persisted state: why a pause must be "save and stop", not "wait in memory", and how to make resume safe to repeat
  • Timeouts and default-deny: what happens when nobody answers, and why a late "yes" must not work
  • Approval fatigue and the controls that keep humans reading: tiering, scoped grants, and measuring review behaviour
  • Approving by policy versus by human, and how to record which one happened
  • An audit trail that is complete and tamper-evident, so you can answer "who allowed this refund?"
  • How a gate is evaluated as a behaviour of the agent (Part 9)

What you don't need

  • API keys. Every sample uses a scripted fake model and runs offline with real output. Part 7 names the provider SDK features but runs no provider call.
  • Docker, databases or any service. The "queue" is a Python dict and the "database" is a dict of JSON strings.
  • Any agent framework. LangGraph and the OpenAI and Claude agent SDKs appear only in Part 7, after the plain version.

Setup

Python 3.11 or newer and nothing else; every file below uses only the standard library. As of 1 December 2026 this lesson needs no installs. Save each block under the file name in its first comment line, in one folder, and run python3 demo_hitl.py <scenario>.

The running example is the support assistant from Module 08A: it looks up orders, opens tickets and issues refunds. All tools are fake and local.


What you must be able to do after this lesson#

  • Build an approval gate in plain Python that classifies each proposed tool call into a risk tier from the tool and its arguments
  • Implement approve, edit, deny and defer decisions, and make an edited call pass through the same checks as any other call
  • Pause a run by saving plain JSON state, and resume it safely even when resume is triggered twice
  • Expire unanswered requests to deny, and reject any decision that arrives after the deadline
  • Record in a hash-chained audit log whether a policy rule or a named person allowed each call
  • Measure reviewer behaviour with approval rate, edit rate and decision time, and flag rubber-stamping
  • Test a gate with a scripted model, so that a policy edit that lets a write run without a human fails the check

Why this matters for an AI engineer#

The model decides what to try. Your code decides what is allowed to happen. The approval gate is where that second sentence becomes real. Teams that skip it learn about it from an incident: a refund loop, an email sent to the wrong customer, a deleted record. Teams that build it badly learn a different lesson: reviewers approve everything without reading, and the gate protects nothing.

You'll hear... You'll understand it after...
"The agent needs a human in the loop." Part 1
"Which actions need approval?" Part 2: Risk tiers
"Approve, edit or reject?" Part 3: The four decisions
"The run waits for the manager to click." Part 4: Pause and resume
"What if nobody answers?" Part 5: Timeouts and default-deny
"People just click approve on everything." Part 6: Approval fatigue and approving by policy
"Who approved this refund, and with which arguments?" Part 6.4: The audit trail
"LangGraph has interrupts, the OpenAI SDK has needs_approval." Part 7: Two implementations and the SDKs

Part 1: What a gate is and where it sits#

1.1 The pattern in one picture#

An approval gate is a checkpoint in the agent loop. The model proposes a tool call. Your code looks at the call, decides whether it may run, and only then runs it.

flowchart TD
    M["Model proposes a tool call"] --> T["Classify: tier of (tool, args)"]
    T --> P{"Policy verdict"}
    P -- "allow" --> X["Execute"]
    P -- "deny" --> E["Error result to the model"]
    P -- "ask" --> Q["Save state, put request in the queue, stop"]
    Q --> H["Human: approve / edit / deny / defer"]
    H -- "approve or edit" --> X
    H -- "deny or timeout" --> E
    X --> A["Audit event"]
    E --> A
    X --> R["Result back to the model, loop continues"]
    E --> R

08A.2, section 6.4 built the smallest version: an approver callback that returns approve, deny or defer. 08A.14, sections 2.4 and 2.5 described what a good approval looks like (exact call, scoped grants, edit before approve, expire to deny). This lesson extends both into a working design and runs it. It does not repeat their arguments for why agents need limits.

1.2 Three words that get mixed up#

Term Question it answers Who or what decides
Authentication Who is this user? Your login system
Authorization Is this user allowed to do this kind of thing? Permissions and scopes
Approval Should this exact proposed call run, now? A policy rule or a human

A support agent can be authorized to issue refunds in general and still need an approval for a 600 dollar refund today. Approval is about one concrete action with concrete arguments.

1.3 Why a gate is code, not a prompt#

A prompt is a request, and the model reads untrusted text all day, so anything it reads can argue with an instruction like "ask before you delete anything". Write the clause anyway: it makes the model expect the gate (04.5, section 6.5). But enforce the rule where the model cannot reach: in your dispatcher. A rule that exists only in the system prompt is a suggestion. 08A.7 shows the other half: tool results are untrusted too, so the gate must not trust a call just because it follows from a tool result.


Part 2: Risk tiers: which calls need a human#

This part extends the tier table of 08A.14, section 2.4 with the code that computes a tier from the tool and its arguments, and with the question of who approves.

2.1 Four tiers#

A risk tier is a label on a proposed call that says how bad its worst case is. 08A.14 section 2.4 owns the table and the reasoning. This lesson uses its four tiers under the names the code needs:

  • read: no state change (lookup_order). Allow.
  • reversible_write: changes state, easy to undo (create_ticket). Allow and log.
  • approval_write: affects a person or money, hard to undo (issue_refund, send_email). Ask, unless a policy rule covers it.
  • destructive: irreversible or very high impact (delete_customer, a refund over 500). Always ask, no standing grants.

The most important rule is in the code: the tier is a function of the tool and its arguments, not the tool name alone. A refund of 10 dollars and a refund of 600 dollars are the same tool and very different risks.

python
# hitl.py (part: basics)
from __future__ import annotations

import hashlib
import json
import statistics
from dataclasses import dataclass, asdict
from enum import Enum


class Tier(str, Enum):
    READ = "read"
    REVERSIBLE_WRITE = "reversible_write"
    APPROVAL_WRITE = "approval_write"
    DESTRUCTIVE = "destructive"


BASE_TIER = {
    "lookup_order": Tier.READ,
    "create_ticket": Tier.REVERSIBLE_WRITE,
    "issue_refund": Tier.APPROVAL_WRITE,
    "send_email": Tier.APPROVAL_WRITE,
    "delete_customer": Tier.DESTRUCTIVE,
}


def tier_of(tool: str, args: dict) -> Tier | None:
    """The tier is a function of (tool, args), not only the tool name."""
    tier = BASE_TIER.get(tool)
    if tier is None:
        return None  # unknown tool: the policy will deny it
    if tool == "issue_refund" and args.get("amount", 0) > 500:
        return Tier.DESTRUCTIVE  # big money: approval every time, no grants
    return tier


class Clock:
    """A fake clock so timeouts are testable and the output is stable."""

    def __init__(self, t: float = 1_000_000.0):
        self.t = t

    def now(self) -> float:
        return self.t

    def advance(self, seconds: float) -> None:
        self.t += seconds

Three details to notice. An unknown tool returns None, which the policy will turn into a denial (fail closed). The Clock class is a fake so that timeouts can be tested without waiting. And the tier lives in your code, not in the model's output: the model never gets to say "this one is safe".

2.2 Who approves#

Different tiers need different approvers. A short table is enough to start:

Tier Typical approver Why
read, reversible_write Nobody (policy) The cost of asking exceeds the risk
approval_write The person who owns the task: the end user in a chat, the on-call agent supervisor in a queue They have the context to judge
destructive A named role with authority (team lead, finance) Separation of duties: the person who asked is not the person who signs

Two design rules follow. First, the approver must be able to see what will happen, not only the tool name. "Allow issue_refund?" is useless. "Refund 84.50 on order A17 (paid 84.50, already refunded 0.00, delivered). Cannot be undone." is a decision. (How to lay that screen out, and where the autonomy dial puts each action, is the UX side: 13A.3 sections 4.1 and 4.4.) Second, for money and data, require separation of duties where you can: the user who triggered the run should not be the only one who can approve its most dangerous action, especially when the request itself might have been written by an attacker.


Part 3: The four decisions: approve, edit, deny, defer#

13A.3, section 4.3 builds the product-layer gate (states, TTL, audit trail). This part adds the framework-neutral queue with a defer decision, edited arguments and scoped grants, which the agent loop in Part 4 depends on.

A human looking at a proposed call has four useful answers.

Decision What happens Typical use
Approve The call runs exactly as proposed It is correct
Edit The call runs with the human's arguments instead Right action, wrong amount or recipient
Deny The call does not run; the model gets a clear error The action is wrong or not allowed
Defer The reviewer passes; the request stays pending "Not mine to decide" or "need more information"

Edit is the underrated one. It saves a round trip: instead of denying and hoping the model proposes a better amount, the human fixes it and the run continues. The rule that keeps edit safe: the edited call is what executes and what is audited, and it goes through the same checks as any call. Tools that declare strict schemas still validate the edited arguments, and idempotency keys must be computed from the final arguments (Part 4).

Deny needs care in what the model hears. A good denial result tells the model three things: the action did not happen, do not retry the same thing, and what to do next. You will see this in the run below.

Defer is a decision to not decide. It must not move the deadline (Part 5), or a reviewer could keep an unsafe request alive forever by deferring it.

Here is the approval queue that implements all four.

python
# hitl.py (part: queue)
@dataclass
class Request:
    id: str
    run_id: str
    tool: str
    args: dict
    tier: str
    summary: str
    created: float
    expires: float
    status: str = "pending"  # pending | approved | edited | denied | expired
    decided_by: str | None = None
    decided_at: float | None = None
    note: str = ""
    final_args: dict | None = None


class ApprovalQueue:
    """An in-memory inbox. In production this is a database table plus a UI."""

    def __init__(self, clock: Clock, audit: AuditLog, ttl_s: float = 900):
        self.clock, self.audit, self.ttl_s = clock, audit, ttl_s
        self.requests: dict[str, Request] = {}
        self.grants: list[dict] = []

    def submit(self, run_id, tool, args, tier, summary) -> Request:
        rid = f"req-{len(self.requests) + 1}"
        now = self.clock.now()
        req = Request(rid, run_id, tool, args, tier.value, summary, now, now + self.ttl_s)
        self.requests[rid] = req
        self.audit.add("approval_requested", req=rid, run=run_id, tool=tool, args=args, tier=tier.value)
        return req

    def pending(self) -> list[Request]:
        return [r for r in self.requests.values() if r.status == "pending"]

    def decide(self, rid, decision, by, note="", edited_args=None, grant_up_to=None):
        req = self.requests[rid]
        if req.status != "pending":
            raise ValueError(f"{rid} is already {req.status}")
        if self.clock.now() > req.expires:
            self._expire(req)
            raise ValueError(f"{rid} expired before the decision arrived")
        if decision not in ("approve", "edit", "deny"):
            raise ValueError("decision must be approve, edit or deny (use defer() to pass)")
        req.status = {"approve": "approved", "edit": "edited", "deny": "denied"}[decision]
        req.decided_by, req.decided_at, req.note = by, self.clock.now(), note
        req.final_args = (edited_args if decision == "edit" else req.args) if decision != "deny" else None
        if grant_up_to is not None and decision != "deny":
            self.grants.append({"run": req.run_id, "tool": req.tool, "max_amount": grant_up_to,
                                "uses_left": 3, "expires": self.clock.now() + 3600, "by": by})
        self.audit.add("approval_decided", req=rid, decision=req.status, by=by,
                       original_args=req.args, final_args=req.final_args, note=note)
        return req

    def defer(self, rid, by):
        """Pass on it. The request stays pending and its deadline does NOT move."""
        self.audit.add("approval_deferred", req=rid, by=by)

    def expire_due(self) -> list[str]:
        out = []
        for req in self.pending():
            if self.clock.now() > req.expires:
                self._expire(req)
                out.append(req.id)
        return out

    def _expire(self, req: Request) -> None:
        req.status, req.decided_by, req.decided_at = "expired", "system:timeout", self.clock.now()
        self.audit.add("approval_expired", req=req.id, default="deny")

    def find_grant(self, run_id, tool, amount):
        for g in self.grants:
            if (g["run"], g["tool"]) == (run_id, tool) and amount <= g["max_amount"] \
                    and g["uses_left"] > 0 and self.clock.now() <= g["expires"]:
                return g
        return None

Read decide closely. It refuses a decision on a request that is not pending, and it refuses a decision that arrives after the deadline. Both checks matter: they stop a double click from approving twice and stop a "yes" that arrives next morning from running a stale action.


Part 4: Pause and resume with persisted state#

This part turns the approver hook of 08A.2, section 6.4 into a runnable agent that stops and restarts from saved state. 08F.12 shows the same idea with LangGraph's checkpointer.

4.1 Save and stop#

The simplest gate blocks on input(). It works on your laptop and nowhere else. A reviewer may take four minutes or four days, a process may restart, and a web server cannot hold a request open that long. The pattern that survives production is save and stop:

  1. The loop reaches a call that needs approval.
  2. It writes the run's state to storage, creates the request, and returns. No thread or process waits.
  3. Later, a decision arrives. A new process loads the saved state and continues from the pending call.

08A.2 section 6.4 warned that its AgentResult.state is in-process and not serialisable, and said to persist the trajectory (tool, args, decision, result) and rebuild the conversation on resume. That is exactly what the code below does: the state is a plain dictionary of JSON values. LangGraph does the same with a checkpointer (08F.12 part 1); Part 7 shows how.

4.2 The policy#

Before the loop, the piece that decides allow, deny or ask.

python
# hitl.py (part: policy)
@dataclass
class Verdict:
    kind: str  # allow | ask | deny
    rule: str
    reason: str


class Policy:
    """Decides whether a proposed call may run, needs a human, or is refused.
    It is plain code. Nothing the model writes can change it."""

    def __init__(self, queue: ApprovalQueue):
        self.queue = queue

    def evaluate(self, run_id: str, tool: str, args: dict, ctx: dict) -> Verdict:
        tier = tier_of(tool, args)
        if tier is None:
            return Verdict("deny", "unknown-tool", f"{tool!r} is not in the registry")  # fail closed
        if tier in (Tier.READ, Tier.REVERSIBLE_WRITE):
            return Verdict("allow", f"tier-{tier.value}", "low-risk tier")
        if tool == "issue_refund" and tier == Tier.APPROVAL_WRITE:
            if args["amount"] <= 25 and ctx["auto_refunds"] < 2:
                return Verdict("allow", "refund-small-v1", "refund <= 25.00 and fewer than 2 auto refunds this run")
            grant = self.queue.find_grant(run_id, tool, args["amount"])
            if grant:
                grant["uses_left"] -= 1
                return Verdict("allow", "session-grant", f"granted by {grant['by']} up to {grant['max_amount']}")
        return Verdict("ask", f"tier-{tier.value}", "needs a human decision")

Four behaviours live here and each matters. Unknown tools are denied. Reads and reversible writes pass. A small refund passes by a named rule with a counter, so a model cannot slice a large refund into many small ones: after two automatic refunds the third goes to a human. And a human-created grant is checked, scoped to a run, tool, amount and time (more in Part 6).

4.3 The agent: a loop that can stop and restart#

python
# hitl.py (part: agent)
STORE_ORDERS = {"A17": {"total": 84.50, "refunded": 0.0, "status": "delivered"}}


class World:
    """The fake outside world: a refund gateway that also dedupes by key."""

    def __init__(self):
        self.refund_log: list[tuple] = []
        self.seen_keys: dict[str, dict] = {}
        self.tickets: list[dict] = []

    def run_tool(self, run_id: str, tool: str, args: dict) -> dict:
        key = hashlib.sha256(f"{run_id}|{tool}|{json.dumps(args, sort_keys=True)}".encode()).hexdigest()[:10]
        if key in self.seen_keys:  # idempotency: same final call, same answer, no second effect
            return {**self.seen_keys[key], "replayed": True}
        if tool == "lookup_order":
            result = {"order_id": args["order_id"], **STORE_ORDERS[args["order_id"]]}
        elif tool == "issue_refund":
            self.refund_log.append((args["order_id"], args["amount"]))
            result = {"status": "refunded", "order_id": args["order_id"], "amount": args["amount"]}
        elif tool == "create_ticket":
            self.tickets.append(args)
            result = {"status": "ticket_created", "ticket": f"T-{len(self.tickets)}"}
        else:
            result = {"error": f"no implementation for {tool}"}
        self.seen_keys[key] = result
        return result


def describe(call: dict, state: dict) -> str:
    """Show the human WHAT WILL HAPPEN, using facts the run already fetched."""
    order = next((s["result"] for s in reversed(state["trajectory"])
                  if s["call"]["tool"] == "lookup_order"), {})
    if call["tool"] == "issue_refund":
        return (f"Refund ${call['args']['amount']:.2f} on order {call['args']['order_id']} "
                f"(paid ${order.get('total', '?')}, already refunded ${order.get('refunded', '?')}, "
                f"status {order.get('status', '?')}). Cannot be undone.")
    return f"{call['tool']} {call['args']}"


class Agent:
    def __init__(self, model, policy, queue, audit, store, world):
        self.model, self.policy, self.queue = model, policy, queue
        self.audit, self.store, self.world = audit, store, world

    def start(self, run_id: str, task: str) -> dict:
        state = {"run_id": run_id, "task": task, "trajectory": [], "status": "running",
                 "pending_request": None, "pending_call": None, "auto_refunds": 0, "answer": None}
        self.store[run_id] = json.dumps(state)  # state is plain JSON: it survives a restart
        return self.advance(run_id)

    def _execute(self, state, call, approved_by):
        result = self.world.run_tool(state["run_id"], call["tool"], call["args"])
        self.audit.add("executed", run=state["run_id"], tool=call["tool"], args=call["args"],
                       approved_by=approved_by, result=result)
        return result

    def advance(self, run_id: str) -> dict:
        state = json.loads(self.store[run_id])  # always rebuild from the saved copy
        if state["status"] == "completed":
            return state  # resuming a finished run is a no-op
        while True:
            if state["pending_request"]:
                req = self.queue.requests[state["pending_request"]]
                if req.status == "pending":
                    break  # still waiting; nothing in memory holds a worker
                call = state["pending_call"]
                state["pending_request"], state["pending_call"] = None, None
                if req.status in ("approved", "edited"):
                    call = {"tool": call["tool"], "args": req.final_args}
                    result = self._execute(state, call, f"human:{req.decided_by}")
                else:
                    why = "timed out" if req.status == "expired" else "was denied by a reviewer"
                    result = {"error": "not_approved",
                              "message": f"The action {why}. Do not retry it. Offer to escalate to a person."}
                    self.audit.add("blocked", run=run_id, tool=call["tool"], status=req.status)
                state["trajectory"].append({"call": call, "result": result})
                continue
            action = self.model(state)
            if action["type"] == "final":
                state["status"], state["answer"] = "completed", action["text"]
                break
            call = {"tool": action["tool"], "args": action["args"]}
            verdict = self.policy.evaluate(run_id, call["tool"], call["args"], state)
            self.audit.add("proposed", run=run_id, tool=call["tool"], args=call["args"],
                           verdict=verdict.kind, rule=verdict.rule)
            if verdict.kind == "allow":
                if verdict.rule == "refund-small-v1":
                    state["auto_refunds"] += 1
                result = self._execute(state, call, f"policy:{verdict.rule}")
            elif verdict.kind == "deny":
                result = {"error": "denied_by_policy", "message": verdict.reason}
                self.audit.add("blocked", run=run_id, tool=call["tool"], status="policy_deny")
            else:
                req = self.queue.submit(run_id, call["tool"], call["args"],
                                        tier_of(call["tool"], call["args"]), describe(call, state))
                state.update(pending_request=req.id, pending_call=call, status="awaiting_approval")
                break
            state["trajectory"].append({"call": call, "result": result})
        if state["status"] != "completed" and not state["pending_request"]:
            state["status"] = "running"
        if state["pending_request"]:
            state["status"] = "awaiting_approval"
        self.store[run_id] = json.dumps(state)
        return state

The important lines are at the top of advance: it always rebuilds from the saved JSON, so whether it is the first call or the fiftieth, and whether the process is the same or new, the behaviour is identical. Notice if state["status"] == "completed": return state. That makes resume safe to repeat, which matters because resume is triggered by things that retry: webhooks, button double clicks, queue redelivery.

4.4 Watching it work#

First, the helpers every scenario shares: a scripted model, a function that builds the whole world, and a printer for the audit trail.

python
# demo_hitl.py (excerpt)
def refund_model(amount):
    """A scripted 'model': look up the order, ask for a refund, then react to the result."""
    def model(state):
        t = state["trajectory"]
        if len(t) == 0:
            return {"type": "tool", "tool": "lookup_order", "args": {"order_id": "A17"}}
        if len(t) == 1:
            return {"type": "tool", "tool": "issue_refund", "args": {"order_id": "A17", "amount": amount}}
        last = t[-1]["result"]
        if len(t) == 2 and "error" in last:
            return {"type": "tool", "tool": "create_ticket",
                    "args": {"title": "Refund needs a person", "order_id": "A17"}}
        if "error" in last:
            return {"type": "final", "text": "I could not refund this myself, so I opened a ticket for a person."}
        return {"type": "final", "text": f"Done. {json.dumps(last)}"}
    return model
python
# demo_hitl.py (excerpt)
def world(amount, ttl_s=900):
    clock, audit = Clock(), AuditLog()
    queue = ApprovalQueue(clock, audit, ttl_s)
    store: dict[str, str] = {}
    w = World()
    return clock, audit, queue, store, w, Agent(refund_model(amount), Policy(queue), queue, audit, store, w)
python
# demo_hitl.py (excerpt)
def show_audit(audit):
    for e in audit.events:
        extra = {k: v for k, v in e.items() if k not in ("seq", "kind", "prev", "hash")}
        print(f"  {e['seq']:>2} {e['kind']:<19} {json.dumps(extra)}")
    print("  chain intact:", audit.verify())

Now the easy case: a small refund approved by policy, no human at all. The scripted model looks up the order and asks for a refund of 19.99.

python
# demo_hitl.py (excerpt)
def small():
    clock, audit, queue, store, w, agent = world(19.99)
    state = agent.start("run-1", "Refund order A17")
    print("status:", state["status"], "| refunds sent:", w.refund_log, "| human involved:", bool(queue.requests))
    show_audit(audit)
Output · real, produced by running python3 demo_hitl.py small6 lines
status: completed | refunds sent: [('A17', 19.99)] | human involved: False
   0 proposed            {"run": "run-1", "tool": "lookup_order", "args": {"order_id": "A17"}, "verdict": "allow", "rule": "tier-read"}
   1 executed            {"run": "run-1", "tool": "lookup_order", "args": {"order_id": "A17"}, "approved_by": "policy:tier-read", "result": {"order_id": "A17", "total": 84.5, "refunded": 0.0, "status": "delivered"}}
   2 proposed            {"run": "run-1", "tool": "issue_refund", "args": {"order_id": "A17", "amount": 19.99}, "verdict": "allow", "rule": "refund-small-v1"}
   3 executed            {"run": "run-1", "tool": "issue_refund", "args": {"order_id": "A17", "amount": 19.99}, "approved_by": "policy:refund-small-v1", "result": {"status": "refunded", "order_id": "A17", "amount": 19.99}}
  chain intact: True

Look at the approved_by field: policy:tier-read and policy:refund-small-v1. The audit trail says which rule allowed each call. That is the difference between "no one approved this" and "the policy approved this under rule refund-small-v1".

Now the main scenario. A refund of 84.50 needs a human. The reviewer waits four minutes, passes once (defer), then edits the amount to 40.00. In the middle, we throw the agent object away and build a new one, to prove the saved state is enough.

python
# demo_hitl.py (excerpt)
def pause_edit_resume():
    clock, audit, queue, store, w, agent = world(84.50)
    state = agent.start("run-2", "Refund order A17")
    print("status:", state["status"])
    print("saved state is", len(store["run-2"]), "bytes of JSON; pending request:", state["pending_request"])
    req = queue.pending()[0]
    print("reviewer sees:", req.summary)
    clock.advance(240)  # the reviewer takes four minutes
    # --- the process restarts here: a brand-new Agent object, only `store` and `queue` survive ---
    agent2 = Agent(refund_model(84.50), Policy(queue), queue, audit, store, w)
    print("resume while still pending ->", agent2.advance("run-2")["status"])
    queue.defer(req.id, "dana")
    queue.decide(req.id, "edit", "dana", note="goodwill amount only", edited_args={"order_id": "A17", "amount": 40.0})
    state = agent2.advance("run-2")
    print("status:", state["status"], "| answer:", state["answer"])
    print("refunds sent:", w.refund_log)
    again = agent2.advance("run-2")  # a second resume (a retried webhook, a double click)
    print("second resume status:", again["status"], "| refunds sent:", w.refund_log)
    show_audit(audit)
Output · real, python3 demo_hitl.py pause_edit_resume15 lines
status: awaiting_approval
saved state is 395 bytes of JSON; pending request: req-1
reviewer sees: Refund $84.50 on order A17 (paid $84.5, already refunded $0.0, status delivered). Cannot be undone.
resume while still pending -> awaiting_approval
status: completed | answer: Done. {"status": "refunded", "order_id": "A17", "amount": 40.0}
refunds sent: [('A17', 40.0)]
second resume status: completed | refunds sent: [('A17', 40.0)]
   0 proposed            {"run": "run-2", "tool": "lookup_order", "args": {"order_id": "A17"}, "verdict": "allow", "rule": "tier-read"}
   1 executed            {"run": "run-2", "tool": "lookup_order", "args": {"order_id": "A17"}, "approved_by": "policy:tier-read", "result": {"order_id": "A17", "total": 84.5, "refunded": 0.0, "status": "delivered"}}
   2 proposed            {"run": "run-2", "tool": "issue_refund", "args": {"order_id": "A17", "amount": 84.5}, "verdict": "ask", "rule": "tier-approval_write"}
   3 approval_requested  {"req": "req-1", "run": "run-2", "tool": "issue_refund", "args": {"order_id": "A17", "amount": 84.5}, "tier": "approval_write"}
   4 approval_deferred   {"req": "req-1", "by": "dana"}
   5 approval_decided    {"req": "req-1", "decision": "edited", "by": "dana", "original_args": {"order_id": "A17", "amount": 84.5}, "final_args": {"order_id": "A17", "amount": 40.0}, "note": "goodwill amount only"}
   6 executed            {"run": "run-2", "tool": "issue_refund", "args": {"order_id": "A17", "amount": 40.0}, "approved_by": "human:dana", "result": {"status": "refunded", "order_id": "A17", "amount": 40.0}}
  chain intact: True

Check what happened. The run paused with 395 bytes of JSON saved. The reviewer saw a summary with the order facts, not a bare tool name. A resume while the request was still pending changed nothing. After the edit, exactly one refund went out, for 40.00, not the 84.50 the model proposed. The second resume was a no-op. The audit trail kept both the original and the final arguments, so a later reader can see that a person changed the amount.

4.5 Deny: what the model hears#

python
# demo_hitl.py (excerpt)
def deny():
    clock, audit, queue, store, w, agent = world(84.50)
    agent.start("run-3", "Refund order A17")
    queue.decide(queue.pending()[0].id, "deny", "dana", note="outside policy window")
    state = agent.advance("run-3")
    print("status:", state["status"])
    print("answer:", state["answer"])
    print("tool results the model saw:")
    for s in state["trajectory"]:
        print("  ", s["call"]["tool"], "->", json.dumps(s["result"]))
    print("refunds sent:", w.refund_log, "| tickets:", len(w.tickets))
Output · real, python3 demo_hitl.py deny7 lines
status: completed
answer: Done. {"status": "ticket_created", "ticket": "T-1"}
tool results the model saw:
   lookup_order -> {"order_id": "A17", "total": 84.5, "refunded": 0.0, "status": "delivered"}
   issue_refund -> {"error": "not_approved", "message": "The action was denied by a reviewer. Do not retry it. Offer to escalate to a person."}
   create_ticket -> {"status": "ticket_created", "ticket": "T-1"}
refunds sent: [] | tickets: 1

The model saw a result that said the action was denied, not to retry, and to offer escalation. A scripted model reacts by opening a ticket; a real model usually does something similar when the message is clear. Compare with a vague "Error: denied", which tends to make a model try the same call again with slightly different arguments.


Part 5: Timeouts and default-deny#

The rule (expire to deny) is stated in 08A.14, section 2.5. This part enforces it in code and shows a late approval failing.

5.1 Every request needs an ending#

If nobody answers, one of two things eventually happens: the run hangs forever holding a slot, or the request expires with a defined outcome. Only the second is acceptable. The outcome must be deny. This is called fail closed: when the system cannot tell whether an action is allowed, it does not do it. 08A.14 section 2.5 states the rule; the code below enforces it in two places.

  1. A sweeper (expire_due) runs on a timer and marks overdue requests expired.
  2. decide itself checks the deadline, so a late click cannot slip through between sweeper runs.
python
# demo_hitl.py (excerpt)
def timeout():
    clock, audit, queue, store, w, agent = world(84.50, ttl_s=900)
    agent.start("run-4", "Refund order A17")
    req = queue.pending()[0]
    clock.advance(901)  # nobody answered within 15 minutes
    print("sweeper expired:", queue.expire_due())
    try:
        queue.decide(req.id, "approve", "dana")
    except ValueError as e:
        print("late approval rejected:", e)
    state = agent.advance("run-4")
    print("status:", state["status"], "| refunds sent:", w.refund_log, "| tickets:", len(w.tickets))
    print("answer:", state["answer"])
Output · real, python3 demo_hitl.py timeout4 lines
sweeper expired: ['req-1']
late approval rejected: req-1 is already expired
status: completed | refunds sent: [] | tickets: 1
answer: Done. {"status": "ticket_created", "ticket": "T-1"}

Here the sweeper ran first, so the late approval was rejected as "already expired". If the sweeper had not run yet, decide would have refused it with "expired before the decision arrived". Either way the refund never happened, and the model received the denial message and opened a ticket for a person.

5.2 Choosing the time#

There is no single right timeout. Think in three numbers:

  • Time to answer: how long a person can reasonably take. Interactive chat: minutes. Back-office queue: hours.
  • Time before the world changes: a refund approved next week may no longer be valid (the order status, the customer, the policy may have changed). Re-check preconditions on resume, not only at proposal time.
  • Time the run may hold resources: with save-and-stop it holds none, which is the whole point.

5.3 Where the deadline clock runs#

Notice that defer does not extend the deadline. If it did, a request could live forever. Deadlines should only move on an explicit policy decision, for example "escalate to the team lead and give them another 30 minutes", which is a new request in the audit trail, not a silent extension.


Part 6: Approval fatigue and approving by policy#

Deep-dive

This part extends 13A.3, sections 4.5 and 4.7 with code: scoped grants, a policy-versus-human label, a hash-chained audit log and review metrics.

6.1 Why people stop reading#

Imagine a reviewer who sees 200 requests a day. By the second week they click approve in two seconds without reading, and your gate protects nothing. This is approval fatigue, the most common way real approval systems fail. 13A.3 section 4.5 covers the failure modes and the review-queue design, 13A.3 section 4.7 covers standing approvals, and 08A.14 section 6.4 names the problem. The controls this lesson implements are: ask less (tier aggressively), ask better (show the facts and the blast radius, Part 2.2), scope grants (6.3), measure the reviewers (6.5), and seed canary requests that should be denied (use test requests, never real harm).

6.2 Approving by policy versus by human#

There are two kinds of approvers and the audit log must say which one acted.

Approved by policy Approved by human
Speed Instant Seconds to days
Consistency Same input, same answer Varies with the person and the hour
Judgment Only what you encoded Can notice the odd case
Failure mode A rule that is too wide Fatigue, or being talked into it
Audit label policy:<rule-name> with a version human:<user id>

The policy in Part 4.2 uses a rule named refund-small-v1. The version suffix is not decoration: when you change a limit, you want the audit trail to show which version approved an old refund. Treat policy as code: review it, test it (Part 9), and version it. 14A.6 covers keeping policy and risk classes as managed artefacts across a whole organisation.

6.3 Grants, unknown tools and tampering#

python
# demo_hitl.py (excerpt)
def grant_and_policy():
    clock, audit, queue, store, w, _ = world(0)
    agent = Agent(two_refunds, Policy(queue), queue, audit, store, w)
    agent.start("run-5", "Refund A17 in two parts")
    queue.decide(queue.pending()[0].id, "approve", "dana", grant_up_to=50)  # approve AND grant up to 50
    state = agent.advance("run-5")
    print("status:", state["status"], "| refunds sent:", w.refund_log)
    print("human requests:", len(queue.requests), "(the second refund rode on the grant)")
    print("rules that approved each call:",
          [e["approved_by"] for e in audit.events if e["kind"] == "executed" and e["tool"] == "issue_refund"])
    print("unknown tool verdict:", Policy(queue).evaluate("r", "wire_transfer", {}, {"auto_refunds": 0}))
    big = Policy(queue).evaluate("run-5", "issue_refund", {"order_id": "A17", "amount": 900}, {"auto_refunds": 0})
    print("900.00 refund verdict:", big)
    audit.events[1]["args"] = {"order_id": "A99"}  # someone edits an old event
    print("chain intact after editing an old event ->", audit.verify())
Output · real, python3 demo_hitl.py grant_and_policy6 lines
status: completed | refunds sent: [('A17', 40.0), ('A17', 30.0)]
human requests: 1 (the second refund rode on the grant)
rules that approved each call: ['human:dana', 'policy:session-grant']
unknown tool verdict: Verdict(kind='deny', rule='unknown-tool', reason="'wire_transfer' is not in the registry")
900.00 refund verdict: Verdict(kind='ask', rule='tier-destructive', reason='needs a human decision')
chain intact after editing an old event -> False

Four results in a few lines. One human decision plus a grant let the second refund run with no second request (session-grant in the audit). A tool that is not in the registry is denied outright. A refund of 900 is classified destructive and asks every time, because grants do not apply to that tier. And editing an old audit event is detectable, which leads to the last piece.

6.4 The audit trail#

An approval system without a record is a rumour. The audit trail answers "who allowed what, when, with which arguments, and what happened". Four properties make it useful:

  • Complete: every proposed call, every verdict, every decision (including denials, deferrals and expiries), every execution. 08A.14 section 7.4 lists the same requirement.
  • Specific: the original and final arguments, the rule or person, and the run id that links to a trace (A7 covers audit logs and session replay).
  • Append-only: events are never edited. The class in this lesson goes one step further with a hash chain: each event includes the hash of the previous one, so changing an old event breaks every later hash.
  • Retained according to your obligations (check with your own compliance people; this lesson does not set numbers).
python
# hitl.py (part: audit)
class AuditLog:
    """Append-only, hash-chained: editing an old event breaks every later hash."""

    def __init__(self):
        self.events: list[dict] = []

    def add(self, kind: str, **data) -> None:
        prev = self.events[-1]["hash"] if self.events else "genesis"
        body = {"seq": len(self.events), "kind": kind, **data}
        digest = hashlib.sha256((prev + json.dumps(body, sort_keys=True)).encode()).hexdigest()[:10]
        self.events.append({**body, "prev": prev, "hash": digest})

    def verify(self) -> bool:
        prev = "genesis"
        for e in self.events:
            body = {k: v for k, v in e.items() if k not in ("prev", "hash")}
            digest = hashlib.sha256((prev + json.dumps(body, sort_keys=True)).encode()).hexdigest()[:10]
            if e["prev"] != prev or e["hash"] != digest:
                return False
            prev = e["hash"]
        return True

A hash chain inside the same database that an attacker could rewrite is only tamper-evident if you also ship the latest hash somewhere the attacker cannot reach (a write-once store or an external log). Treat it as the idea, not the finished control.

6.5 Measuring reviewers#

The metrics function at the end of hitl.py turns the queue into numbers.

python
# hitl.py (part: metrics)
def review_metrics(requests: list[Request]) -> dict:
    """Numbers that tell you whether reviewers are still reading."""
    decided = [r for r in requests if r.status in ("approved", "edited", "denied")]
    waits = [r.decided_at - r.created for r in decided]
    approved = [r for r in decided if r.status in ("approved", "edited")]
    rate = len(approved) / len(decided)
    median = statistics.median(waits)
    return {"decided": len(decided), "approval_rate": round(rate, 2),
            "edit_rate": round(sum(r.status == "edited" for r in decided) / len(decided), 2),
            "median_seconds": median,
            "rubber_stamp_risk": rate >= 0.98 and median < 5}
python
# demo_hitl.py (excerpt)
def fatigue():
    clock, audit = Clock(), AuditLog()
    queue = ApprovalQueue(clock, audit)
    def day(n_requests, wait_s, deny_every, label):
        reqs = []
        for i in range(n_requests):
            r = queue.submit("r", "send_email", {"i": i}, Tier.APPROVAL_WRITE, "email")
            clock.advance(wait_s)
            decision = "deny" if deny_every and i % deny_every == 0 else "approve"
            queue.decide(r.id, decision, "dana")
            reqs.append(r)
        print(label, review_metrics(reqs))
    day(20, 45, 5, "week 1 (read each one):  ")
    day(200, 2, 0, "week 6 (queue is huge): ")
Output · real, python3 demo_hitl.py fatigue2 lines
week 1 (read each one):   {'decided': 20, 'approval_rate': 0.8, 'edit_rate': 0.0, 'median_seconds': 45.0, 'rubber_stamp_risk': False}
week 6 (queue is huge):  {'decided': 200, 'approval_rate': 1.0, 'edit_rate': 0.0, 'median_seconds': 2.0, 'rubber_stamp_risk': True}

In week 1 the reviewer read each request, took 45 seconds and denied one in five. In week 6, with a flooded queue, they approved 100 percent at 2 seconds each. Both numbers are synthetic, but the shape is the real one, and the flag is a cheap alarm: when it fires, the fix is almost never "tell people to try harder". It is Part 6.1 items 1 to 3.


Part 7: The same pattern in LangGraph and the provider SDKs#

Reference

You now have the plain version. Every framework that offers "human in the loop" implements some subset of it. Reading them gets much easier when you can name the pieces.

Piece in this lesson LangGraph (08F.12) OpenAI Agents SDK Claude Agent SDK
Gate between proposal and execution interrupt() inside a node or tool needs_approval on a tool can_use_tool callback, rules and permission modes
Pause with saved state Checkpointer plus thread id result.to_state() then state.to_json() The callback can stay pending; a PreToolUse hook can return defer so the process exits and resumes later
Decision Command(resume=...) state.approve(item) or state.reject(item) PermissionResultAllow(updated_input=...) or PermissionResultDeny(message=...)
Edit Resume with new arguments Re-run with changed input (your code) updated_input carries the edited arguments
Default-deny You write it Callable rules fail closed when arguments are malformed dontAsk mode turns any prompt into a denial

The OpenAI and Anthropic details below were checked against their official docs on 1 December 2026 and may change; check the pages linked in Further resources before relying on a name.

7.1 LangGraph: interrupts and a checkpointer#

LangGraph's interrupt() pauses a node, the checkpointer saves the state, and Command(resume=value) continues on the same thread id. That is the "save and stop" pattern with the storage built in. 08F.12 section 3.1 shows approve or reject, and 08F.12 part 4 lists the rules (do not wrap interrupt() in a bare except, keep side effects before an interrupt idempotent, only serialisable values). Those rules exist for the same reason as everything in Part 4 here: the node restarts from its first line when it resumes. Use LangGraph when you already have a graph and want the checkpointing; use the plain version when you own a small loop and want to read every line.

7.2 OpenAI Agents SDK#

A tool marked needs_approval (True, or an async function of the arguments) ends the run with result.interruptions. You resolve each one with state.approve(...) or state.reject(...) and call Runner.run(agent, state) again; the RunState serialises with to_json(). Per the SDK docs (checked 1 December 2026), callable rules fail closed when arguments are missing or malformed, and approval does not guarantee exactly-once execution, so tools with external side effects still need idempotency keys (Part 4.3). 08F.2, section 2.5 walks through this flow with a keyless model of the runner and compares it with 08A.2's approver hook.

7.3 Claude Agent SDK#

Allow and deny rules and permission modes decide the easy cases, and a can_use_tool callback decides the rest. Per the docs (checked 1 December 2026), the callback returns PermissionResultAllow(updated_input=...), which is how "approve with edits" works, or PermissionResultDeny(message=...), whose message is what the model sees. A call approved by an earlier step never reaches the callback, so checks that must always run belong in a PreToolUse hook. dontAsk mode turns every would-be prompt into a denial, a good fit for unattended runs (08A.13), and a hook can return defer so the process exits and resumes later, which is the save-and-stop pattern. 08F.3, section 2.5 and Part 5 show the callback and the permission stack.

7.4 Raw API loops#

If you write the loop yourself on OpenAI Responses or Anthropic Messages, the gate is exactly the code in this lesson: the model returns tool calls, your dispatcher runs the policy, and an "ask" ends the loop with the pending call saved. Nothing about approval is a provider feature at that level. 08A.2 part 2 shows both providers' loops; insert the gate between "parse tool calls" and "execute".


Reference

8.1 A gate design checklist#

  • Every tool has a tier, and the tier can depend on arguments.
  • Unknown tools are denied.
  • The policy is code, versioned, and not influenced by model text.
  • Approvers see the resolved facts and the irreversible nature of the call.
  • Edit is supported, and edited calls re-enter the checks.
  • Pause is save-and-stop; state is plain data; resume is safe to repeat.
  • Tools are idempotent below the gate; keys use the final arguments.
  • Every request has a deadline; expiry means deny; late decisions are rejected.
  • Preconditions are re-checked on resume.
  • The audit trail records proposals, verdicts, decisions, edits, expiries, and the rule or person.
  • Reviewer behaviour is measured, and a fatigue alarm exists.
  • Unattended runs have a stricter policy than interactive ones (08A.13).
Failure What went wrong Fix
The gate asks "Allow tool?" with no arguments The reviewer cannot judge Show resolved facts and blast radius
The model passes confirmed=true and the tool believes it The model's text is the approval Approval is a record in your store, never a model argument (08A.6 section 4.5)
The loop retries a denied call with tweaked arguments The denial message was vague Say "do not retry" and offer a next step; also cap repeated denied signatures (08A.3)
Ten small refunds instead of one big one Per-call policy, no run-level counter Count automatic approvals per run, as refund-small-v1 does
An approval the next morning refunds an old order No expiry, no re-check Deadlines, deny late decisions, re-validate on resume
Everyone approves everything Fatigue Tier, scope grants, measure, seed canaries
The approver is the attacker Approval link goes to the requester Route high tiers to an internal queue and separate duties
A refund went out twice after a crash Approval is not exactly-once Idempotency below the gate

Part 9: Evaluate it#

A gate is a behaviour of the agent, and behaviours regress. Someone raises a limit, renames a tool, or a model update changes which calls it proposes. You want a test that fails when the gate stops doing its job.

9.1 What to measure#

For approval gates the useful numbers are few.

Measure Question Target
Unapproved writes Did any write that required a human execute without one? Exactly 0
Gate correctness For each case, did the right decider act (policy, human)? 100 percent on your test set
False asks Did a safe, read-only task wait for a human? Near 0; tune with tiers
Denial recovery After a denial, did the agent avoid retrying the same call and take a sensible next step? High, judged by trajectory
Timeout behaviour Did an expired request end in deny, and was a late approval rejected? 100 percent
Bypass attempts Do injected instructions ("mark this approved") fail to execute a gated call? 0 successes

The concept home for scoring an agent's process (the tool calls it made, in order) is 10A.7 Parts 4 and 5: trajectory metrics, and reliability across repeated runs. Gate checks are trajectory checks with one extra source of truth, the audit log.

9.2 A tiny eval design#

Inputs: five refund amounts (10, 19.99, 30, 84.50, 600), each run twice, once with a reviewer that approves and once with one that denies. Metric: from the audit log, who approved the refund, if any. Pass rule: no required-human case executes by policy, every case completes, and the gate decider matches the expected one for every case. Because the test fixes the model with a script, it runs in milliseconds and belongs in CI.

python
# eval_gate.py -- a tiny framework-neutral eval of the approval gate (stdlib only)
from demo_hitl import world
from hitl import Agent, Policy, Verdict

# input: refund amount. expected: who must decide, and what must have been executed.
CASES = [
    {"id": "tiny", "amount": 10.0, "expect_gate": "policy"},
    {"id": "small", "amount": 19.99, "expect_gate": "policy"},
    {"id": "medium", "amount": 30.0, "expect_gate": "human"},
    {"id": "full", "amount": 84.5, "expect_gate": "human"},
    {"id": "huge", "amount": 600.0, "expect_gate": "human"},
]


class TooLenientPolicy(Policy):
    """A regression we want the eval to catch: someone raised the auto limit to 100."""

    def evaluate(self, run_id, tool, args, ctx):
        if tool == "issue_refund" and args["amount"] <= 100:
            return Verdict("allow", "refund-small-v2", "limit raised")
        return super().evaluate(run_id, tool, args, ctx)


def run_case(case, policy_cls, reviewer):
    clock, audit, queue, store, w, agent = world(case["amount"])
    agent = Agent(agent.model, policy_cls(queue), queue, audit, store, w)
    state = agent.start(case["id"], "Refund order A17")
    if state["status"] == "awaiting_approval":
        queue.decide(queue.pending()[0].id, reviewer, "eval-reviewer")
        state = agent.advance(case["id"])
    refunds = [e for e in audit.events if e["kind"] == "executed" and e["tool"] == "issue_refund"]
    who = "none"
    if refunds:
        who = "human" if refunds[0]["approved_by"].startswith("human:") else "policy"
    return {"gate_ok": (who == case["expect_gate"]) if reviewer == "approve" else (who == "none" or case["expect_gate"] == "policy"),
            "executed_without_human_when_required":
                bool(refunds) and refunds[0]["approved_by"].startswith("policy:") and case["expect_gate"] == "human",
            "denied_then_retried": reviewer == "deny" and len(refunds) > 0 and who == "human",
            "completed": state["status"] == "completed"}


def evaluate(policy_cls, label):
    rows = [(c, run_case(c, policy_cls, r)) for c in CASES for r in ("approve", "deny")]
    leaks = list(dict.fromkeys(c["id"] for c, res in rows if res["executed_without_human_when_required"]))
    gate = sum(res["gate_ok"] for _, res in rows) / len(rows)
    done = sum(res["completed"] for _, res in rows) / len(rows)
    verdict = "PASS" if not leaks and gate == 1.0 and done == 1.0 else "FAIL"
    print(f"{label:<14} gate_correct={gate:.0%} completed={done:.0%} unapproved_writes={leaks or 'none'} -> {verdict}")


evaluate(Policy, "current policy")
evaluate(TooLenientPolicy, "lenient policy")
Output · real, python3 eval_gate.py2 lines
current policy gate_correct=100% completed=100% unapproved_writes=none -> PASS
lenient policy gate_correct=60% completed=100% unapproved_writes=['medium', 'full'] -> FAIL

The second row is the point. A single edit that raised the automatic limit from 25 to 100 passes a "does the happy path work?" test and fails this one, because refunds of 30 and 84.50 now execute without a human. This eval is deliberately framework-neutral, and it is a bespoke harness: when you need many cases, judged trajectories or model-based grading, move to a framework. Which one is a general decision, covered in 13A.8 (the decision-frameworks lesson).

9.3 Evaluating with the Module 10A and 10B toolkit#

Read these in order. The concept lessons come first because they tell you what to measure; the tool lessons tell you how to run it.


Common misconceptions#

  • "Human-in-the-loop means a person reviews everything." It means defined decision points. Reviewing everything produces fatigue and a gate that protects nothing.
  • "The system prompt can enforce approval." A prompt shapes behaviour; only code enforces a rule. The gate lives in the dispatcher.
  • "Approval makes the action safe." It makes it authorized. The action can still be wrong, still fail, still run twice. Idempotency and validation stay necessary.
  • "A confirmed argument is a human approval." It is the model saying it is sure. Approval is a record your code creates when a human decides.
  • "Pausing means holding a thread open." In production a pause is saved state and a return. Nothing waits.
  • "If no one answers, the agent can proceed." Silence is not consent. Expire to deny.
  • "Policy approval is the same as no approval." It is approval by a versioned rule that you can audit, test and change. The label in the audit log is what keeps it honest.
  • "This is a LangGraph feature." LangGraph, the OpenAI Agents SDK, the Claude Agent SDK and Inspect all implement the same pattern. You can build it in plain Python in an afternoon.

Key takeaways#

  • An approval gate is code between a proposed tool call and its execution. The model proposes; your policy decides.
  • Tier calls by tool and arguments. Unknown tools are denied. Destructive calls ask every time and take no standing grants.
  • Offer approve, edit, deny and defer. Make edits re-enter the checks, and make denial messages tell the model not to retry.
  • Pause is save-and-stop. Store plain JSON state, make resume idempotent, re-validate preconditions, and compute idempotency keys from the final arguments.
  • Timeouts fail closed. Every request has a deadline, expiry means deny, late approvals are rejected, and defer does not move the deadline.
  • Fight approval fatigue by asking less, asking better, scoping grants and measuring reviewer behaviour.
  • Record who or what approved: policy:<rule>@version or human:<id>, with original and final arguments, in an append-only, tamper-evident log.
  • LangGraph interrupts and Inspect approvers are implementations. The OpenAI and Claude agent SDKs offer the same pieces under different names.
  • Test the gate: unapproved writes must be zero, and a policy edit should fail an eval before it reaches production.

Terms introduced in this lesson#

Term Meaning
Approval gate Code between a proposed tool call and its execution that allows, denies or asks a human
Human-in-the-loop (HITL) A design where defined decision points require a person's decision
Risk tier A label for a proposed call's worst case, computed from the tool and its arguments
Approve / edit / deny / defer The four reviewer decisions: run as is, run with changes, refuse, or pass without deciding
Save and stop Pausing by persisting state and returning, so nothing waits in memory
Fail closed When the answer is unknown, refuse; for approvals, expiry means deny
Default-deny The outcome applied when no one decides in time or the tool is unknown
Approval fatigue Reviewers approving without reading because they see too many requests
Grant A scoped, expiring pre-approval, such as "refunds up to 50 for this run, three uses"
Policy approval An allow decision made by a named, versioned rule instead of a person
Separation of duties The requester is not the only person who can approve a dangerous action
Hash-chained audit log An append-only log where each event includes the previous event's hash, so edits are detectable
Canary request A test request that should be denied, used to check reviewers are reading

Exercises#

  1. Add a tier rule. Make send_email to an address outside your company domain destructive, and inside it approval_write. Add a scenario that proves the external email always asks. Hint: extend tier_of to read args["to"]; add the check to demo_hitl.py and assert Policy.evaluate(...).kind == "ask" for both.
  2. Re-validate on resume. In Agent.advance, before executing an approved refund, re-run lookup_order and refuse if the order's refunded plus the amount exceeds the total. Show a scenario where another process refunds the order during the pause. Hint: mutate STORE_ORDERS["A17"]["refunded"] between start and the decision; return an error result and audit it as blocked.
  3. A second approver. Require two different humans for destructive calls. Change Request to hold a list of decisions and make decide refuse the same person twice. Hint: keep approvals: list[str], execute only when two distinct people approved, and let one denial end it.
  4. Escalation instead of silence. When a request expires, create a new request for the team lead with a 30 minute deadline instead of denying outright, and audit the link between the two. Hint: in _expire, submit a new Request with parent=req.id; the run keeps waiting only if the new request is pending.
  5. Canaries. Add a function that injects a request designed to be denied (an email to a made-up address) into the queue, and extend review_metrics to report the canary approval rate. Hint: tag requests with canary=True in the audit event; the alarm fires if any canary is approved.
  6. Break the eval. Write a TooStrictPolicy that asks for everything and add a "false ask" metric for read-only cases to eval_gate.py. Show the current policy passes and the strict one fails. Hint: add a read-only case with expect_gate: "none" and count requests in queue.requests.

Check yourself#

  1. What is the difference between authorization and approval?
  2. Why must the risk tier be computed from the tool and its arguments rather than the tool name?
  3. Name the four reviewer decisions and say what each does to the run.
  4. Why is "save and stop" better than blocking on input() in production?
  5. What does a safe resume need to be true about the saved state, and about the tool layer?
  6. A reviewer clicks approve the morning after the request was created. What should happen, and which two mechanisms make it happen?
  7. Why does defer not move the deadline?
  8. List three engineering controls against approval fatigue.
  9. What is the difference between policy:refund-small-v1 and human:dana in the audit log, and why is the version in the name?
  10. Your eval passes on the happy path, but a policy change let 30.00 refunds run without a human. Which metric catches it, and what should its target be?

Further resources#


← 08A.11 — Reflection, Parallel Fan-Out and Agent-as-a-Tool | Module 08A overview | 08A.13 — Background and Long-Running Agents →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close