Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Add human approval to agent actions

Pause risky tool calls, show the exact arguments, resume on approve or reject, then log and test it.

By Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

To add human approval to an agent, mark the risky tools, let the framework pause the run when the model calls one, show a person the exact tool name and arguments, and resume the same run with their decision. A rejection goes back to the model as the tool’s result, so the agent can tell the user what did not happen. Log every decision, default to “no”, and test that the gate holds without a model in the loop.

This tutorial adds that gate to the notes agent from Build your first agent in Python. It gives the agent a delete_note tool that always needs approval and a write_note tool that needs approval only when it would overwrite a note, then shows the same gate in TypeScript for the AI SDK version. Everything runs without an API key, because a scripted model stands in for the LLM. It was written against the OpenAI Agents SDK 0.25.0 and AI SDK 7.0.179, both checked on 21 November 2026.

Which calls need a person

Approval costs a person’s attention, so spend it where a wrong call is expensive or cannot be undone. Reading needs no approval: the folder guard in safe_path already limits what can be read. Overwriting needs it only when there is something to lose. Deleting needs it every time.

Tool What a bad call costs Rule
list_notes, read_note Nothing changes Run without asking
write_note to a new file A stray file you can delete Run without asking
write_note over an existing file Lost content Ask
delete_note Lost content, no undo Always ask

This is the practical answer to what OWASP calls excessive agency: an agent that can act beyond what its task needs. An approval gate leaves the model as careless as it was and makes the dangerous calls depend on a person.

1. Set up the project

Start a fresh folder with the same notes as the first tutorial, plus an old draft for the agent to delete:

mkdir notes-approval && cd notes-approval
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install openai-agents==0.25.0 pytest==9.2.0

mkdir notes
printf "# Deploy checklist\nRun migrations before the release. Rollback with git revert.\n" > notes/deploy.md
printf "# Onboarding\nNew starters get laptop access on day one.\n" > notes/onboarding.md
printf "# Old deploy draft\nSuperseded by deploy.md.\n" > notes/old-deploy-draft.md

pytest is for step 5, where you prove the rules hold.

2. Mark the risky tools

Create agent.py with the tools. The read-only tools are the ones from the first tutorial; the two new ones carry the approval rules:

# agent.py
import argparse
import asyncio
import json
from datetime import datetime, timezone
from pathlib import Path

from agents import (
    Agent,
    RunContextWrapper,
    RunHooks,
    Runner,
    ToolApprovalItem,
    function_tool,
    set_tracing_disabled,
)

NOTES_DIR = Path("notes").resolve()
AUDIT_LOG = Path("approvals.jsonl")


def safe_path(name: str) -> Path:
    """Resolve a note name inside NOTES_DIR and refuse anything outside it."""
    path = (NOTES_DIR / name).resolve()
    if path.parent != NOTES_DIR or path.suffix != ".md":
        raise ValueError(f"{name!r} is not a note in {NOTES_DIR.name}/")
    return path


# Read-only tools: no approval needed.
@function_tool
def list_notes() -> list[str]:
    """List the file names of all Markdown notes."""
    return sorted(p.name for p in NOTES_DIR.glob("*.md"))


@function_tool
def read_note(name: str) -> str:
    """Read one note in full.

    Args:
        name: The file name, for example "deploy.md".
    """
    return safe_path(name).read_text(encoding="utf-8")


# Risky tools: a person decides before they run.
@function_tool(needs_approval=True)
def delete_note(name: str) -> str:
    """Delete one note permanently.

    Args:
        name: The file name of the note to delete.
    """
    safe_path(name).unlink()
    return f"Deleted {name}."


async def overwrites_existing(_ctx: RunContextWrapper, params: dict, _call_id: str) -> bool:
    """Creating a new note is safe. Replacing an existing one needs a person."""
    try:
        return safe_path(params.get("name", "")).exists()
    except ValueError:
        return True  # cannot tell what it would touch: ask


@function_tool(needs_approval=overwrites_existing)
def write_note(name: str, text: str) -> str:
    """Create a note, or replace an existing note with new text.

    Args:
        name: The file name, for example "release.md".
        text: The full Markdown content of the note.
    """
    safe_path(name).write_text(text, encoding="utf-8")
    return f"Saved {name}."


class LogSteps(RunHooks):
    async def on_tool_start(self, context, agent, tool) -> None:
        print(f"-> {tool.name}")


agent = Agent(
    name="Notes assistant",
    instructions=(
        "You manage the user's Markdown notes. Use the tools to find, read, write or delete notes. "
        "If a person declines a tool call, do not retry it: tell the user it was not done."
    ),
    tools=[list_notes, read_note, delete_note, write_note],
)

