# Human in the loop for AI agents (/docs/human-in-the-loop)

**Human in the loop (HITL)** means an AI agent stops before an action that matters, asks a person, and only continues with their answer. Agent frameworks give you the pause. CallHuman gives you the question: it phones the person, reads your message, and returns what they chose (`approve`, `reject` or any option you define) as structured data.

<Callout title="Hear what the approver hears">
A short message, the options, an answer by keypress or voice. [Listen to a real approval call](/demo).
</Callout>

## The pattern [#the-pattern]

1. **Pause.** The agent reaches a step it shouldn't take alone: a refund, a deploy, deleting data, sending money, emailing every customer.
2. **Ask.** It calls the approver with one request: what it wants to do, with exact amounts and names, and the options.
3. **Resume.** The answer comes back as `option_id`. The agent continues on `approve` and stops on anything else.

```json title="POST /v1/calls"
{
  "to": "+34600111222",
  "message": "Your support agent wants to refund 1,240 euros to Acme Ltd for invoice 2231.",
  "options": [
    { "id": "approve", "label": "Approve", "reply": "Approved. Going ahead." },
    { "id": "reject", "label": "Reject", "reply": "Rejected. Nothing will happen." }
  ],
  "webhook_url": "https://example.com/hooks/callhuman",
  "metadata": { "run_id": "run_8812" }
}
```

```json title="The answer (webhook or GET /v1/calls/{id})"
{
  "id": "call_x9f2k",
  "status": "answered",
  "option_id": "approve",
  "option_label": "Approve",
  "answer_method": "keypad",
  "answer_transcript": null,
  "metadata": { "run_id": "run_8812" }
}
```

There is no AI on the phone: the person hears your text and your options, nothing else. The answer is always one of your option `id`s or `null`, so your code never has to interpret free text.

## Phone or chat? [#phone-or-chat]

Chat and email approvals work well when the answer can wait. Use a phone call when it can't, or when the approver isn't in your tools.

| | Phone call (CallHuman) | Slack, email or an approval inbox |
|---|---|---|
| Gets an answer now | The phone rings | When someone looks |
| Reaches customers and people outside your team | Anyone with a phone | Needs the app or an account |
| Nights and weekends | Rings until picked up, with retries | Waits in a channel |
| Long context (diffs, documents) | Keep it to a sentence or two | Better |

More detail in [CallHuman vs Slack & email approvals](/docs/comparisons/slack-email-approvals).

## Design rules [#design-rules]

- **Fail closed.** Only `option_id: "approve"` means yes. `not_answered`, `failed`, `canceled` and `option_id: null` (they hung up before choosing) all mean no, or a call to a second approver.
- **Say exactly what will happen.** Amounts, names, IDs. The approver decides only from what they hear, and can't scroll back.
- **Never call twice for the same decision.** Send an `Idempotency-Key` (for example `refund-2231`) so a retried request returns the same call instead of ringing again.
- **Wait in the right place.** A call usually ends within a minute, but with retries a missed call can take longer to reach a final status. In a tool that blocks while it waits, set `retries: 0` (or a short `retry_delay_seconds`). For long waits, use the [webhook](/docs/webhooks) and resume the run from there.
- **Keep secrets out of storage.** If the message must include a code or account number, wrap it in `[[…]]`: it is spoken but never stored. See [Redacting sensitive data](/docs/redacting-sensitive-data).
- **Find the run again.** Put your run, thread or ticket ID in `metadata`. It comes back unchanged in the result.

## MCP agents (Claude, ChatGPT, Cursor, VS Code) [#mcp-agents-claude-chatgpt-cursor-vs-code]

No code. Add our [MCP server](/docs/mcp) and the agent gets a `call_human` tool that places the call **and waits for the answer** (up to `wait_seconds`; if the call takes longer, it continues with `get_call` instead of calling again). Tell the agent when to use it:

```text title="Instruction for your agent"
Before any refund over 500 euros, use call_human to ask Laura (+34600111222)
to approve it, with the amount, the customer and the order number.
Only refund if she chooses Approve. If she rejects or doesn't answer, don't refund
and tell me why.
```

## n8n [#n8n]

The [CallHuman node](/docs/n8n) calls, pauses the workflow while the phone rings and continues down **one output per option**, plus one for no answer. Put it between your AI Agent node and the step it guards:

1. **AI Agent** decides what to do (for example, which invoice to refund).
2. **CallHuman** (*Call and Wait for Answer*): *“Your agent wants to refund 1,240 euros to Acme Ltd…”* with **Approve** and **Reject**.
3. **Approve** → the refund node. **Reject** and **No answer** → stop and notify.

## LangGraph [#langgraph]

LangGraph pauses a graph with `interrupt()` and resumes it with `Command(resume=…)`. Place the call in one node and wait in the next: when a graph resumes, the interrupted node runs again from the top, so the call must not be in it. Your webhook handler resumes the thread with the answer.

