Skip to main contentSkip to footer
ExamplescriptintermediateRunnablehuman-approval

Human-in-the-Loop: Tool Call Approval

Key Facts

Level
intermediate
Runtime
Python • OpenAI API
Pattern
Inspectable flow with visible system boundaries
Interaction
Live sandbox • Script
Updated
14 March 2026

Navigate this example

High-level flow

How this example moves from input to execution and reviewable output
Human-in-the-Loop: Tool Call Approval -> Use bounded tools -> Pause for approval -> User request -> System execution -> Reviewable output

Start

Human-in-the-Loop: Tool Call Approval

Checkpoint

Use bounded tools

Outcome

Pause for approval

Why this page exists

This example is shown as both real source code and a product-facing interaction pattern so learners can connect implementation, UX, and doctrine without leaving the library.

Visual flowReal sourceSandbox or walkthroughMCP access
How should this example be used in the platform?

Use the sandbox to understand the experience pattern first, then inspect the source to see how the product boundary, model boundary, and doctrine boundary are actually implemented.

UX pattern: Inspectable flow with visible system boundaries
Establish trust through inspectability
Make hand-offs, approvals, and blockers explicit
Optimise for steering, not only initiating
Source references
Library entry
models-openai-10-human-in-the-loop-2-tool-call-approval
Source path
content/example-library/sources/models/openai/10-human-in-the-loop/2-tool-call-approval.py
Libraries
openai, python-dotenv
Runtime requirements
OPENAI_API_KEY
Related principles
Establish trust through inspectability, Make hand-offs, approvals, and blockers explicit, Optimise for steering, not only initiating

2-tool-call-approval.py

python
"""
Human-in-the-Loop: Tool Call Approval

This pattern intercepts tool calls before execution and asks
for user approval on sensitive actions.

Run: python 2-tool-call-approval.py
"""

import json
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

client = OpenAI()

# --------------------------------------------------------------
# Define Tools
# --------------------------------------------------------------

tools = [
    {
        "type": "function",
        "name": "get_balance",
        "description": "Get the current account balance",
        "parameters": {"type": "object", "properties": {}, "required": []},
    },
    {
        "type": "function",
        "name": "transfer_money",
        "description": "Transfer money to another account",
        "parameters": {
            "type": "object",
            "properties": {
                "to_account": {
                    "type": "string",
                    "description": "Recipient account name",
                },
                "amount": {"type": "number", "description": "Amount to transfer"},
            },
            "required": ["to_account", "amount"],
            "additionalProperties": False,
        },
        "strict": True,
    },
    {
        "type": "function",
        "name": "deposit_money",
        "description": "Deposit money into the account",
        "parameters": {
            "type": "object",
            "properties": {
                "amount": {"type": "number", "description": "Amount to deposit"},
            },
            "required": ["amount"],
            "additionalProperties": False,
        },
        "strict": True,
    },
]


# --------------------------------------------------------------
# Tool Implementations
# --------------------------------------------------------------

BALANCE = 1000.0


def get_balance() -> str:
    return f"Current balance: ${BALANCE:.2f}"


def transfer_money(to_account: str, amount: float) -> str:
    global BALANCE
    if amount > BALANCE:
        return "Error: Insufficient funds"
    BALANCE -= amount
    return f"Transferred ${amount:.2f} to {to_account}. New balance: ${BALANCE:.2f}"


def deposit_money(amount: float) -> str:
    global BALANCE
    BALANCE += amount
    return f"Deposited ${amount:.2f}. New balance: ${BALANCE:.2f}"


def execute_tool(name: str, args: dict) -> str:
    if name == "get_balance":
        return get_balance()
    elif name == "transfer_money":
        return transfer_money(**args)
    elif name == "deposit_money":
        return deposit_money(**args)
    return f"Unknown tool: {name}"


# --------------------------------------------------------------
# Human-in-the-Loop Functions
# --------------------------------------------------------------


def requires_approval(tool_name: str, args: dict) -> bool:
    if tool_name == "transfer_money":
        return args.get("amount", 0) > 100
    return False