needs_approval takes either True or an async function. The SDK calls the function with the run context, the parsed arguments and the call id, before the tool runs, and pauses the run if it returns True. Notice what overwrites_existing does when the name is invalid: it returns True. A rule that cannot decide should ask, not wave the call through. The SDK documents the same behaviour for arguments it cannot parse: it skips your function and requires manual approval.

The last sentence of the instructions matters too. Without it, a model whose delete was declined may try again with a slightly different argument, and the person gets asked twice.

3. Ask a person and resume the run

Add the approval loop to the bottom of agent.py:

def ask_human(item: ToolApprovalItem) -> bool:
    """Show the exact call and wait for a decision. Anything but 'y' is a no."""
    args = json.loads(item.arguments or "{}")
    print(f"\nApproval needed: {item.name} {json.dumps(args)}")
    return input("Approve? [y/N] ").strip().lower() == "y"


def record(item: ToolApprovalItem, approved: bool) -> None:
    """Append one line per decision, so you can audit who allowed what."""
    entry = {
        "at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "tool": item.name,
        "arguments": json.loads(item.arguments or "{}"),
        "call_id": item.call_id,
        "approved": approved,
    }
    with AUDIT_LOG.open("a", encoding="utf-8") as f:
        f.write(json.dumps(entry) + "\n")


async def run_with_approvals(task: str) -> str:
    result = await Runner.run(agent, task, max_turns=8, hooks=LogSteps())
    while result.interruptions:
        state = result.to_state()
        for item in result.interruptions:
            approved = ask_human(item)
            record(item, approved)
            if approved:
                state.approve(item)
            else:
                state.reject(item, rejection_message=f"A person declined {item.name}. Do not retry it.")
        result = await Runner.run(agent, state, max_turns=8, hooks=LogSteps())
    return result.final_output


async def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("task", nargs="?", default="Delete the old deploy draft.")
    parser.add_argument("--offline", action="store_true", help="use the scripted model, no API key")
    args = parser.parse_args()

    if args.offline:
        from fake_model import ScriptedModel

        set_tracing_disabled(True)  # nothing to send traces to without a key
        agent.model = ScriptedModel([
            ("call", "list_notes", {}),
            ("call", "delete_note", {"name": "old-deploy-draft.md"}),
            ("say", "Tool result: {last_output}"),
        ])
    print("\n" + await run_with_approvals(args.task))


if __name__ == "__main__":
    asyncio.run(main())

How the loop works:

  • When the model calls a tool that needs approval, Runner.run returns early. result.interruptions holds one ToolApprovalItem per pending call, with the tool name, the raw arguments and the call_id.
  • result.to_state() turns the paused run into a RunState. You record a decision on it with state.approve(item) or state.reject(item, rejection_message=...), then pass the state, not the original task, back to Runner.run with the same agent.
  • A rejection is not an exception. The SDK sends your rejection_message to the model as the tool’s result, and the model carries on from there.
  • The loop is a while, because the resumed run can pause again: the model might ask to overwrite a note after the delete.

ask_human shows the arguments, not the model’s description of them. The model’s summary of a call (“tidying up an old file”) is exactly the text you cannot trust; the arguments are what will run. The prompt defaults to no: pressing Enter declines.

4. Run it with a scripted model

To run without a key, the agent needs something that behaves like a model. Save fake_model.py. It implements the SDK’s Model interface and plays back a fixed list of turns:

# fake_model.py: a scripted stand-in for the LLM, so the approval flow runs without an API key.
import json
from itertools import count

from agents import Model, ModelResponse, Usage
from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage, ResponseOutputText

_ids = count(1)


def _last_tool_output(input_items) -> str:
    """Return the most recent tool result the agent loop sent back to the model."""
    if isinstance(input_items, list):
        for item in reversed(input_items):
            if isinstance(item, dict) and item.get("type") == "function_call_output":
                return str(item.get("output"))
    return ""


