# Tool calling (/docs/entwickler/tool-calling)

> Let a model call functions in your code, such as an invoice lookup, with the full loop, parallel calls, streaming and supported models.

With tool calling, a model can ask your code to run a function, for example to look up an invoice in your accounting system, and then answer with the result. Use it when the answer depends on data or actions that only your systems have.

The model never runs anything itself. It returns the name of a function and its arguments, and your code decides whether and how to run it. Everything on this page was tested against the live API on 11.11.2026.

## How it works
```mermaid
sequenceDiagram
    participant App as Your code
    participant API as PeakPrivacy API
    App->>API: messages + tools
    API-->>App: tool_calls (finish_reason "tool_calls")
    App->>App: run get_invoice_status(...)
    App->>API: messages + assistant turn + one tool message per call
    API-->>App: answer (finish_reason "stop")
```

1. Send `messages` and `tools`. Each tool is a function with a name, a description and a JSON Schema for its parameters.
2. If the answer contains `tool_calls`, run each function with the arguments it names.
3. Send the conversation again: add the assistant message with its `tool_calls`, then one `tool` message per call with the matching `tool_call_id`.
4. Repeat until the model answers without `tool_calls`.

## Complete example
Nadia in accounting at Alpenblick Treuhand AG wants to know whether two invoices have been paid. A dictionary stands in for the accounting system.

**curl**

Step 1 sends the question and the tool:

```bash
curl https://api.peakprivacy.ch/v1/ai/chat/completions \
  -H "Authorization: Bearer $PEAKPRIVACY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [{"role": "user", "content": "Has invoice RE-2026-0142 been paid?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_invoice_status",
        "description": "Look up the payment status of an invoice by its number.",
        "parameters": {
          "type": "object",
          "properties": {
            "invoice_number": {"type": "string", "description": "Invoice number, for example RE-2026-0142"}
          },
          "required": ["invoice_number"]
        }
      }
    }]
  }'
```

The model asks for a call instead of answering. `content` is empty or holds a short sentence such as `I'll look that up for you.`

```json
{
  "choices": [{
    "finish_reason": "tool_calls",
    "message": {
      "role": "assistant",
      "content": "",
      "tool_calls": [{
        "id": "chatcmpl-tool-9617f8d39177fa97",
        "type": "function",
        "function": {"name": "get_invoice_status", "arguments": "{\"invoice_number\": \"RE-2026-0142\"}"}
      }]
    }
  }]
}
```

Step 2 sends the conversation back with the result. In your code, use the `id` from step 1. Any id works as long as both messages use the same one.

```bash
curl https://api.peakprivacy.ch/v1/ai/chat/completions \
  -H "Authorization: Bearer $PEAKPRIVACY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "user", "content": "Has invoice RE-2026-0142 been paid?"},
      {"role": "assistant", "content": "", "tool_calls": [{
        "id": "call_1",
        "type": "function",
        "function": {"name": "get_invoice_status", "arguments": "{\"invoice_number\": \"RE-2026-0142\"}"}
      }]},
      {"role": "tool", "tool_call_id": "call_1", "content": "{\"status\": \"paid\", \"paid_on\": \"2026-10-28\"}"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_invoice_status",
        "description": "Look up the payment status of an invoice by its number.",
        "parameters": {
          "type": "object",
          "properties": {
            "invoice_number": {"type": "string", "description": "Invoice number, for example RE-2026-0142"}
          },
          "required": ["invoice_number"]
        }
      }
    }]
  }'
```

`choices[0].message.content` now holds the answer: `Yes — invoice **RE-2026-0142** has been paid, on **2026-10-28**.`

**Python**

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

client = OpenAI(
    base_url="https://api.peakprivacy.ch/v1/ai",
    api_key=os.environ["PEAKPRIVACY_API_KEY"],
)
MODEL = "deepseek-v4-flash"