def get_user_approval(tool_name: str, args: dict) -> bool:
    print("\n⚠️  Approval Required")
    print(f"Tool: {tool_name}")
    print(f"Arguments: {json.dumps(args, indent=2)}")
    response = input("\nApprove? (y/n): ").strip().lower()
    return response == "y"


# --------------------------------------------------------------
# Agent Loop with Tool Approval
# --------------------------------------------------------------


def run_with_approval(prompt: str) -> str:
    messages = [
        {"role": "user", "content": prompt},
    ]

    while True:
        response = client.responses.create(
            instructions=(
                "You are a helpful banking assistant. "
                "You can check balances, list contacts, and transfer money."
            ),
            model="gpt-4o",
            temperature=0,
            input=messages,
            tools=tools,
        )

        # Check if model wants to call tools
        tool_calls = [item for item in response.output if item.type == "function_call"]

        if not tool_calls:
            return response.output_text

        # Process each tool call
        for tool_call in tool_calls:
            args = json.loads(tool_call.arguments)

            # Human-in-the-loop: Check if approval is needed
            if requires_approval(tool_call.name, args):
                if not get_user_approval(tool_call.name, args):
                    messages.append(tool_call)
                    messages.append(
                        {
                            "type": "function_call_output",
                            "call_id": tool_call.call_id,
                            "output": "DENIED: User rejected this action",
                        }
                    )
                    continue

            # Execute approved tool
            result = execute_tool(tool_call.name, args)
            messages.append(tool_call)
            messages.append(
                {
                    "type": "function_call_output",
                    "call_id": tool_call.call_id,
                    "output": result,
                }
            )


# --------------------------------------------------------------
# Demo
# --------------------------------------------------------------

if __name__ == "__main__":
    print("=" * 60)
    print("Human-in-the-Loop: Tool Call Approval")
    print("=" * 60)

    # Multiple actions - check balance and small transfer
    print("\n--- Check Balance + Small Transfer ($50) ---")
    result = run_with_approval("Check my balance and transfer $50 to Alice")
    print(f"\nResult: {result}")

    # Deposit money
    print("\n--- Deposit ---")
    result = run_with_approval("Deposit $200 into my account")
    print(f"\nResult: {result}")

    # Large transfer - requires approval
    print("\n--- Large Transfer ($500) ---")
    result = run_with_approval("Transfer $500 to Bob for rent")
    print(f"\nResult: {result}")
What should the learner inspect in the code?

Look for the exact place where system scope is bounded: schema definitions, prompt framing, runtime configuration, and the call site that turns user intent into a concrete model or workflow action.

Look for output contracts and validation
Look for the exact execution call
Look for what the product could expose to the user
How does the sandbox relate to the source?

The sandbox should make the UX legible: what the user sees, what the system is deciding, and how the result becomes reviewable. The source then shows how that behavior is actually implemented.

Read the implementation summary.
Step through the user and system states.
Inspect the source code with the highlighted doctrine decisions in mind.
SandboxInspectable flow with visible system boundaries
Interaction walkthrough

Use the sandbox to step through the user-visible experience, the system work behind it, and the doctrine choice the example is making.

UX explanation

The sandbox explains what the user should see, what the system is doing, and where control or inspectability must remain explicit.

AI design explanation

The page turns raw source into a product-facing pattern: what the model is allowed to decide, what the product should expose, and where deterministic code or review should take over.

Interaction walkthrough

  1. 1Read the implementation summary.
  2. 2Step through the user and system states.
  3. 3Inspect the source code with the highlighted doctrine decisions in mind.

Prompt

Draft firstHuman checkpoint

Draft output

The draft appears here before any final action is taken.

Approval checkpoint

Approval only becomes available after the system exposes a draft.

Why approval is a product pattern

  • Establish trust through inspectability
  • Make hand-offs, approvals, and blockers explicit
  • Optimise for steering, not only initiating
Used in courses and paths

This example currently stands on its own in the library, but it still connects to the principle system and the broader example family.

Related principles

Runtime architecture

Use this example in your agents

This example is also available through the blueprint’s agent-ready layer. Use the For agents page for the public MCP, deterministic exports, and Claude/Cursor setup.

Define triggers, context, and boundaries before increasing autonomy
Make control, observability, and recovery explicit in the runtime
Choose the right operational patterns before delegating to workflows