class ScriptedModel(Model):
    """Plays back a fixed list of turns: ("call", tool_name, args) or ("say", text).

    In "say" text, {last_output} is replaced with the last tool result, so the final
    message reflects whether the human approved or rejected the call.
    """

    def __init__(self, turns):
        self.turns = list(turns)

    async def get_response(self, system_instructions, input, model_settings, tools,
                           output_schema, handoffs, tracing, **kwargs) -> ModelResponse:
        kind, *rest = self.turns.pop(0)
        n = next(_ids)
        if kind == "call":
            name, args = rest
            item = ResponseFunctionToolCall(
                type="function_call", id=f"fc_{n}", call_id=f"call_{n}",
                name=name, arguments=json.dumps(args),
            )
        else:
            text = rest[0].format(last_output=_last_tool_output(input))
            item = ResponseOutputMessage(
                type="message", id=f"msg_{n}", role="assistant", status="completed",
                content=[ResponseOutputText(type="output_text", text=text, annotations=[])],
            )
        return ModelResponse(output=[item], usage=Usage(), response_id=None)

    def stream_response(self, *args, **kwargs):
        raise NotImplementedError("ScriptedModel does not stream")

The script asks to list the notes, then to delete the draft, then reports the last tool result. Run it and decline:

python agent.py --offline
-> list_notes

Approval needed: delete_note {"name": "old-deploy-draft.md"}
Approve? [y/N] n

Tool result: A person declined delete_note. Do not retry it.

Run it again and type y:

-> list_notes

Approval needed: delete_note {"name": "old-deploy-draft.md"}
Approve? [y/N] y
-> delete_note

Tool result: Deleted old-deploy-draft.md.

Look at where -> delete_note appears. The hook that logs tool starts fired only after the approval, so nothing touched the file while the run was paused. approvals.jsonl now holds both decisions:

{"at": "2026-11-21T16:17:23+00:00", "tool": "delete_note", "arguments": {"name": "old-deploy-draft.md"}, "call_id": "call_2", "approved": false}
{"at": "2026-11-21T16:17:27+00:00", "tool": "delete_note", "arguments": {"name": "old-deploy-draft.md"}, "call_id": "call_2", "approved": true}

With a real model, drop --offline and give it a task. Set OPENAI_API_KEY first; the agent uses the SDK’s default model, as in the first tutorial:

export OPENAI_API_KEY="sk-..."
python agent.py "Replace deploy.md with a one-line note saying the checklist moved to the wiki."

That run is not shown here because it needs a paid key. Expect the model to read or list notes first, then pause on write_note, because deploy.md exists. Ask it to create a new note instead and it should not ask at all.

5. Prove the gate holds

An approval rule nobody tests can break without anyone noticing. Save test_gate.py. Each test scripts the model’s calls, so it checks your rules, not the model’s judgement:

# test_gate.py: prove the approval rules hold, with no model and no API key.
import asyncio

import pytest
from agents import RunState, Runner, set_tracing_disabled

import agent as app
from fake_model import ScriptedModel

set_tracing_disabled(True)


@pytest.fixture(autouse=True)
def notes(tmp_path, monkeypatch):
    (tmp_path / "deploy.md").write_text("# Deploy\nRun migrations first.\n")
    monkeypatch.setattr(app, "NOTES_DIR", tmp_path)
    return tmp_path


def run(turns, task="do it"):
    app.agent.model = ScriptedModel(turns)
    return asyncio.run(Runner.run(app.agent, task, max_turns=5))


def test_new_note_needs_no_approval(notes):
    result = run([("call", "write_note", {"name": "new.md", "text": "hi"}), ("say", "done")])
    assert result.interruptions == []
    assert (notes / "new.md").read_text() == "hi"


def test_overwrite_pauses_before_running(notes):
    result = run([("call", "write_note", {"name": "deploy.md", "text": "gone"}), ("say", "done")])
    assert [i.name for i in result.interruptions] == ["write_note"]
    assert "migrations" in (notes / "deploy.md").read_text()  # nothing ran yet


def test_unsafe_name_asks_instead_of_guessing(notes):
    result = run([("call", "write_note", {"name": "../escape.md", "text": "x"}), ("say", "done")])
    assert [i.name for i in result.interruptions] == ["write_note"]


def test_rejected_delete_leaves_the_file(notes):
    result = run([("call", "delete_note", {"name": "deploy.md"}), ("say", "{last_output}")])
    state = result.to_state()
    state.reject(result.interruptions[0], rejection_message="Declined by a person.")
    result = asyncio.run(Runner.run(app.agent, state))
    assert (notes / "deploy.md").exists()
    assert result.final_output == "Declined by a person."


def test_approval_survives_a_restart(notes):
    result = run([("call", "delete_note", {"name": "deploy.md"}), ("say", "{last_output}")])
    saved = result.to_state().to_string()  # store this while you wait for a person

    async def resume():
        state = await RunState.from_string(app.agent, saved)
        state.approve(state.get_interruptions()[0])
        return await Runner.run(app.agent, state)

    result = asyncio.run(resume())
    assert not (notes / "deploy.md").exists()
    assert result.final_output == "Deleted deploy.md."