# Your own code. A dictionary stands in for the accounting system.
INVOICES = {
    "RE-2026-0142": {"status": "paid", "paid_on": "2026-10-28", "amount_chf": "1234.50"},
    "RE-2026-0143": {"status": "open", "due_on": "2026-11-30", "amount_chf": "860.00"},
}

def get_invoice_status(invoice_number):
    return INVOICES.get(invoice_number, {"error": f"Unknown invoice {invoice_number}"})

FUNCTIONS = {"get_invoice_status": get_invoice_status}

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_invoice_status",
            "description": "Look up the payment status of an invoice by its number.",
            "parameters": {
                "type": "object",
                "properties": {
                    "invoice_number": {
                        "type": "string",
                        "description": "Invoice number, for example RE-2026-0142",
                    }
                },
                "required": ["invoice_number"],
            },
        },
    }
]

messages = [{"role": "user", "content": "Have invoices RE-2026-0142 and RE-2026-0143 been paid?"}]

for _ in range(5):  # upper limit for tool rounds
    response = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
    message = response.choices[0].message
    if not message.tool_calls:
        break

    # 1. Add the assistant turn with its tool calls to the conversation.
    messages.append({
        "role": "assistant",
        "content": message.content,
        "tool_calls": [call.model_dump() for call in message.tool_calls],
    })

    # 2. Run every requested function and answer each call with a tool message.
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        print(f"Calling {call.function.name}({args})")
        result = FUNCTIONS[call.function.name](**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

print(message.content)
```

**JavaScript**

```js
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.peakprivacy.ch/v1/ai",
  apiKey: process.env.PEAKPRIVACY_API_KEY,
});
const MODEL = "deepseek-v4-flash";

// Your own code. An object stands in for the accounting system.
const INVOICES = {
  "RE-2026-0142": { status: "paid", paid_on: "2026-10-28", amount_chf: "1234.50" },
  "RE-2026-0143": { status: "open", due_on: "2026-11-30", amount_chf: "860.00" },
};

function getInvoiceStatus({ invoice_number }) {
  return INVOICES[invoice_number] ?? { error: `Unknown invoice ${invoice_number}` };
}

const FUNCTIONS = { get_invoice_status: getInvoiceStatus };

const tools = [
  {
    type: "function",
    function: {
      name: "get_invoice_status",
      description: "Look up the payment status of an invoice by its number.",
      parameters: {
        type: "object",
        properties: {
          invoice_number: {
            type: "string",
            description: "Invoice number, for example RE-2026-0142",
          },
        },
        required: ["invoice_number"],
      },
    },
  },
];

const messages = [
  { role: "user", content: "Have invoices RE-2026-0142 and RE-2026-0143 been paid?" },
];

let message;
for (let round = 0; round < 5; round++) { // upper limit for tool rounds
  const response = await client.chat.completions.create({ model: MODEL, messages, tools });
  message = response.choices[0].message;
  if (!message.tool_calls?.length) break;

  // 1. Add the assistant turn with its tool calls to the conversation.
  messages.push({ role: "assistant", content: message.content, tool_calls: message.tool_calls });

  // 2. Run every requested function and answer each call with a tool message.
  for (const call of message.tool_calls) {
    const args = JSON.parse(call.function.arguments);
    console.log(`Calling ${call.function.name}(${JSON.stringify(args)})`);
    const result = FUNCTIONS[call.function.name](args);
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }
}

