Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Human-in-the-Loop Approval Gates

Recommended resources

Introduction

In our previous lesson, we constructed a robust set of output guardrails to ensure our agent's responses are structurally valid, well-formatted, and compliant with content policies. We built a system to block bad outputs. However, some of the most critical risks in agentic systems come not from invalid outputs, but from valid actions that have high-stakes, real-world consequences. An agent correctly formatting a request to delete a production database is far more dangerous than one producing malformed JSON.

This brings us to the focus of today's lesson: designing and implementing human-in-the-loop (HITL) approval gates. Our objective is to create a mechanism that can pause an agent's execution before it performs a high-stakes action, await explicit approval from a human operator, and then resume its work. This isn't just a simple if statement; it's a fundamental architectural pattern for managing stateful, long-running tasks that must survive pauses that could last minutes, hours, or even days. Given your background in distributed systems, you'll recognize this as a classic problem of durable execution and state management in an asynchronous environment.


The Design Philosophy of Approval Gates

The immediate objection to HITL is that it seems to defeat the purpose of automation. If a human must approve every step, have we not just built a very complicated email client? This is a valid concern, which is why the design philosophy behind approval gates is paramount.

Designing Approval Gates for Autonomous AI Agents

This article from Tian Pan provides an excellent engineering-focused perspective on approval gates, framing them as architectural interrupts rather than compliance checkboxes.

Please read the first three sections: Start with the introduction, "Most agent failures aren't explosions", which sets the stage for why gates are needed. Read the reframing of the purpose of gates: they should be rare, targeted, and load-bearing. Finally, study the section Classifying Actions. This introduces a practical three-tiered taxonomy for categorizing agent actions based on risk.

As the article argues, the key is to develop a clear taxonomy of your agent's capabilities. A simple, effective model is:

  1. AUTO: Low-stakes, reversible, or read-only actions. These can be executed without any human oversight. Examples include fetching data, reading a file, or generating a draft summary.
  2. LOG: Actions that are likely safe but are worth auditing. The agent proceeds autonomously, but a detailed record of the action is created for asynchronous review. Examples include sending a standard customer email or updating a non-critical CRM field.
  3. REQUIRE_APPROVAL: High-stakes, irreversible, or costly actions. The agent's execution must be paused until a human grants explicit permission. This is our focus today. Examples include processing a refund over a certain threshold, deleting customer data, or executing a financial transaction.

The decision of which category an action falls into can be based on static rules (e.g., any tool call named delete_records requires approval) or dynamic logic (e.g., a transfer_funds call requires approval only if amount > 1000).


The Core Architecture: Interrupt-Checkpoint-Resume

A standard, stateless web server process can't simply sleep() for 24 hours waiting for an email reply. The request would time out, and if the server restarted, the entire task state would be lost. To implement a true approval gate, we need a durable execution model. The pattern that solves this is interrupt-checkpoint-resume.

This diagram illustrates the interrupt-checkpoint-resume pattern. An agent's workflow is paused, its state is serialized to a durable database, and it waits indefinitely for an external command to resume execution. This is the core architecture we will implement.

This diagram illustrates the interrupt-checkpoint-resume pattern. An agent's workflow is paused, its state is serialized to a durable database, and it waits indefinitely for an external command to resume execution. This is the core architecture we will implement.

The flow is as follows:

  1. Interrupt: The agent's main loop determines that a proposed action (e.g., a tool call) requires human approval. Instead of executing the action, it halts its current execution path.
  2. Checkpoint: The agent serializes its entire current state—including the message history, any intermediate data, and the specific action awaiting approval—into a durable store, such as a database or a persistent key-value store. The task is now safely persisted.
  3. Resume: A human operator provides a decision (e.g., "approve" or "reject") through an external mechanism (a Slack bot, a web UI, a CLI command). This triggers a new process that loads the checkpointed state, applies the decision, and resumes the agent's execution from the exact point it was paused.

This model decouples the agent's execution from any single running process, making it resilient to server restarts, network failures, and long human-induced delays.

The following video provides an excellent high-level overview of this architecture in practice, showing how the different components of a modern application stack work together to enable HITL.

How to Build Human-in-the-Loop for AI Agents (Practical Guide)

This video from Dave Ebbelaar provides a practical guide to HITL, with clear diagrams of production architectures.

First, watch the walkthrough of the first production pattern, which uses Server-Sent Events (SSE) for a real-time chat application. Pay close attention to the role of the database as the state store that enables the connection to close and resume later. Next, review the second pattern for asynchronous back-end processes. Notice how the core logic remains the same, but the notification/approval channel changes to something like Slack or email. Finally, internalize the key concepts: deferred execution, state serialization, and stateless resume. These are the first principles of our design.