pytest -q test_gate.py
.....                                                                    [100%]
5 passed in 0.94s

The last test is the one to copy into a real system. In a terminal the person answers in seconds; in a web app or a Slack approval they may answer tomorrow, on another server. to_string() turns the paused run into text you can store, and RunState.from_string(agent, saved) rebuilds it later, with the pending call still pending.

6. The same gate in TypeScript

The AI SDK has the same idea with different names. In AI SDK 7, approval rules live in a toolApproval setting on ToolLoopAgent (a tool’s own needsApproval option is marked deprecated in the version 7 reference). Set up a project next to the Python one:

mkdir notes-approval-ts && cd notes-approval-ts
npm init -y
npm pkg set type=module
npm install ai@7.0.179 @ai-sdk/anthropic@4.0.107 zod@4.6.7
npm install -D tsx@4.23.15 typescript@7.0.2 @types/node@26.6.6

mkdir notes
printf "# Deploy checklist\nRun migrations before the release. Rollback with git revert.\n" > notes/deploy.md
printf "# Old deploy draft\nSuperseded by deploy.md.\n" > notes/old-deploy-draft.md

Save the scripted model as fake-model.ts. The SDK ships MockLanguageModelV4 in ai/test for exactly this:

// fake-model.ts: a scripted stand-in for the LLM, so the approval flow runs without an API key.
import { MockLanguageModelV4 } from "ai/test";

const usage = {
  inputTokens: { total: 0, noCache: 0, cacheRead: undefined, cacheWrite: undefined },
  outputTokens: { total: 0, text: 0, reasoning: undefined },
};

function call(id: string, toolName: string, input: object) {
  return {
    content: [{ type: "tool-call" as const, toolCallId: id, toolName, input: JSON.stringify(input) }],
    finishReason: { unified: "tool-calls" as const, raw: undefined },
    usage,
    warnings: [],
  };
}

function say(text: string) {
  return {
    content: [{ type: "text" as const, text }],
    finishReason: { unified: "stop" as const, raw: undefined },
    usage,
    warnings: [],
  };
}

export function scriptedModel() {
  return new MockLanguageModelV4({
    doGenerate: [
      call("call-1", "listNotes", {}),
      call("call-2", "deleteNote", { name: "old-deploy-draft.md" }),
      say("Done. (Scripted reply: a real model would say whether the delete ran.)"),
    ],
  });
}

Then agent.ts:

