# Human approval on tool calls

Stop the agent before a call that matters, and run it only when a person says yes.

1. [Mark the calls that need a person](#1-mark-the-calls-that-need-a-person).
2. [Stop the loop on those calls](#2-stop-the-loop-on-those-calls).
3. [Send back what the person decided](#3-send-back-what-the-person-decided).
4. [Save the conversation while it waits](#4-save-the-conversation-while-it-waits).

## 1. Mark the calls that need a person

The model never runs your code: it asks for a call, and your loop runs it ([Tools and function calling](/docs/tools)). Your loop sits between the ask and the run, so it decides which calls wait for a person.

Karim sells phones in Oran. His support agent looks up orders on its own and refunds small ones; a refund above his limit waits for him.

| Tool | Runs |
|---|---|
| `order_status` | at once: it reads, it changes nothing |
| `refund_order`, up to `AUTO_LIMIT` | at once |
| `refund_order`, above `AUTO_LIMIT` | after a yes |

<div class="good-to-know">
<p>Decide on the arguments, not on the tool's name alone. One tool can be routine at one amount and a risk at another: <code>needs_approval</code> reads both.</p>
</div>

## 2. Stop the loop on those calls

The loop sends the conversation, runs each call the model asks for, and sends the results back, until the model answers in words. A call that needs a person stops at `ask_person` first. The samples ask in the terminal: swap `ask_person` for your dashboard, a message, or a queue.

```python
import json
import os
from openai import OpenAI

API_KEY = os.environ["OPENDUNES_API_KEY"]
BASE_URL = "https://opendunes.com/v1"
MODEL = "anthropic/claude-sonnet-4.5"
PROMPT = "Order 1042 arrived broken. I want my money back."
REFUSED = "The shop owner said no. Do not try again."
AUTO_LIMIT = 2000
MAX_STEPS = 10

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)


def order_status(order_id):
    return {"order_id": order_id, "status": "delivered", "total": 4500}


def refund_order(order_id, amount):
    return {"order_id": order_id, "refunded": amount}


FUNCTIONS = {"order_status": order_status, "refund_order": refund_order}


def needs_approval(name, args):
    return name == "refund_order" and args["amount"] > AUTO_LIMIT


def ask_person(name, args):
    answer = input(f"Run {name} {json.dumps(args)}? [y/N] ")
    return answer.strip().lower() == "y"


def function_tool(name, description, properties):
    return {
        "type": "function",
        "function": {
            "name": name,
            "description": description,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": list(properties),
            },
        },
    }


tools = [
    function_tool(
        "order_status",
        "An order's status and total.",
        {"order_id": {"type": "string"}},
    ),
    function_tool(
        "refund_order",
        "Refund an order, whole or in part.",
        {"order_id": {"type": "string"}, "amount": {"type": "integer"}},
    ),
]

messages = [{"role": "user", "content": PROMPT}]
spent = 0.0

for step in range(MAX_STEPS):
    reply = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        tools=tools,
    )
    spent += reply.usage.cost
    message = reply.choices[0].message
    if not message.tool_calls:
        break
    messages.append(message)
    for call in message.tool_calls:
        name = call.function.name
        args = json.loads(call.function.arguments)
        if needs_approval(name, args) and not ask_person(name, args):
            result = {"refused": REFUSED}
        else:
            result = FUNCTIONS[name](**args)
        messages.append(
            {
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(result),
            }
        )

print(message.content)
print(spent)
```

```javascript
import OpenAI from "openai";
import * as readline from "node:readline/promises";

const API_KEY = process.env.OPENDUNES_API_KEY;
const BASE_URL = "https://opendunes.com/v1";
const MODEL = "anthropic/claude-sonnet-4.5";
const PROMPT = "Order 1042 arrived broken. I want my money back.";
const REFUSED = "The shop owner said no. Do not try again.";
const AUTO_LIMIT = 2000;
const MAX_STEPS = 10;

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });
const terminal = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const functions = {
  order_status: ({ order_id }) => ({
    order_id,
    status: "delivered",
    total: 4500,
  }),
  refund_order: ({ order_id, amount }) => ({ order_id, refunded: amount }),
};

const needsApproval = (name, args) =>
  name === "refund_order" && args.amount > AUTO_LIMIT;

async function askPerson(name, args) {
  const question = `Run ${name} ${JSON.stringify(args)}? [y/N] `;
  const answer = await terminal.question(question);
  return answer.trim().toLowerCase() === "y";
}

const functionTool = (name, description, properties) => ({
  type: "function",
  function: {
    name,
    description,
    parameters: {
      type: "object",
      properties,
      required: Object.keys(properties),
    },
  },
});

const tools = [
  functionTool("order_status", "An order's status and total.", {
    order_id: { type: "string" },
  }),
  functionTool("refund_order", "Refund an order, whole or in part.", {
    order_id: { type: "string" },
    amount: { type: "integer" },
  }),
];

const messages = [{ role: "user", content: PROMPT }];
let spent = 0;
let message;

for (let step = 0; step < MAX_STEPS; step++) {
  const reply = await client.chat.completions.create({
    model: MODEL,
    messages,
    tools,
  });
  spent += reply.usage.cost;
  message = reply.choices[0].message;
  if (!message.tool_calls?.length) break;
  messages.push(message);
  for (const call of message.tool_calls) {
    const name = call.function.name;
    const args = JSON.parse(call.function.arguments);
    const refused = needsApproval(name, args) && !(await askPerson(name, args));
    const result = refused ? { refused: REFUSED } : functions[name](args);
    messages.push({
      role: "tool",
      tool_call_id: call.id,
      content: JSON.stringify(result),
    });
  }
}

terminal.close();
console.log(message.content);
console.log(spent);
```

```go
package main

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

const (
	baseURL   = "https://opendunes.com/v1"
	model     = "anthropic/claude-sonnet-4.5"
	prompt    = "Order 1042 arrived broken. I want my money back."
	refused   = "The shop owner said no. Do not try again."
	autoLimit = 2000
	maxSteps  = 10
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
	)
	terminal := bufio.NewReader(os.Stdin)

	text := map[string]any{"type": "string"}
	whole := map[string]any{"type": "integer"}
	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.UserMessage(prompt),
		},
		Tools: []openai.ChatCompletionToolUnionParam{
			functionTool("order_status", "An order's status and total.",
				map[string]any{"order_id": text}),
			functionTool("refund_order", "Refund an order, whole or in part.",
				map[string]any{"order_id": text, "amount": whole}),
		},
	}

	spent := 0.0
	var message openai.ChatCompletionMessage
	for step := 0; step < maxSteps; step++ {
		reply, err := client.Chat.Completions.New(context.TODO(), params)
		if err != nil {
			panic(err)
		}
		cost := reply.Usage.JSON.ExtraFields["cost"].Raw()
		charge, _ := strconv.ParseFloat(cost, 64)
		spent += charge
		message = reply.Choices[0].Message
		if len(message.ToolCalls) == 0 {
			break
		}
		params.Messages = append(params.Messages, message.ToParam())
		for _, call := range message.ToolCalls {
			name := call.Function.Name
			var args orderArgs
			json.Unmarshal([]byte(call.Function.Arguments), &args)
			var result any = map[string]string{"refused": refused}
			if !needsApproval(name, args) || askPerson(terminal, name, args) {
				result = run(name, args)
			}
			out, _ := json.Marshal(result)
			toolMessage := openai.ToolMessage(string(out), call.ID)
			params.Messages = append(params.Messages, toolMessage)
		}
	}

	fmt.Println(message.Content)
	fmt.Println(spent)
}

type orderArgs struct {
	OrderID string `json:"order_id"`
	Amount  int    `json:"amount"`
}

func run(name string, args orderArgs) map[string]any {
	if name == "order_status" {
		return map[string]any{
			"order_id": args.OrderID,
			"status":   "delivered",
			"total":    4500,
		}
	}
	return map[string]any{"order_id": args.OrderID, "refunded": args.Amount}
}

func needsApproval(name string, args orderArgs) bool {
	return name == "refund_order" && args.Amount > autoLimit
}

func askPerson(terminal *bufio.Reader, name string, args orderArgs) bool {
	shown, _ := json.Marshal(args)
	fmt.Printf("Run %s %s? [y/N] ", name, shown)
	answer, _ := terminal.ReadString('\n')
	return strings.ToLower(strings.TrimSpace(answer)) == "y"
}

func functionTool(
	name, description string,
	properties map[string]any,
) openai.ChatCompletionToolUnionParam {
	required := []string{}
	for key := range properties {
		required = append(required, key)
	}
	return openai.ChatCompletionFunctionTool(openai.FunctionDefinitionParam{
		Name:        name,
		Description: openai.String(description),
		Parameters: openai.FunctionParameters{
			"type":       "object",
			"properties": properties,
			"required":   required,
		},
	})
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
PROMPT="Order 1042 arrived broken. I want my money back."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "'"$PROMPT"'"
      },
      {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_1",
            "type": "function",
            "function": {
              "name": "refund_order",
              "arguments": "{\"order_id\": \"1042\", \"amount\": 4500}"
            }
          }
        ]
      },
      {
        "role": "tool",
        "tool_call_id": "call_1",
        "content": "{\"refused\": \"The shop owner said no.\"}"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "refund_order",
          "description": "Refund an order, whole or in part.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {
                "type": "string"
              },
              "amount": {
                "type": "integer"
              }
            },
            "required": ["order_id", "amount"]
          }
        }
      }
    ]
  }'
```

The cURL sample is the turn after a no: the model reads the refusal and answers the customer in words.

## 3. Send back what the person decided

A yes runs the function, and its result goes back like any other. A no goes back too, as the call's result: a `tool` message that says so, with the call's `tool_call_id`. The model reads it and carries on: it tells the customer, or offers something else.

| The person | Your loop sends back |
|---|---|
| says yes | what the function returned |
| says no | `{"refused": "…"}`, and why, in words the model can act on |
| edits the call | what the function returned when run with the edited arguments |
| never answers | a refusal, once the deadline you set has passed |

<div class="dont">
<p>Don't drop a refused call from the conversation. Every call in the model's message needs its <code>tool</code> message, or the next request is refused with a 400.</p>
</div>

<div class="do">
<p>Answer every call, the refused ones included, and say in the refusal what the model may do next.</p>
</div>

## 4. Save the conversation while it waits

A person may take an hour. Don't hold a process open for them: no request is open while the loop waits, so there is nothing to keep alive. Save the conversation and the pending call, end the process, and pick it up when the decision arrives.

```json
{
  "conversation": "order-1042",
  "messages": [
    {
      "role": "user",
      "content": "Order 1042 arrived broken. I want my money back."
    },
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_1",
          "type": "function",
          "function": {
            "name": "refund_order",
            "arguments": "{\"order_id\": \"1042\", \"amount\": 4500}"
          }
        }
      ]
    }
  ],
  "pending": "call_1"
}
```

When the decision arrives: load the record, run or refuse the pending call, append its `tool` message, and send the conversation again. The loop goes on from there, as if it had never stopped.

<div class="watch-out">
<p>Record that a call ran before anything else can fail. A process that crashes after the refund and before the save would run it again on resume: store the result with the call's <code>id</code>, and skip a call whose result is already there.</p>
</div>

## What it costs

Each turn is a request of its own, charged as one, and `usage.cost` on each answer carries its charge in DA: the samples add them up in `spent`. The wait costs nothing. A refusal costs one more turn, the one in which the model reads it and answers.

What to do on each status: [Errors and retries](/docs/errors-and-retries).