console.log(message.content);
```

Output of the Python script. The JavaScript script prints the arguments as JSON. The wording of the answer varies from run to run.

```text
Calling get_invoice_status({'invoice_number': 'RE-2026-0142'})
Calling get_invoice_status({'invoice_number': 'RE-2026-0143'})
Here are the results:
| Invoice | Status | Amount | Details |
|---|---|---|---|
| RE-2026-0142 | ✅ Paid | CHF 1,234.50 | Paid on 2026-10-28 |
| RE-2026-0143 | ⏳ Open | CHF 860.00 | Due on 2026-11-30 |
So only **RE-2026-0142** has been paid. **RE-2026-0143** is still open, with payment due by November 30, 2026.
```

The same script ran unchanged with `mistral-small-swiss`, `gpt-swiss`, `qwen-3-fast`, `gpt-4.1` and `claude-sonnet`.

## Parallel tool calls
Asked about two invoices, most models return two `tool_calls` in one message, as above. Answer every call with its own `tool` message before you send the next request. `gpt-swiss` asks for one call per round, and the loop handles that too.

## Streaming with tools
With `"stream": true`, tool calls arrive in pieces in `choices[0].delta.tool_calls`. Collect them by `index`: the first piece carries `id` and `function.name`, the following pieces add to `function.arguments`.

**Python**

```python
stream = client.chat.completions.create(
    model="mistral-small-swiss",
    messages=[{"role": "user", "content": "Have invoices RE-2026-0142 and RE-2026-0143 been paid?"}],
    tools=TOOLS,
    stream=True,
)

calls = {}  # index -> collected tool call
for chunk in stream:
    if not chunk.choices:
        continue  # the final usage chunk
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)
    for part in delta.tool_calls or []:
        call = calls.setdefault(part.index, {"id": None, "name": "", "arguments": ""})
        if part.id:
            call["id"] = part.id
        if part.function and part.function.name:
            call["name"] += part.function.name
        if part.function and part.function.arguments:
            call["arguments"] += part.function.arguments

for call in calls.values():
    print(call)
```

**JavaScript**

```js
const stream = await client.chat.completions.create({
  model: "mistral-small-swiss",
  messages: [{ role: "user", content: "Have invoices RE-2026-0142 and RE-2026-0143 been paid?" }],
  tools,
  stream: true,
});

const calls = new Map(); // index -> collected tool call
for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta;
  if (!delta) continue; // the final usage chunk
  if (delta.content) process.stdout.write(delta.content);
  for (const part of delta.tool_calls ?? []) {
    if (!calls.has(part.index)) calls.set(part.index, { id: null, name: "", arguments: "" });
    const call = calls.get(part.index);
    if (part.id) call.id = part.id;
    if (part.function?.name) call.name += part.function.name;
    if (part.function?.arguments) call.arguments += part.function.arguments;
  }
}