import { appendFile, readdir, unlink, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { createInterface } from "node:readline/promises";
import { anthropic } from "@ai-sdk/anthropic";
import { type LanguageModel, type ModelMessage, type ToolApprovalResponse, ToolLoopAgent, isStepCount, tool } from "ai";
import { z } from "zod";
import { scriptedModel } from "./fake-model.ts";

const NOTES_DIR = path.resolve("notes");

function safePath(name: string): string {
  const full = path.resolve(NOTES_DIR, name);
  if (path.dirname(full) !== NOTES_DIR || !full.endsWith(".md")) {
    throw new Error(`${name} is not a note in notes/`);
  }
  return full;
}

const offline = process.argv.includes("--offline");
const model: LanguageModel = offline ? scriptedModel() : anthropic("claude-opus-5-5");

const notesAgent = new ToolLoopAgent({
  model,
  instructions:
    "You manage the user's Markdown notes. Use the tools to find, read, write or delete notes. " +
    "If a person declines a tool call, do not retry it: tell the user it was not done.",
  tools: {
    listNotes: tool({
      description: "List the file names of all Markdown notes.",
      inputSchema: z.object({}),
      execute: async () => (await readdir(NOTES_DIR)).filter((f) => f.endsWith(".md")).sort(),
    }),
    deleteNote: tool({
      description: "Delete one note permanently.",
      inputSchema: z.object({ name: z.string().describe("The file name of the note to delete.") }),
      execute: async ({ name }) => {
        await unlink(safePath(name));
        return `Deleted ${name}.`;
      },
    }),
    writeNote: tool({
      description: "Create a note, or replace an existing note with new text.",
      inputSchema: z.object({ name: z.string(), text: z.string() }),
      execute: async ({ name, text }) => {
        await writeFile(safePath(name), text, "utf8");
        return `Saved ${name}.`;
      },
    }),
  },
  // The gate: which calls wait for a person. Tools not listed run normally.
  toolApproval: {
    deleteNote: "user-approval",
    writeNote: async ({ name }) => {
      try {
        return existsSync(safePath(name)) ? "user-approval" : undefined;
      } catch {
        return "user-approval"; // cannot tell what it would touch: ask
      }
    },
  },
  stopWhen: isStepCount(8),
  onStepEnd: ({ toolCalls }) => {
    for (const call of toolCalls) console.error(`model asked for ${call.toolName}`);
  },
});

const rl = createInterface({ input: process.stdin, output: process.stdout });
const task = process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "Delete the old deploy draft.";
const messages: ModelMessage[] = [{ role: "user", content: task }];

let result = await notesAgent.generate({ messages });
messages.push(...result.responseMessages);

while (true) {
  const requests = result.content.filter((p) => p.type === "tool-approval-request" && !p.isAutomatic);
  if (requests.length === 0) break;

  const responses: ToolApprovalResponse[] = [];
  for (const req of requests) {
    if (req.type !== "tool-approval-request") continue;
    const { toolName, input } = req.toolCall;
    console.log(`\nApproval needed: ${toolName} ${JSON.stringify(input)}`);
    const approved = (await rl.question("Approve? [y/N] ")).trim().toLowerCase() === "y";
    await appendFile(
      "approvals.jsonl",
      JSON.stringify({ at: new Date().toISOString(), tool: toolName, input, approved }) + "\n",
    );
    responses.push({
      type: "tool-approval-response",
      approvalId: req.approvalId,
      approved,
      reason: approved ? undefined : "A person declined this call.",
    });
  }
  messages.push({ role: "tool", content: responses });
  result = await notesAgent.generate({ messages });
  messages.push(...result.responseMessages);
}

rl.close();
console.log("\n" + result.text);

Run it and decline:

npx tsx agent.ts --offline
model asked for listNotes
model asked for deleteNote

Approval needed: deleteNote {"name":"old-deploy-draft.md"}
Approve? [y/N] n

Done. (Scripted reply: a real model would say whether the delete ran.)

old-deploy-draft.md is still in notes/; run it again and approve, and it is gone. The shape is the same as in Python, with two differences worth knowing. The AI SDK does not keep the run for you: you keep the messages array, append result.responseMessages, and send the decisions back as a tool message with one tool-approval-response per approvalId. And because that history is ordinary data, a web client could forge an approval in it. The AI SDK documents an experimental_toolApprovalSecret option that signs approval requests on the server and rejects forged ones; set it whenever the message history passes through a browser. To run against Claude, drop --offline and set ANTHROPIC_API_KEY; that run is not shown here.

Pitfalls

Showing the model’s summary instead of the arguments. A prompt like “The assistant wants to tidy up old files. Allow?” hides which file. Print the tool name and the exact arguments, because that is what will run.

Approving by default. If the prompt treats Enter, a timeout or a closed browser tab as yes, the gate is decoration. Make anything other than an explicit approval a rejection.

Retry loops after a rejection. Without an instruction not to retry, a model may call the declined tool again with slightly different arguments. Say it in the instructions and in the rejection message, and keep the turn limit.

Putting the rule in the prompt. “Always ask before deleting” in the instructions is a request, not a control. The rule belongs in needs_approval or toolApproval, where the model cannot skip it.

Asking for everything. If every read needs a click, people approve without reading. Gate the calls that change or send something, and leave reads to the guards in the tools.

Trusting saved or client-held state. A paused run stored in a browser, or a message history sent by a client, can be edited. Keep paused runs on the server, check who is approving, and sign approvals when history crosses a trust boundary.

Next steps

Covers

Check your understanding

Human approval for agent actions quiz

Choosing which tool calls need a person, needs_approval rules, pausing and resuming runs, rejections, saved state and toolApproval.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. In the notes agent, which call needs a person's approval?
  • Build your first agent in Python

    Three tools, a hard turn limit, a clear stop condition and a log of every tool call it makes.

    TutorialIntermediate1 h

  • Build your first agent in TypeScript

    Tools that search and read notes, a step limit, a clear stop condition and logged steps.

    TutorialIntermediate1 h

  • Human in the loop

    A design in which a person reviews or approves an AI system's actions or outputs at defined points before they take effect.

    Glossary

  • Excessive agency

    The risk that an AI system has more permissions, tools or autonomy than is safe, so a mistake or manipulation causes real harm.

    Glossary

  • OWASP Top 10 for LLM applications, explained with examples

    The 2026 OWASP Top 10 for LLM applications in plain language, with an agent-era example and a practical fix for each risk, plus what changed from 2025.

    Article

Back to top