Implementing the Interrupt-Checkpoint-Resume Pattern

Now, let's build a simplified version of this architecture from scratch, honoring your preference for first-principles engineering. We'll simulate the durable store with local files, but the logic is directly transferable to a production database like PostgreSQL or Redis.

First, we need to define a structure for our checkpointed state. Pydantic is perfect for this. Our state must capture everything needed to resume the task.

import json
import uuid
from pydantic import BaseModel, Field
from typing import List, Dict, Any

# A Pydantic model representing the state we need to save.
class AgentCheckpoint(BaseModel):
    run_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    message_history: List[Dict[str, Any]]
    pending_action: Dict[str, Any] # The tool call awaiting approval
    status: str = "pending_approval"
    decision: str | None = None
    outcome: str | None = None

Next, we'll create a simple Checkpointer class to handle saving and loading these state objects. In a real system, this would interact with a database.

import os

CHECKPOINT_DIR = "checkpoints"

class FileCheckpointer:
    def __init__(self, base_dir: str = CHECKPOINT_DIR):
        self.base_dir = base_dir
        if not os.path.exists(self.base_dir):
            os.makedirs(self.base_dir)

    def save(self, checkpoint: AgentCheckpoint):
        filepath = os.path.join(self.base_dir, f"{checkpoint.run_id}.json")
        with open(filepath, 'w') as f:
            f.write(checkpoint.model_dump_json(indent=2))
        print(f"✅ Checkpoint saved for run_id: {checkpoint.run_id}")

    def load(self, run_id: str) -> AgentCheckpoint:
        filepath = os.path.join(self.base_dir, f"{run_id}.json")
        with open(filepath, 'r') as f:
            data = json.load(f)
        return AgentCheckpoint(**data)

    def update(self, run_id: str, updates: Dict[str, Any]):
        checkpoint = self.load(run_id)
        for key, value in updates.items():
            setattr(checkpoint, key, value)
        self.save(checkpoint)

Now, we define our tools, including a high-stakes one. We also create a policy to determine which tools require approval.

# --- Tool Definitions & Policy ---

def get_user_profile(user_id: str) -> Dict[str, Any]:
    """Retrieves a user's profile. A safe, read-only action."""
    print(f"Executing get_user_profile for user_id: {user_id}")
    # In a real app, this would query a database
    return {"user_id": user_id, "name": "Alex", "email": "alex@example.com"}

def process_refund(user_id: str, amount: float, reason: str) -> str:
    """Processes a refund for a user. A high-stakes action."""
    print(f"Executing process_refund for user_id: {user_id} with amount: {amount}")
    # In a real app, this would call a payment gateway API
    return f"Refund of ${amount} for user {user_id} processed successfully."

AVAILABLE_TOOLS = {
    "get_user_profile": get_user_profile,
    "process_refund": process_refund,
}

def requires_approval(tool_call: Dict[str, Any]) -> bool:
    """Policy to decide if a tool call needs approval."""
    if tool_call["function"]["name"] == "process_refund":
        args = json.loads(tool_call["function"]["arguments"])
        if args.get("amount", 0) > 100.0:
            return True
    return False

Finally, we modify our agent loop. When it encounters an action requiring approval, it will create a checkpoint and halt.

# --- Agent Execution Logic ---

checkpointer = FileCheckpointer()

# A mock function to simulate an LLM deciding to call a tool.
def get_llm_tool_call(message_history: List[Dict[str, Any]]) -> Dict[str, Any]:
    # In a real scenario, this is an actual LLM call.
    # We'll hardcode a response for demonstration.
    print("\n🤖 LLM is thinking...")
    return {
        "type": "tool_calls",
        "tool_calls": [{
            "id": "call_abc123",
            "type": "function",
            "function": {
                "name": "process_refund",
                "arguments": '{"user_id": "user-123", "amount": 250.50, "reason": "Defective product"}'
            }
        }]
    }

def run_agent_task(initial_prompt: str):
    """Main function to run the agent task."""
    message_history = [{"role": "user", "content": initial_prompt}]
    
    # 1. Agent thinks and decides on a tool call
    llm_response = get_llm_tool_call(message_history)
    tool_call = llm_response["tool_calls"][0]
    
    # 2. INTERRUPT: Check if approval is needed
    if requires_approval(tool_call):
        print(f"🚨 Action '{tool_call['function']['name']}' requires human approval.")
        
        # 3. CHECKPOINT: Create and save the state
        checkpoint = AgentCheckpoint(
            message_history=message_history,
            pending_action=tool_call
        )
        checkpointer.save(checkpoint)
        
        print("\n---")
        print("Agent execution paused. To resume, run the following command:")
        print(f"python resume.py --run-id {checkpoint.run_id} --decision [approve/reject]")
        print("---\n")
        return # Halt execution
    
    # This part would run if no approval was needed
    execute_tool(tool_call)