for (const call of calls.values()) console.log(call);
```

```text
{'id': 'Sw79DsxfJ', 'name': 'get_invoice_status', 'arguments': '{"invoice_number": "RE-2026-0142"}'}
{'id': 'QaMh0m0eJ', 'name': 'get_invoice_status', 'arguments': '{"invoice_number": "RE-2026-0143"}'}
```

These snippets reuse `client` and the tool list from the complete example. Once the stream has ended, send the collected calls back as in the loop, as `{"id": …, "type": "function", "function": {"name": …, "arguments": …}}`.

> **Known limitation:** `gpt-swiss` streams incomplete tool-call arguments. **Workaround:** call `gpt-swiss` without `stream` when you send `tools`, or stream with a model marked Yes under [Which models support it](/docs/entwickler/tool-calling#models).

## Which models support it
| Model | Level | Tool calls | Parallel calls | Streaming |
|---|---|---|---|---|
| `deepseek-v4-flash`, `glm5` | [Schweiz] | Yes | Yes | Yes ¹ |
| `mistral-small-swiss` | [Schweiz] | Yes | Yes | Yes |
| `gpt-swiss` | [Schweiz] | Yes | One per round | No: arguments arrive incomplete |
| `gpt-eu`, `deepseek-r1` | [EU] | Yes | Yes | Yes ¹ |
| `qwen-3`, `qwen-3-fast` | [EU] | Yes | Yes | Yes |
| `gemma-3` | [EU] | No: tools are ignored | – | – |
| `gpt-4o`, `gpt-4.1` | [Extern] | Yes | Yes | Yes |
| `gpt-5` | [Extern] | Only with `"reasoning_effort": "none"`, otherwise `500`. Or use [`/responses`](#responses). | Yes | Yes |
| `claude-sonnet`, `claude-opus` | [Extern] | Yes | Yes | Yes |
| `gemini-3.5-flash`, `gemini-3-pro-preview` | [Extern] | No: tools are ignored | – | – |

¹ Text that the model writes before its tool calls can lose its first words to `delta.reasoning_content`, see [Reasoning › Streaming](/docs/entwickler/reasoning#streaming). The tool calls arrive complete.

"Tools are ignored" means: the request succeeds, but no tool call comes back. The model answers in text, says it has no access to your data, or returns an empty answer. Check `finish_reason`: only `tool_calls` means the model wants a call.

## Request fields
- **`tools`**: only `"type": "function"`. `parameters` is a JSON Schema object.
- **`tool_choice` and `parallel_tool_calls`**: dropped without an error, as are the older `functions` and `function_call`. You can't force or forbid a call: in our tests, `"tool_choice": "none"` still produced a call. To rule out calls, send the request without `tools`. To make calls more likely, say in the system message when the model should use a tool.
- **Messages**: an `assistant` message carries `tool_calls`, and a `tool` message carries `tool_call_id` and a string `content`. Encode objects as JSON.
- **Anonymisation**: with `"anonymize": true`, `tool` messages are processed like user messages, and the arguments in `tool_calls` come back with the original values. See [Anonymisation](/docs/entwickler/anonymisation).

## Responses endpoint
Tools also work on `POST /v1/ai/responses` for models with `meta.capabilities.responses: true`. Tool definitions are flat, calls arrive as `function_call` items in `output`, and you return results as `function_call_output` items. `previous_response_id` is dropped, so send the whole conversation each time. The snippet reuses `client`, `json` and `get_invoice_status` from the [complete example](/docs/entwickler/tool-calling#example).

```python
tools = [{
    "type": "function",
    "name": "get_invoice_status",
    "description": "Look up the payment status of an invoice by its number.",
    "parameters": {
        "type": "object",
        "properties": {"invoice_number": {"type": "string"}},
        "required": ["invoice_number"],
    },
}]
inputs = [{"role": "user", "content": "Has invoice RE-2026-0142 been paid?"}]

response = client.responses.create(model="gpt-5", input=inputs, tools=tools)
for item in response.output:
    if item.type == "function_call":
        result = get_invoice_status(**json.loads(item.arguments))
        inputs.append({"type": "function_call", "call_id": item.call_id,
                       "name": item.name, "arguments": item.arguments})
        inputs.append({"type": "function_call_output", "call_id": item.call_id,
                       "output": json.dumps(result)})

final = client.responses.create(model="gpt-5", input=inputs, tools=tools)
print(final.output_text)  # Yes. Invoice **RE-2026-0142** was paid on **October 28, 2026**, for **CHF 1,234.50**.
```

## Pitfalls
- **Answer every call.** A conversation with a tool call but no matching `tool` message failed with `500` on `gpt-4.1` and `claude-sonnet`. Retrying won't help. Fix the messages.
- **Treat arguments as untrusted input.** `arguments` is a JSON string written by the model. Parse it, validate the values, and ask a person before your code changes or sends anything.
- **Limit the rounds.** A model can keep asking for calls. Stop after a few rounds, as the loop above does.
- **Tools cost tokens.** Every tool definition is sent with every request and counts in `prompt_tokens`. Step 1 of the example used about 330 prompt tokens for a one-line question.

## See also
- [Chat completions › Request body](/docs/entwickler/chat-completions#fields)
- [Choosing a model](/docs/entwickler/choose-a-model)
- [Reasoning](/docs/entwickler/reasoning)
- [Errors and limits](/docs/entwickler/errors)
