# OpenAI Chat Format (Chat Completions)

> Official docs: [OpenAI Chat Completions API reference](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create)

## 📝 Introduction

The Chat Completions endpoint takes a list of conversation messages and returns the model's next reply. It is the most widely supported OpenAI-compatible format: every text model on BeeRoute (GPT, Claude, Gemini, DeepSeek, Kimi, GLM, Qwen, and more) can be called through it, and the gateway handles format conversion automatically.

OpenAI recommends the Responses API for new projects; see [OpenAI Response Format (Responses)](coding/openai-responses.md). Chat Completions remains supported by OpenAI.

> **Quick facts**
> - Base URL: `https://beeroute.ai/v1`
> - Endpoint: `POST https://beeroute.ai/v1/chat/completions`
> - Authentication: request header `Authorization: Bearer $API_KEY`
> - API keys: create one on the console [API Keys page](https://beeroute.ai/keys); keys look like `sk-xxx`
> - Models and prices: [https://beeroute.ai/modellist/](https://beeroute.ai/modellist/), or call `GET https://beeroute.ai/v1/models` to list the models available to your key

The curl examples below read the key from an environment variable. Run this first:

```bash
export API_KEY=sk-xxx
```

## 💡 Request Examples

### Basic Text Chat ✅

```bash
curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello! Please introduce yourself in one sentence."}
    ]
  }'
```

**Response example:**

```json
{
  "id": "chatcmpl-Dk2v8Qx3NcR7uYbT5mWfL0aJsPe9H",
  "object": "chat.completion",
  "created": 1795740000,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! I am an AI assistant that can help you answer questions, write, translate, and code.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 86,
    "total_tokens": 114,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 64, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}
```

?> Replace `model` with another model ID such as `claude-sonnet-5-5`, `gemini-4-hydrogen`, `deepseek-flash`, `kimi-k3.1-pro`, `glm-5.3`, or `qwen4-max` to call other providers with exactly the same request format.

?> OpenAI recommends the `developer` role instead of `system` for newer models. If the same code also calls non-OpenAI models such as Claude or DeepSeek, keep using `system` for the best compatibility.

### Image Input ✅

Make `content` an array to send text and images in the same user message. An image can be a public URL or a base64 data URL (for example `data:image/jpeg;base64,...`).

```bash
curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {
        "role": "user",
        "content": [
          {"type": "text", "text": "What is in this image?"},
          {
            "type": "image_url",
            "image_url": {
              "url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg",
              "detail": "auto"
            }
          }
        ]
      }
    ],
    "max_completion_tokens": 1000
  }'
```

**Response example:**

```json
{
  "id": "chatcmpl-Dk2wB7nTq0VhXe4sKp9LcR2mYa6Gu",
  "object": "chat.completion",
  "created": 1795740060,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "This is an oil portrait of a young woman seated in a curved bentwood chair. She wears a red-and-blue striped jacket and a blue skirt with orange dots, holds a small sprig of flowers, and sits against a pale turquoise background. The bold brushwork and vivid colors are characteristic of Van Gogh.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 512,
    "completion_tokens": 168,
    "total_tokens": 680,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 96, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}
```

### Streaming Response ✅

With `"stream": true`, the endpoint returns the reply in pieces as SSE (Server-Sent Events). Set `stream_options.include_usage` to receive one final chunk with the total usage for the request. Add `-N` to curl to disable output buffering so you see each chunk as it arrives.

```bash
curl -N https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ],
    "stream": true,
    "stream_options": {"include_usage": true}
  }'
```

**Streaming response example:**

```text
data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{"content":"! How can I help you today?"},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":40,"total_tokens":49,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":28,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}

data: [DONE]
```

Key points:

- Each `data:` line carries one `chat.completion.chunk` object. The incremental text is in `choices[0].delta.content`; concatenate the pieces in order.
- The stop reason appears in `finish_reason` of the last chunk that has `choices`.
- With `include_usage` enabled, one extra chunk with an empty `choices` array arrives before `[DONE]`; its `usage` covers the whole request, and `usage` is `null` on every other chunk. If the stream is interrupted you may not receive this usage chunk.
- The stream ends with `data: [DONE]`, which is a plain-text marker, not JSON.
- BeeRoute usually returns the usage chunk even when `stream_options` is omitted; set `"include_usage": false` explicitly if you do not want it.

### Function Calling (Tool Calls) ✅

Function calling takes two requests. First, send the available function definitions in `tools`; when the model decides to call one, it returns `tool_calls`. Run the function in your own code, then send the result back as a `tool` message so the model can write the final answer.

**Step 1: send the question and the function definitions**

```bash
curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "user", "content": "What is the weather like in Boston today?"}
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get the current weather for a city",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "City and state, for example: Boston, MA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'
```

**Response example:**

```json
{
  "id": "chatcmpl-Dk2yR9cLx5TbW2nQ7vPe4KmZs1Hj",
  "object": "chat.completion",
  "created": 1795740180,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_Q8sV2nK7pL4mX1rT",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}"
            }
          }
        ],
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 86,
    "completion_tokens": 52,
    "total_tokens": 138,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 24, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}
```

`arguments` is a JSON string generated by the model. The model does not guarantee that it is valid JSON or that it matches your schema, so parse and validate it before running the function.

**Step 2: send the function result back to the model**

Append to `messages`, in order: the assistant message the model returned (keep its `tool_calls` unchanged), then a message with `role` set to `tool` whose `tool_call_id` matches the `id` of the call. Keep sending `tools` as well.

```bash
curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "user", "content": "What is the weather like in Boston today?"},
      {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_Q8sV2nK7pL4mX1rT",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}"
            }
          }
        ]
      },
      {
        "role": "tool",
        "tool_call_id": "call_Q8sV2nK7pL4mX1rT",
        "content": "{\"location\":\"Boston, MA\",\"temperature\":6,\"unit\":\"celsius\",\"condition\":\"sunny\"}"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get the current weather for a city",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "City and state, for example: Boston, MA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      }
    ]
  }'
```

**Response example:**

```json
{
  "id": "chatcmpl-Dk2zT3vNq6WcY8mLp1RbX5KeJs0Fa",
  "object": "chat.completion",
  "created": 1795740185,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "It is sunny in Boston today, at about 6°C. Dress warmly if you go out.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 152,
    "completion_tokens": 30,
    "total_tokens": 182,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}
```

?> The model may return several `tool_calls` in one reply (parallel calls). Append one `tool` message per call, directly after the assistant message that contains them.

!> According to OpenAI, GPT-6 Astra, GPT-6.1 Sol, and GPT-6.2 Astra / Sol do not support function calling in Chat Completions. Use the [Responses API](coding/openai-responses.md) when these models need tools.

### Structured Output (JSON Schema) ✅

Pass a JSON Schema in `response_format` and set `"strict": true`; the model output will then follow that structure exactly.

```bash
curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "system", "content": "Extract the event information from the user text."},
      {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "event_info",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "date": {"type": "string"},
            "participants": {
              "type": "array",
              "items": {"type": "string"}
            }
          },
          "required": ["name", "date", "participants"],
          "additionalProperties": false
        }
      }
    }
  }'
```

**Response example:**

```json
{
  "id": "chatcmpl-Dk30Lm5Rq8ZtV2xNc7WbK4PeYs9Hd",
  "object": "chat.completion",
  "created": 1795740240,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"name\":\"Science fair\",\"date\":\"Friday\",\"participants\":[\"Alice\",\"Bob\"]}",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 92,
    "completion_tokens": 58,
    "total_tokens": 150,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 32, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}
```

`message.content` is a JSON string; parse it to get the structured data. If the model refuses for safety reasons, `content` is `null` and the reason is in `message.refusal`.

### Reasoning Effort (reasoning_effort) ✅

Reasoning models produce internal reasoning tokens before answering. `reasoning_effort` controls how deeply they reason: higher values think more thoroughly but take longer and use more reasoning tokens. Reasoning tokens do not appear in the reply, but they count toward `completion_tokens` and are billed as output.

```bash
curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "reasoning_effort": "high",
    "messages": [
      {"role": "user", "content": "A farmer has 17 sheep and all but 9 die. How many sheep are left? Explain briefly."}
    ],
    "max_completion_tokens": 4000
  }'
```

**Response example:**

```json
{
  "id": "chatcmpl-Dk31Wq2Tn7KcX5vRb9LmZe3PsY0Gj",
  "object": "chat.completion",
  "created": 1795740300,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "9 sheep are left. \"All but 9 die\" means every sheep except 9 died, so exactly 9 survive.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 412,
    "total_tokens": 457,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 352, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}
```

?> `max_completion_tokens` limits visible output and reasoning tokens together. Leave enough room at higher effort levels, or the reply may be cut off with `finish_reason: "length"` before the answer is written.

## 📮 Request

### Endpoint

```text
POST https://beeroute.ai/v1/chat/completions
```

### Authentication

Send your API key in the request header:

```text
Authorization: Bearer $API_KEY
```

`$API_KEY` is the key you created on the BeeRoute console [API Keys page](https://beeroute.ai/keys). The request body is JSON, so also set `Content-Type: application/json`.

### Request Body Parameters

The tables below list the main parameters from OpenAI's documentation. Parameter support varies by model, especially for reasoning models. The [official API reference](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) has the complete field descriptions. OpenAI's `prompt_cache_options` and `moderation` parameters are not currently forwarded by BeeRoute, so they are not listed.

#### Required Parameters

| Parameter | Type | Description |
|------|------|------|
| `model` | string | Model ID, for example `gpt-5.6-terra`. See the [pricing page](https://beeroute.ai/modellist/) or `GET /v1/models` for available models. |
| `messages` | array | The conversation so far, with at least 1 message. See "Message Types" below. |

#### Generation Control

| Parameter | Type | Default | Description |
|------|------|--------|------|
| `max_completion_tokens` | integer or null | - | Upper bound on tokens generated for the completion, including visible output and reasoning tokens. |
| `reasoning_effort` | string or null | model-dependent | Reasoning effort: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. Supported values differ by model; for example, `gpt-5.6-terra` supports `none`, `low`, `medium` (default), `high`, `xhigh`, and `max`. See the [official reasoning guide](https://developers.openai.com/api/docs/guides/reasoning). |
| `verbosity` | string or null | `medium` | How detailed the reply should be: `low`, `medium`, or `high`. Lower values give more concise replies. Support varies by model. |
| `stop` | string, array, or null | null | Up to 4 stop sequences. Generation stops at these sequences, and the returned text does not include them. Not supported by some reasoning models. |
| `n` | integer or null | 1 | How many choices to generate for each input. Omit it to get one choice; newer models reject an explicit `n` (even `n=1`). Output tokens of all choices are billed. |
| `modalities` | array or null | `["text"]` | Output modalities you want. Models that support audio output accept `["text", "audio"]`. |
| `audio` | object or null | - | Audio output parameters, required when audio output is requested. See "audio Parameters" below. |
| `prediction` | object or null | - | Predicted Outputs configuration. When most of the reply is known in advance (for example, a small edit to a file), this can greatly speed up the response. Format: `{"type": "content", "content": "..."}`, where `content` is a string or an array of text parts. |

#### Sampling Parameters

| Parameter | Type | Default | Description |
|------|------|--------|------|
| `temperature` | number or null | 1 | Sampling temperature between 0 and 2. Higher values give more random output; lower values give more focused, deterministic output. Adjust this or `top_p`, not both. |
| `top_p` | number or null | 1 | Nucleus sampling between 0 and 1. 0.1 means only the tokens in the top 10% probability mass are considered. |
| `presence_penalty` | number or null | 0 | Between -2.0 and 2.0. Positive values penalize tokens that have already appeared, encouraging new topics. |
| `frequency_penalty` | number or null | 0 | Between -2.0 and 2.0. Positive values penalize tokens by how often they have appeared, reducing verbatim repetition. |
| `logit_bias` | object or null | null | Maps token IDs to a bias from -100 to 100 to raise or lower the likelihood of specific tokens; -100 or 100 effectively bans or forces a token. |
| `logprobs` | boolean or null | false | Whether to return log probabilities of the output tokens. |
| `top_logprobs` | integer or null | - | Between 0 and 20: the number of most likely tokens to return at each position, with their log probabilities. Requires `logprobs: true`. |

!> Reasoning models usually do not support some of these sampling parameters. For example, OpenAI says to omit `temperature`, `top_p`, `logprobs`, and `top_logprobs` when using GPT-6.2 Astra / Sol with Chat Completions, and BeeRoute usually ignores `temperature`, `top_p`, and `logprobs` for GPT-5 series models. Check each model's official documentation.

#### Streaming

| Parameter | Type | Default | Description |
|------|------|--------|------|
| `stream` | boolean or null | false | When `true`, the response is streamed as SSE `chat.completion.chunk` events, ending with `data: [DONE]`. |
| `stream_options` | object or null | null | Streaming options; set only when `stream: true`. `include_usage` (boolean): when `true`, one extra chunk with the total usage is sent before `[DONE]`. OpenAI also defines `include_obfuscation`, which BeeRoute usually does not forward. |

#### Tool Calling

| Parameter | Type | Default | Description |
|------|------|--------|------|
| `tools` | array | - | Tools the model may call: function tools (`function`) and custom tools (`custom`). See "tools Definitions" below. |
| `tool_choice` | string or object | `none` without tools, `auto` with tools | Controls whether and which tool the model calls. See "tool_choice Values" below. |
| `parallel_tool_calls` | boolean | true | Whether the model may call several functions in parallel in one reply. |
| `web_search_options` | object | - | Web search configuration, only for search models that support it. See "web_search_options" below. |

#### Output Format

| Parameter | Type | Description |
|------|------|------|
| `response_format` | object | Output format: `{"type": "text"}` (default), `{"type": "json_schema", "json_schema": {...}}` (Structured Outputs, recommended), or `{"type": "json_object"}` (older JSON mode). See "response_format" below. |

#### Caching, Identifiers and Other

| Parameter | Type | Default | Description |
|------|------|--------|------|
| `prompt_cache_key` | string or null | - | Key used to improve prompt cache hit rates; use the same value for similar requests. Replaces the caching role of the deprecated `user` field. |
| `safety_identifier` | string or null | - | Stable end-user identifier (up to 128 characters) that helps OpenAI detect users who violate its usage policies; a hash of the username or email is recommended. BeeRoute does not forward this field upstream by default. |
| `service_tier` | string or null | `auto` | Official values: `auto`, `default`, `flex`, `scale`, `priority`, `fast`. BeeRoute accepts the field but normally ignores it and forwards the request with default processing. |
| `metadata` | object or null | - | Up to 16 key-value pairs; keys up to 64 characters, values are strings up to 512 characters. |
| `store` | boolean or null | false | Whether the upstream provider stores this completion for OpenAI's model distillation or evals products. BeeRoute does not offer endpoints for reading stored completions, so you usually do not need this. |

#### Deprecated Parameters

These parameters are still accepted, but OpenAI no longer recommends them:

| Parameter | Replacement | Description |
|------|----------|------|
| `max_tokens` | `max_completion_tokens` | Old maximum number of generated tokens; not compatible with o-series reasoning models. |
| `user` | `safety_identifier`, `prompt_cache_key` | Old end-user identifier. |
| `seed` | - | Beta feature for best-effort deterministic sampling; identical results are not guaranteed. |
| `functions` | `tools` | Old list of functions (up to 128). |
| `function_call` | `tool_choice` | Old function call control: `none`, `auto`, or `{"name": "my_function"}`. |
| `prompt_cache_retention` | `prompt_cache_options.ttl` | Prompt cache retention policy, `in_memory` or `24h`; `gpt-5.5`, `gpt-5.5-pro`, and later models support only `24h`. BeeRoute still forwards this field but does not forward `prompt_cache_options`. |

### Message Types

Each message in `messages` has a `role`:

| role | Description | Main fields |
|------|------|----------|
| `developer` | Developer instructions the model should always follow. OpenAI recommends it instead of `system` for newer models. | `content` (required, string or array of text parts), `name` |
| `system` | System instructions, same purpose as `developer`. | `content` (required, string or array of text parts), `name` |
| `user` | Input from the end user. | `content` (required, string or array of content parts: text, image, audio, file), `name` |
| `assistant` | A previous reply from the model, sent back unchanged in multi-turn conversations. | `content` (may be null when `tool_calls` is present), `tool_calls`, `refusal`, `audio` (`{"id": "..."}` of a previous audio reply), `name` |
| `tool` | Result of a tool call. | `content` (required, string or array of text parts), `tool_call_id` (required, the `id` of the tool call) |
| `function` | Deprecated, replaced by `tool`. | `content`, `name` |

`name` is an optional participant name that distinguishes participants with the same role.

### Content Parts

When `content` is an array, each element is a content part with a `type`:

| type | Structure | Used in | Description |
|------|------|--------|------|
| `text` | `{"type": "text", "text": "..."}` | all roles | Text. |
| `image_url` | `{"type": "image_url", "image_url": {"url": "...", "detail": "auto"}}` | user | Image. `url` is an image URL or a base64 data URL; `detail` is `auto` (default), `low`, `high`, or `original`, and supported values depend on the model. |
| `input_audio` | `{"type": "input_audio", "input_audio": {"data": "...", "format": "wav"}}` | user | Base64-encoded audio; `format` is `wav` or `mp3`. Requires a model with audio input. |
| `file` | `{"type": "file", "file": {"filename": "a.pdf", "file_data": "data:application/pdf;base64,..."}}` | user | File input; Chat Completions accepts PDF only. OpenAI also supports `file_id` for uploaded files; through BeeRoute, use `file_data`. |
| `refusal` | `{"type": "refusal", "refusal": "..."}` | assistant | A refusal the model generated earlier. |

### tools Definitions

**Function tool**:

```json
{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "Get the current weather for a city",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {"type": "string"}
      },
      "required": ["location"]
    }
  }
}
```

| Field | Required | Description |
|------|------|------|
| `function.name` | yes | Function name: a-z, A-Z, 0-9, underscores, and dashes, up to 64 characters. |
| `function.description` | no | What the function does; helps the model decide when and how to call it. |
| `function.parameters` | no | Parameters described as a JSON Schema object; omit it for a function with no parameters. |
| `function.strict` | no | Official field; when `true`, generated arguments strictly follow the schema. BeeRoute does not currently forward this field; for strict structure, use `response_format` with `json_schema`. |

**Custom tool** (the model sends free-form text or grammar-constrained text as the tool input; mainly for OpenAI models):

```json
{
  "type": "custom",
  "custom": {
    "name": "run_sql",
    "description": "Run a read-only SQL query",
    "format": {"type": "text"}
  }
}
```

`custom.name` is required; `description` is optional; `format` is optional and defaults to unconstrained text (`{"type": "text"}`), or it can be a grammar `{"type": "grammar", "grammar": {"definition": "...", "syntax": "lark"}}` (`syntax` is `lark` or `regex`). When the model calls a custom tool, the `tool_calls` entry looks like `{"id": "...", "type": "custom", "custom": {"name": "run_sql", "input": "..."}}`.

### tool_choice Values

| Value | Meaning |
|------|------|
| `"none"` | Do not call any tool; generate a message. |
| `"auto"` | The model chooses between generating a message and calling one or more tools. |
| `"required"` | The model must call one or more tools. |
| `{"type": "function", "function": {"name": "get_weather"}}` | Force a call to the named function tool. |
| `{"type": "custom", "custom": {"name": "run_sql"}}` | Force a call to the named custom tool. |
| `{"type": "allowed_tools", "allowed_tools": {...}}` | Limit the available tools to a subset; see the example below. |

`allowed_tools` example (with `mode` set to `auto` the model may pick from the subset or reply directly; with `required` it must call a tool from the subset):

```json
{
  "type": "allowed_tools",
  "allowed_tools": {
    "mode": "auto",
    "tools": [
      {"type": "function", "function": {"name": "get_weather"}},
      {"type": "function", "function": {"name": "get_time"}}
    ]
  }
}
```

### response_format

| type | Structure | Description |
|------|------|------|
| `text` | `{"type": "text"}` | Default; plain text reply. |
| `json_schema` | `{"type": "json_schema", "json_schema": {...}}` | Structured Outputs; the output matches the given JSON Schema. Recommended for models that support it. |
| `json_object` | `{"type": "json_object"}` | Older JSON mode that only guarantees valid JSON. You must also tell the model to produce JSON in a system or user message. |

Fields of the `json_schema` object:

| Field | Required | Description |
|------|------|------|
| `name` | yes | Format name: a-z, A-Z, 0-9, underscores, and dashes, up to 64 characters. |
| `description` | no | What the format is for. |
| `schema` | no | The JSON Schema object. |
| `strict` | no | Defaults to false. When `true`, the output strictly follows the schema, but only a subset of JSON Schema is supported; see the [official Structured Outputs guide](https://developers.openai.com/api/docs/guides/structured-outputs). |

### web_search_options

```json
{
  "search_context_size": "medium",
  "user_location": {
    "type": "approximate",
    "approximate": {
      "country": "US",
      "city": "San Francisco",
      "region": "California",
      "timezone": "America/Los_Angeles"
    }
  }
}
```

| Field | Description |
|------|------|
| `search_context_size` | How much context window space search results may use: `low`, `medium` (default), or `high`. |
| `user_location` | Approximate location, or null. `type` is always `approximate`; `approximate` can contain `country` (two-letter ISO country code), `region` and `city` (free text), and `timezone` (IANA time zone), all optional. |

### audio Parameters

| Field | Required | Description |
|------|------|------|
| `voice` | yes | A built-in voice such as `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`, `marin`, or `cedar`, or a custom voice object `{"id": "voice_1234"}`. |
| `format` | yes | Output audio format: `wav`, `aac`, `mp3`, `flac`, `opus`, or `pcm16`. |

## 📥 Response

A non-streaming request returns one `chat.completion` object; a streaming request returns a sequence of `chat.completion.chunk` objects.

### chat.completion Object

| Field | Type | Description |
|------|------|------|
| `id` | string | Unique ID of the completion. |
| `object` | string | Always `chat.completion`. |
| `created` | integer | Creation time (Unix timestamp in seconds). |
| `model` | string | The model that generated the completion. |
| `choices` | array | List of choices; can contain more than one when `n` is greater than 1. |
| `usage` | object | Token usage for the request; see "usage Object" below. |
| `service_tier` | string or null | The service tier actually used (may be present). |
| `system_fingerprint` | string | Deprecated. Backend configuration fingerprint (may be present). |

Each element of `choices`:

| Field | Description |
|------|------|
| `index` | Position of the choice in the list. |
| `message` | The message generated by the model; fields in the table below. |
| `logprobs` | Log probability information when `logprobs` was requested, with `content` and `refusal` token lists; otherwise null. |
| `finish_reason` | Why generation stopped; see "finish_reason Values" below. |

The `message` object:

| Field | Description |
|------|------|
| `role` | Always `assistant`. |
| `content` | Reply text; may be null (for example, when only tool calls are returned). |
| `refusal` | Explanation when the model refuses; otherwise null. |
| `tool_calls` | List of tool calls. A function call entry has `id`, `type` (`function`), and `function` (with `name` and `arguments`); a custom tool call entry has `id`, `type` (`custom`), and `custom` (with `name` and `input`). |
| `annotations` | Annotations, such as `url_citation` entries (with `url`, `title`, `start_index`, `end_index`) when web search is used. |
| `audio` | Returned when audio output is requested; contains `id`, `data` (base64 audio), `transcript`, and `expires_at`. |
| `function_call` | Deprecated, replaced by `tool_calls`. |

### usage Object

| Field | Description |
|------|------|
| `prompt_tokens` | Number of input (prompt) tokens. |
| `completion_tokens` | Number of output tokens, including reasoning tokens. |
| `total_tokens` | Total tokens (input + output). |
| `prompt_tokens_details.cached_tokens` | Input tokens served from the prompt cache. |
| `prompt_tokens_details.cache_write_tokens` | Input tokens written to the prompt cache (a newer official field; may be absent). |
| `prompt_tokens_details.audio_tokens` | Audio tokens in the input. |
| `completion_tokens_details.reasoning_tokens` | Reasoning tokens generated by the model. |
| `completion_tokens_details.audio_tokens` | Audio tokens generated by the model. |
| `completion_tokens_details.accepted_prediction_tokens` | With Predicted Outputs, prediction tokens that appeared in the completion. |
| `completion_tokens_details.rejected_prediction_tokens` | With Predicted Outputs, prediction tokens that did not appear in the completion; they are still billed as output. |

?> For models whose format BeeRoute converts (such as Claude and Gemini), `usage` may contain a few extra fields; you can ignore them.

### finish_reason Values

| Value | Meaning |
|------|------|
| `stop` | The model finished naturally or hit a `stop` sequence. |
| `length` | Reached `max_completion_tokens` or the model's output limit. |
| `tool_calls` | The model called a tool. |
| `content_filter` | Content was omitted by a content filter. |
| `function_call` | Deprecated; the model called a legacy function. |

### chat.completion.chunk Object

Each chunk in a streaming response:

| Field | Description |
|------|------|
| `id` | Completion ID; the same for every chunk of a request. |
| `object` | Always `chat.completion.chunk`. |
| `created` | Creation time; the same for every chunk. |
| `model` | The model that generated the completion. |
| `choices` | List of choice deltas, each with `index`, `delta`, `logprobs`, and `finish_reason`. With `include_usage`, the final usage chunk has an empty `choices` array. |
| `choices[].delta` | Incremental content; may contain `role`, `content`, `tool_calls`, `refusal`, and `audio`. |
| `choices[].finish_reason` | null until the end, then one of the values in the table above. |
| `usage` | Present only with `include_usage`: the total usage on the last chunk, null on the others. |
| `service_tier`, `system_fingerprint` | Same as in the `chat.completion` object. |
| `obfuscation` | Random string OpenAI uses to normalize chunk sizes; may be present and can be ignored. |

When tool calls are streamed, each entry in `delta.tool_calls` has an `index`, and the function name and `arguments` arrive across several chunks. Concatenate the `arguments` fragments by `index` before parsing them.

## ❗ Errors

A failed request returns a non-2xx status code with an OpenAI-style `error` object in the body. Common status codes:

| Status | Common causes |
|--------|----------|
| 400 | Invalid request: malformed JSON, missing required fields, a parameter the model does not support, and so on. |
| 401 | Invalid API key: wrong key, or the key is disabled, expired, or out of quota. |
| 403 | Access denied: insufficient account balance, or the key is not allowed to use the model or group. |
| 429 | Too many requests; a rate limit was hit. Retry later. |
| 500 | Internal server error or upstream processing failure; retry later. |
| 503 | No channel is currently available for the model, or the upstream service is temporarily unavailable. |

Errors produced by the BeeRoute gateway itself (such as an invalid key, insufficient balance, or no available channel) look like this; the exact `message` text may vary with the language setting:

```json
{
  "error": {
    "code": "",
    "message": "Invalid token (request id: 20261127120000123456789abcdefgh)",
    "type": "new_api_error"
  }
}
```

Errors from upstream model providers are also returned as an `error` object, usually with `message`, `type`, `param`, and `code` fields. Include the request id at the end of `message` when you contact support. If a streaming request fails after output has started, the error may arrive as a `data:` chunk containing an `error` field, and the stream may end without `[DONE]`.