```python title="graph.py"
import os
import requests
from langgraph.types import interrupt

API = "https://api.callhuman.es/v1/calls"
HEADERS = {"Authorization": f"Bearer {os.environ['CALLHUMAN_API_KEY']}"}

def request_approval(state, config):
    thread_id = config["configurable"]["thread_id"]
    requests.post(
        API,
        headers={**HEADERS, "Idempotency-Key": f"approval-{thread_id}"},
        json={
            "to": state["approver_phone"],
            "message": f"Your agent wants to {state['action']}.",
            "options": [
                {"id": "approve", "label": "Approve", "reply": "Approved. Going ahead."},
                {"id": "reject", "label": "Reject", "reply": "Rejected. Nothing will happen."},
            ],
            "webhook_url": "https://example.com/hooks/callhuman",
            "metadata": {"thread_id": thread_id},
        },
        timeout=10,
    ).raise_for_status()
    return {}

def wait_for_approval(state):
    option_id = interrupt({"waiting_for": "phone approval"})
    return {"approved": option_id == "approve"}

# builder.add_edge("request_approval", "wait_for_approval"), then compile
# with a durable checkpointer so the paused thread survives restarts.
```

```python title="webhook.py (FastAPI)"
import json
from fastapi import FastAPI, Request
from langgraph.types import Command

app = FastAPI()

@app.post("/hooks/callhuman")
async def callhuman_hook(request: Request):
    body = await request.body()
    verify_signature(body, request.headers["CallHuman-Signature"])  # see Webhooks
    call = json.loads(body)
    config = {"configurable": {"thread_id": call["metadata"]["thread_id"]}}
    graph.invoke(Command(resume=call["option_id"]), config)  # None if nobody chose
    return {"ok": True}
```

How to verify the signature: [Webhooks](/docs/webhooks#verify-the-signature).

## OpenAI Agents SDK and other tool-calling agents [#openai-agents-sdk-and-other-tool-calling-agents]

Make the risky action a tool that asks first. The agent can't skip the approval because the approval is inside the tool.

```python title="approval.py"
import os, time, requests

API = "https://api.callhuman.es/v1/calls"
HEADERS = {"Authorization": f"Bearer {os.environ['CALLHUMAN_API_KEY']}"}
FINAL = {"answered", "not_answered", "failed", "canceled"}

def ask_for_approval(phone: str, action: str, key: str) -> bool:
    """Phones the approver. True only if they choose Approve."""
    call = requests.post(API, headers={**HEADERS, "Idempotency-Key": key}, json={
        "to": phone,
        "message": f"Your agent wants to {action}.",
        "options": [
            {"id": "approve", "label": "Approve", "reply": "Approved. Going ahead."},
            {"id": "reject", "label": "Reject", "reply": "Rejected. Nothing will happen."},
        ],
        "retries": 0,  # this function blocks: end quickly if nobody picks up
    }, timeout=10).json()
    while True:
        time.sleep(5)
        call = requests.get(f"{API}/{call['id']}", headers=HEADERS, timeout=10).json()
        if call["status"] in FINAL:
            return call["option_id"] == "approve"
```

```python title="agent.py"
from agents import Agent, function_tool
from approval import ask_for_approval

@function_tool
def refund_invoice(invoice_id: str, amount: float) -> str:
    """Refund an invoice. A human approves it by phone first."""
    if not ask_for_approval("+34600111222", f"refund {amount} euros for invoice {invoice_id}", f"refund-{invoice_id}"):
        return "Not refunded: the approver rejected it or didn't answer."
    refund(invoice_id)
    return "Refunded."

agent = Agent(name="Billing", instructions="Handle refunds.", tools=[refund_invoice])
```

## Vercel AI SDK [#vercel-ai-sdk]

The same idea in TypeScript, with the `askForApproval` function from the [approval recipe](/docs/recipes/agent-approval):

```ts title="tools.ts"
import { tool } from "ai";
import { z } from "zod";
import { askForApproval } from "./approval";

export const refundInvoice = tool({
  description: "Refund an invoice. A human approves it by phone first.",
  inputSchema: z.object({ invoiceId: z.string(), amount: z.number() }),
  execute: async ({ invoiceId, amount }) => {
    const approved = await askForApproval({
      phone: "+34600111222",
      action: `refund ${amount} euros for invoice ${invoiceId}`,
    });
    if (!approved) return { refunded: false, reason: "Rejected or not answered" };
    await refund(invoiceId);
    return { refunded: true };
  },
});
```

On serverless platforms, keep the wait short (`retries: 0`) or switch to the webhook so the function doesn't time out.

## FAQ [#faq]

**What if nobody answers?** The call ends `not_answered` and your code treats it as a rejection. Or call a second approver with a new request.

**Can the approver answer by voice?** Yes. Depending on the project's [answer mode](/docs/options#keypress-or-voice), they press a key, say the option, or either. You get the same `option_id`, plus `answer_method`.

**Can the call say something I didn't write?** No. We read your message, your options and your replies. Nothing is generated during the call.

**Who can approve?** Anyone with a phone in a [supported country](/docs/phone-numbers#country-coverage-table): your team, a manager, the customer themselves. No app or account needed.

**Does every approval count against my plan?** Answered calls do. A call nobody picks up doesn't, unless voicemail picked up. See [What counts](/docs/limits-and-billing#what-counts).