How to add human approval to an AI agent

A working pattern for any agent framework: ask before the risky call, wait for a person, act only on an explicit yes. With code in Python and TypeScript.

· 7 min read

Telling a model “ask me before you delete anything” is a request, not a control. It works until the model decides the deletion is obviously fine, or a document it read tells it otherwise. Human approval that holds has to sit in the code path of the action itself: the function that deletes asks first, and does nothing without a yes.

The pattern is the same in every framework. Ask before the risky call, wait for a person, act only on an explicit yes, and say afterwards what happened. This guide builds it in Python with plain HTTP, so it fits LangChain, the OpenAI Agents SDK, CrewAI or your own loop, and shows where each choice matters.

1. Choose what needs a person

Not every tool call. Reads and drafts can run freely; a person is for what is hard to take back:

  • Money moving: payments, refunds, purchases, subscriptions.
  • Messages leaving: email, posts, replies to customers.
  • Data going: deletions, overwrites, bulk updates.
  • Access changing: permissions, keys, settings, deploys.

If you would be unhappy to learn about it afterwards, it needs a yes before. The human-in-the-loop article goes through the line in more detail.

2. Ask with a summary a person can decide on

The person deciding reads one sentence, often on a phone. Put the facts in it: what, how much, to whom, how many.

Weak
Clean up old files
Strong
Delete 214 files in /exports/2024, 1.8 GB in total
Weak
Issue refund
Strong
Refund €49.00 to ana@example.com for order 1182

Give the action a stable, dotted name such as files.delete or payment.refund. Rules match on it later, so the routine requests can be answered without anyone.

3. Wait without hammering

A person may take a minute or an hour. Instead of polling every second, pass wait_seconds: the call stays open until someone decides or 30 seconds pass. A loop over that costs about two calls a minute. Give the request a time limit that suits the task with ttl_seconds. When it runs out the request expires and the answer is no.

import os
import requests

API_URL = os.environ.get("VARIANTGATE_API_URL", "https://api.variantgate.com")
HEADERS = {"Authorization": f"Bearer {os.environ['VARIANTGATE_KEY']}"}


def ask_person(action: str, summary: str, **fields) -> dict:
    """Ask for approval and wait until the request is no longer pending."""
    body = {"agent": "file-janitor", "action": action, "summary": summary,
            "wait_seconds": 30, **fields}
    response = requests.post(f"{API_URL}/v1/requests", headers=HEADERS,
                             json=body, timeout=40)
    response.raise_for_status()
    request = response.json()
    while request["status"] == "pending":
        response = requests.get(f"{API_URL}/v1/requests/{request['id']}",
                                headers=HEADERS, params={"wait_seconds": 30},
                                timeout=40)
        response.raise_for_status()
        request = response.json()
    return request


def report(request_id: str, outcome: str, note: str = "") -> None:
    """Say how the approved action went: "succeeded" or "failed"."""
    response = requests.post(f"{API_URL}/v1/requests/{request_id}/outcome",
                             headers=HEADERS, json={"outcome": outcome, "note": note},
                             timeout=10)
    response.raise_for_status()

4. Act on allowed, and nothing else

Here is a tool that deletes old exports. The check is inside it, so no prompt can reach the deletion without a yes:

from approvals import ask_person, report


def delete_old_exports(folder: str) -> str:
    files = list_files(folder, older_than_days=365)
    size = sum(f.size for f in files) / 1e9
    answer = ask_person(
        "files.delete",
        f"Delete {len(files)} files in {folder}, {size:.1f} GB in total",
        details={"folder": folder, "first": [f.name for f in files[:5]]},
        ttl_seconds=3600,
    )
    if answer["allowed"] is not True:
        return f"Nothing deleted: it was not approved ({answer['status']})."
    if answer["changed"]:
        # A person approved other wording; this code can only do what it asked.
        report(answer["id"], "failed", "not done: approved only with changes")
        return f"Nothing deleted. Approved instead: {answer['approved_summary']}"
    for f in files:
        f.delete()
    report(answer["id"], "succeeded", f"{len(files)} files deleted")
    return f"Deleted {len(files)} files."

Compare allowed, never status. A request can be approved and still not allowed, because a person paused every agent after approving it.

  • On a no, return a sentence. The model can tell the user what happened. Raising often makes it try another way to do the same thing.
  • On an error, do nothing. raise_for_status stops the tool if the service cannot be reached. An agent that acts when it cannot ask has no approval step at all.
  • Do what was approved. The deletion uses the same list of files the summary described, not a fresh one. If the person approved changed wording (changed is true), this code cannot do that version, so it does nothing and says so.

5. Say what happened

An approval says an action may happen. The outcome says whether it did. Reporting it once, with a note such as a message id or an error, puts both on the record: who allowed it, and what came of it.

In TypeScript

The TypeScript client wraps all five steps in one call: guard asks, waits, runs your function only on a yes and reports the outcome. Without it, the same helper is twenty lines of fetch, shown on the OpenAI Agents SDK page.

Keep the questions rare

After a week you will know which requests you always approve. Answer those in advance with a rule: always allow calendar.*, always allow payment.refund up to €20, never allow files.delete from the research agent’s key. People keep reading what reaches them only if little does.