def resume_agent_task(run_id: str, decision: str):
    """Function to resume a paused task."""
    print(f"\nResuming task {run_id} with decision: {decision}...")
    
    # 4. RESUME: Load the checkpoint
    try:
        checkpoint = checkpointer.load(run_id)
    except FileNotFoundError:
        print(f"❌ Error: No checkpoint found for run_id: {run_id}")
        return

    if checkpoint.status != "pending_approval":
        print(f"⚠️ Warning: Task {run_id} is not pending approval (status: {checkpoint.status}).")
        return

    checkpointer.update(run_id, {"decision": decision})

    if decision == "approve":
        print("✅ Action approved. Executing...")
        tool_call = checkpoint.pending_action
        
        # Execute the originally planned action
        tool_name = tool_call["function"]["name"]
        tool_args = json.loads(tool_call["function"]["arguments"])
        tool_function = AVAILABLE_TOOLS[tool_name]
        result = tool_function(**tool_args)
        
        print(f"Tool execution result: {result}")
        checkpointer.update(run_id, {"status": "completed", "outcome": result})
    else:
        print("❌ Action rejected.")
        # Here, you could add logic to inform the LLM to re-plan
        checkpointer.update(run_id, {"status": "rejected", "outcome": "Human rejected action."})

# To run this, you would have a main script `run_task.py` and a `resume.py`.
# run_task.py:
# if __name__ == "__main__":
#     run_agent_task("Please process a refund for user-123 for $250.50 due to a defective product.")

# resume.py:
# import argparse
# if __name__ == "__main__":
#     parser = argparse.ArgumentParser()
#     parser.add_argument("--run-id", required=True)
#     parser.add_argument("--decision", required=True, choices=["approve", "reject"])
#     args = parser.parse_args()
#     resume_agent_task(args.run_id, args.decision)

This implementation, though simplified, contains all the essential components of a durable HITL system. It demonstrates the clean separation between the agent process that initiates the pause and the external process that triggers the resumption, with the file-based checkpoint acting as the durable state bridge between them.


Design Considerations for Production

A working implementation is only the first step. For a production-grade system, you must consider the human factors and failure modes.

Designing Approval Gates for Autonomous AI Agents

Let's revisit the article on approval gates to explore these crucial production considerations.

First, read the section on Async Approval in Practice. This discusses the critical problem of approval fatigue and the importance of designing informative approval requests. Next, study What Happens After Rejection. This is a vital point: rejection is not a failure state but a feedback signal that the agent must be able to handle gracefully, for example, by re-planning.

The key takeaways from these sections are:

  • Avoid Approval Fatigue: If operators are bombarded with trivial requests, they will start approving them blindly, creating a false sense of security. Your approval gates must be carefully calibrated to trigger only for genuinely high-stakes situations. Monitor approval rates; a gate with a 99% approval rate is likely too sensitive.
  • Design for Rejection: Rejection is not an endpoint. It's an input. The agent's workflow should be designed to receive a "reject" signal and use that information. Options include aborting the task, logging the failure for human review, or, most powerfully, feeding the rejection back into the model's context with a prompt to try a different approach.

Conclusion

Today, we've moved beyond simple validation to implement a sophisticated safety and control mechanism: the human-in-the-loop approval gate. We've seen that this is not a trivial feature but a core architectural pattern—interrupt-checkpoint-resume—that enables durable, long-running agentic tasks. By designing a clear action taxonomy and building the infrastructure for pausing and resuming, you can deploy agents that handle high-stakes operations safely and reliably.

Key Takeaways:

  • HITL is for valid but high-stakes actions, complementing the guardrails we built to block invalid outputs.
  • The core architectural pattern is interrupt-checkpoint-resume, which decouples task execution from any single process, enabling long pauses and resilience to failures.
  • State must be serialized and stored durably (checkpointing) whenever a pause is initiated.
  • Resumption is triggered by an external signal, which loads the state and continues the workflow.
  • Approval fatigue and rejection handling are critical design considerations for a production system. A rejection should be treated as a valuable feedback signal for the agent.

Preview of the Next Lesson:

Our current approval gate is binary: a human either approves or rejects the action. But what if the situation is merely ambiguous, and the agent needs guidance rather than a simple yes/no? In our next lesson, we will explore a more nuanced form of human oversight by designing an escalation policy that routes agent tasks to human operators based on confidence scores or risk levels, enabling true collaboration between the agent and its human counterparts.