> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.deepmask.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat completions

> Reference for the OpenAI-compatible chat completions and models endpoints, including request rules, sampling options, image input, streaming, and tool calling.

The DeepMask API is OpenAI-compatible. You send chat requests to `POST /v1/chat/completions`, and you list the models your key can use with `GET /v1/models`. Because the API follows the OpenAI format, you can use the official OpenAI SDKs by changing only the base URL and the API key.

DeepMask accepts a defined subset of the OpenAI parameters. A request with an unsupported parameter is refused instead of running without it. Some models ignore some sampling options, such as `top_p` or `seed`, without an error. See [Sampling options](#sampling-options). To make your first call, start with the [Quickstart](https://documentation.deepmask.io/api/quickstart.md).

> [!NOTE]
>
> You need an API key created by an organization admin. Your organization also needs an active Pro, Power, or Enterprise plan with API billing enabled.

> [!NOTE]
>
> The base URL is `https://api.deepmask.io/v1`. Organization admins can also copy it from **Base URL** in **User Settings** > **API**.

## Endpoints

| Method | Path | Description |
| - | - | - |
| `POST` | `/v1/chat/completions` | Generate a model response for a conversation. |
| `GET` | `/v1/models` | List the models your API key can use. |

Only these two endpoints are available. Other OpenAI endpoints, including embeddings and image generation, aren't offered.

* **Most other endpoints:** paths such as `/v1/responses`, `/v1/completions`, and `/v1/images/generations` return `404` with `API_ENDPOINT_NOT_FOUND`. SDK methods that rely on them don't work, including the Responses API (`client.responses`) and `client.models.retrieve()`.
* **Embeddings:** the catalog has no embedding models, so `client.embeddings.create()` fails with an access error, usually `403` with `API_MODEL_NOT_ALLOWED`.

Paths are case-sensitive. A path with a trailing slash, such as `/v1/chat/completions/`, also returns `404`.

## Authentication

Send your API key as a bearer token in the `Authorization` header of every request. `POST` requests also need a JSON content type.

```text theme={null}
Authorization: Bearer sk-...
Content-Type: application/json
```

* Keys start with `sk-`, followed by 64 lowercase hexadecimal characters.
* Send exactly one `Authorization` header. The `Bearer` prefix is case-sensitive.
* A missing, malformed, unknown, or revoked key returns `401` with `API_CREDENTIAL_INVALID`.

To create or revoke keys, see [API keys](https://documentation.deepmask.io/api/keys.md). The examples on this page read the key from the `DEEPMASK_API_KEY` environment variable.

> [!WARNING]
>
> Keep your API key on your server. Don't put it in browser or mobile app code, where anyone who uses your app can read it. Browsers also block calls to the API from your own web pages (CORS), so call it from your backend.

## Create a chat completion

This request sends a system message and a user message to `gpt-4o`. The Python and Node.js examples use the official `openai` package. Install it with `pip install openai` or `npm install openai`. The Node.js examples use ES modules, so save them as `.mjs` files or set `"type": "module"` in `package.json`.

```bash cURL theme={null}
curl https://api.deepmask.io/v1/chat/completions \
  -H "Authorization: Bearer $DEEPMASK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "Explain what an API key is in one sentence."}
    ],
    "max_tokens": 200
  }'
```

```python Python theme={null}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPMASK_API_KEY"],
    base_url="https://api.deepmask.io/v1",
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "Explain what an API key is in one sentence."},
    ],
    max_tokens=200,
)

print(response.choices[0].message.content)
```

```javascript Node.js theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPMASK_API_KEY,
  baseURL: "https://api.deepmask.io/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [
    { role: "system", content: "You are a concise assistant." },
    { role: "user", content: "Explain what an API key is in one sentence." },
  ],
  max_tokens: 200,
});

console.log(response.choices[0].message.content);
```

The response follows the OpenAI format. See [Response](#response) for its fields.

## Request body

| Field | Type | Required | Rules |
| - | - | - | - |
| `model` | string | Yes | The API model ID, such as `gpt-4o`. Your key must have access to the model. |
| `messages` | array | Yes | The conversation so far, with at least one message. See [Messages](#messages). |
| `max_tokens` | integer | No | The maximum number of output tokens, from 1 up to the model's maximum. See [Output length](#output-length). |
| `max_completion_tokens` | integer | No | An alias of `max_tokens` with the same limits. Sending both returns `400` with `API_REQUEST_UNBOUNDED`. |
| `stream` | boolean | No | Set to `true` to receive the response as server-sent events. See [Streaming](#streaming). |
| `stream_options` | object | No | Allowed only with `stream: true`. Its only key is `include_usage`, a boolean. |
| `user` | string | No | An identifier for your end user, up to 100 characters. It can't contain the NUL character (`U+0000`). |
| `tools` | array | No | From 1 to 128 function tools. See [Tool calling](#tool-calling). |
| `tool_choice` | string or object | No | `"auto"`, `"none"`, `"required"`, or a named function. Requires `tools`. |
| `parallel_tool_calls` | boolean | No | Whether the model may return several tool calls in one response. Requires `tools`. |
| `temperature` | number | No | From 0 to 2. |
| `top_p` | number | No | From 0 to 1. |
| `presence_penalty` | number | No | From −2 to 2. |
| `frequency_penalty` | number | No | From −2 to 2. |
| `seed` | integer | No | A whole number that fits in a signed 64-bit integer. |
| `stop` | string or array of strings | No | From 1 to 4 stop sequences. Each sequence is a non-empty string. |
| `n` | integer | No | Only `1`, which is also the default. |

The last seven fields are sampling options. You can send any of them as `null`, which means not set. Some models ignore some of them. See [Sampling options](#sampling-options).

Any other top-level field returns `400` with `API_REQUEST_UNBOUNDED`. A field with the wrong type or a value outside its limits returns the same error. There are three exceptions, which return `400` with `API_REQUEST_INVALID`: a missing or non-string `model`, a `user` value that contains NUL, and a string that contains invalid Unicode.

Organization admins can copy each model's ID from **API model ID** on the **Models** tab in **User Settings** > **API**. If you can't open that page, call [`GET /v1/models`](#list-models) with your key to list the model IDs it can use. A model that isn't assigned to your key returns `403` with `API_MODEL_NOT_ALLOWED`. You can't add models to an existing key, so create a new key to use other models. See [Models](https://documentation.deepmask.io/api/models.md) for the catalog.

### Messages

Each message has a `role` and `content`. System and user messages can send `content` as a string or as an array of content parts.

| Role | Fields | Rules |
| - | - | - |
| `system` | `role`, `content` | `content` is a string or an array of text parts. |
| `user` | `role`, `content` | `content` is a string or an array of text parts and image parts. See [Image input](#image-input). |
| `assistant` | `role`, `content`, `tool_calls` | `content` must be a string. When the message has `tool_calls`, `content` can be `null`. |
| `tool` | `role`, `tool_call_id`, `content`, optional `name` | `tool_call_id` is the `id` of the tool call you're answering, 1–100 characters. `content` must be a string. |

* **Text parts:** a text part has exactly two keys: `type`, set to `"text"`, and `text`, a string. Text parts work on every model.
* **Content arrays:** an array holds 1–256 parts. An empty array is refused.
* **Images:** image parts work only in user messages, and only on the seven models listed under [Image input](#image-input). Other models refuse them, even if they accept images in DeepMask Chat.
* **No other content:** file, audio, and document parts are refused. So is `cache_control` on any part. See [Unsupported parameters](#unsupported-parameters).
* **No `developer` role:** use `system` instead.
* **`name` only on tool messages:** remove `name` from system, user, and assistant messages.
* **Tool calls:** an assistant message can include 1–128 tool calls. Each one has an `id` of 1–100 characters, `type: "function"`, and a `function` object with `name` and `arguments`, a JSON string.
* **At least one user message:** some models refuse a request that contains only a `system` message.
* **No message limit:** you can send as many messages as fit in the model's context window.

> [!TIP]
>
> You can append the assistant `message` from a response to `messages` exactly as your SDK returns it. DeepMask accepts and removes the extra fields that SDKs and reasoning models add, such as empty `refusal` and `annotations` fields, and reasoning content. If `refusal` contains text, send your own assistant message instead.

### Sampling options

Many SDKs, frameworks, and coding agents send sampling options with every request. DeepMask accepts `temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `seed`, `stop`, and `n`. See [Request body](#request-body) for the type and range of each one.

* **Ranges:** each range includes its end values, so DeepMask accepts `temperature: 2`. A value outside its range returns `400` with `API_REQUEST_UNBOUNDED`. Some models accept a narrower `temperature` range. See [Options that some models ignore](#options-that-some-models-ignore).
* **Numbers only:** send numbers as JSON numbers. A string such as `"0.5"` or a boolean is refused.
* **Whole numbers for `seed`:** a value such as `1.5` or `"42"` is refused. So is a value that doesn't fit in a signed 64-bit integer. Very large seeds can lose precision, so keep `seed` within ±9,007,199,254,740,991 for exact results.
* **`null` means not set:** DeepMask treats an option sent as `null` as if you left it out.
* **`n` only as 1:** `n: 1` is accepted because it's the default. Any other value, such as `2` or `0`, returns `400` with `API_REQUEST_UNBOUNDED`. To get several answers, send a separate request for each one.
* **`stop` as a string or an array:** a string counts as one stop sequence. An array can hold 1 to 4 strings. An empty array or an array with more than 4 strings is refused.
* **No empty stop sequences:** an empty string (`""`) is refused, on its own or in an array.
* **Blank stop sequences:** on the Claude models, DeepMask removes stop sequences that contain only whitespace, such as `"\n\n"`. If no sequence is left, the request runs without `stop`. `gpt-4o`, `gpt-4.1`, `o3-mini`, and `mistral-large-3` receive them unchanged. The other models ignore `stop`. See [Options that some models ignore](#options-that-some-models-ignore).
* **Request size:** `stop` counts toward the 32 MiB limit for messages and tools. See [Request size](#request-size).

#### Options that some models ignore

Not every model supports every sampling option. When a model doesn't support an option, DeepMask accepts it but doesn't send it to the model. The option then has no effect. You get no error, and you're billed as if you hadn't sent it.

| Models | Ignored options |
| - | - |
| `gpt-4o`, `gpt-4.1`, `mistral-large-3` | None |
| `gpt-5.4` | `stop`, `presence_penalty`, `frequency_penalty` |
| `o3-mini` | `top_p`, `presence_penalty`, `frequency_penalty`, and any `temperature` other than `1` |
| `haiku-4.5`, `sonnet-4.5`, `opus-4.5`, `opus-4.6`, `sonnet-4.6` | `top_p`, `presence_penalty`, `frequency_penalty`, `seed` |
| `opus-4.7`, `opus-4.8`, `opus-5`, `sonnet-5`, `haiku-5.5`, `sonnet-5.5`, `opus-5.5` | `temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `seed` |
| `deepseek-v3.2`, `glm-4.7`, `glm-4.7-flash`, `glm-5`, `kimi-k2.5`, `minimax-m2.1`, `minimax-m2.5`, `nemotron-3-super`, `qwen3-235b-2507` | `stop`, `presence_penalty`, `frequency_penalty`, `seed` |

* **`temperature` above 1:** `haiku-4.5`, `sonnet-4.5`, `opus-4.5`, `opus-4.6`, and `sonnet-4.6` accept `temperature` only from 0 to 1. So do `deepseek-v3.2`, `glm-4.7`, `glm-4.7-flash`, `glm-5`, `kimi-k2.5`, `minimax-m2.1`, `minimax-m2.5`, `nemotron-3-super`, and `qwen3-235b-2507`. The model provider refuses a higher value with a `4xx` status and `API_UPSTREAM_REJECTED`. That refusal isn't billed.
* **`temperature` on Claude 4.7 and later models:** these models ignore `temperature`, as the table shows. A value above 1 therefore has no effect on them.
* **Other provider refusals:** a model provider can also refuse a value that its model doesn't support. That refusal also returns `API_UPSTREAM_REJECTED` and isn't billed.

### Unsupported parameters

These parameters and inputs return `400` with `API_REQUEST_UNBOUNDED`, unless the row names another code.

| Not supported | What to do instead |
| - | - |
| `response_format`, including JSON mode, structured outputs, and the SDKs' `parse()` helpers | Describe the format in your prompt, or define a function tool and read its arguments. |
| `n` other than 1 | Send a separate request for each answer you need. |
| `logprobs`, `top_logprobs` | Remove them. |
| `logit_bias` | Remove it. |
| `top_k` | Remove it. Use `temperature` or `top_p` instead. |
| `reasoning_effort` | Remove it. |
| `functions`, `function_call` | Use `tools` and `tool_choice`. |
| `metadata`, `store`, or any other field not listed under [Request body](#request-body) | Remove them. |
| File, audio, or document parts, or any other part without an `image_url` field, such as `input_text` | Send text as a string or in text parts. |
| Text parts in `assistant` or `tool` messages | Send their `content` as a string. |
| `cache_control` on a text part | Remove it. |
| `cache_control` on an image part (`API_IMAGE_INVALID`) | Remove it. |
| Images in any message other than a user message, such as `system`, `assistant`, `tool`, or `developer` messages (`API_IMAGE_INPUT_UNSUPPORTED`) | Send images in user messages. |
| Images on a model without image input (`API_IMAGE_INPUT_UNSUPPORTED`) | Use one of the models listed under [Image input](#image-input). |
| Image links, such as `https://` URLs (`API_IMAGE_URL_UNSUPPORTED`) | Send the image as a base64 data URL. |
| `detail: "high"`, or any `detail` other than `"auto"` or `"low"` (`API_IMAGE_INVALID`) | Leave `detail` out, or set it to `"auto"` or `"low"`. |
| The `developer` role, or `name` on system, user, and assistant messages | Use `system`, and remove `name`. |
| Tools with a `type` other than `function` | Define function tools. |
| An empty `tools` array, or `tool_choice` or `parallel_tool_calls` without `tools` | Leave the fields out when you have no tools. |
| `stream_options` without `stream: true` | Send `stream_options` only with streaming. |

> [!WARNING]
>
> Some frameworks, agent libraries, and SDK wrappers add parameters such as `reasoning_effort`, `top_k`, `logprobs`, `response_format`, or an empty `tools` array, sometimes by default. DeepMask returns `400` with `API_REQUEST_UNBOUNDED` for those requests. Configure your tool so it doesn't send these parameters, or call the API with the plain OpenAI SDK as shown on this page. Sampling options within their ranges are accepted, so you don't need to remove them. On some models, keep `temperature` at 1 or below. See [Sampling options](#sampling-options).

### Output length

`max_tokens` sets the maximum number of output tokens for a response. `max_completion_tokens` works the same way. Send only one of them. For all token limits in one place, see [Token limits](https://documentation.deepmask.io/api/limits.md#token-limits).

* **No DeepMask default for most models:** if you omit `max_tokens`, DeepMask adds no limit of its own. The model's default output length applies, and it can be lower than the model's maximum. Set `max_tokens` when you expect long answers.
* **GLM 4.7 models:** `glm-4.7` and `glm-4.7-flash` stop at 65,536 output tokens unless you set `max_tokens`.
* **Per-model maximum:** each model accepts up to its own maximum, listed under **Max output tokens** in [Models](https://documentation.deepmask.io/api/models.md#available-models). A larger value returns `400` with `API_REQUEST_UNBOUNDED`.
* **Reasoning tokens count:** for reasoning models such as `o3-mini`, and for the Claude models that always think, hidden reasoning tokens count toward `max_tokens`. They're billed as output tokens. You can't turn thinking off for these Claude models. See [Reasoning and thinking tokens](https://documentation.deepmask.io/api/models.md#reasoning-and-thinking-tokens) for which models always think.
* **Truncated answers:** when an answer reaches the limit, `finish_reason` is `length`. With a low limit, reasoning can use up the budget before the visible answer is complete.
* **Long requests:** a request can run for up to 15 minutes. The OpenAI SDKs time out after 10 minutes by default and then retry, and DeepMask bills both requests. For long answers, raise the client `timeout`. See [Retries in the OpenAI SDKs](https://documentation.deepmask.io/api/errors.md#retries-in-the-openai-sdks).
* **At the 15-minute limit:** DeepMask stops the request. Its outcome is then unclear, so it isn't billed unless usage for it still arrives later. See [Request duration](https://documentation.deepmask.io/api/limits.md#request-duration).

### Request size

For all size and duration limits in one place, see [Request size and duration](https://documentation.deepmask.io/api/limits.md#request-size-and-duration).

* **Body:** a request body can be up to 32 MiB. A larger body returns `413` with `API_REQUEST_INVALID`.
* **Uncompressed:** send the body without compression. A body with a `Content-Encoding` header such as `gzip`, `deflate`, or `br` returns `400` with `API_REQUEST_INVALID`. The OpenAI SDKs send uncompressed bodies.
* **Base64 images:** the base64 text of your images counts toward the 32 MiB. 20 MB of images is about 26.7 MB of base64, which leaves about 6.9 MB for the rest of the request.
* **Messages, tools, and stop sequences:** messages, tool definitions, `tool_choice`, and `stop` together can be up to 32 MiB as UTF-8 JSON. Base64 images count here too. Tool schemas count with their `$ref`s resolved. Above that, the request returns `400` with `API_REQUEST_UNBOUNDED`.
* **Bodies in flight:** the request bodies that one key has in flight can total up to 64 MiB. A request that would go over returns `429` with `API_CONCURRENCY_LIMIT`. With large images, send fewer requests in parallel. See [Per-key requests in flight](https://documentation.deepmask.io/api/limits.md#per-key-requests-in-flight).
* **Context window:** in practice, the model's context window is the limit. A prompt that doesn't fit is refused by the model provider with a `4xx` status and `API_UPSTREAM_REJECTED`. That refusal isn't billed. See [Models](https://documentation.deepmask.io/api/models.md) for each model's context window.

## Image input

You can send images in user messages to seven models: `gpt-4o`, `gpt-4.1`, and the Claude models `haiku-4.5`, `sonnet-4.5`, `opus-4.5`, `opus-4.6`, and `sonnet-4.6`. The model reads the images together with your text and answers in text. The same list is in [Image input](https://documentation.deepmask.io/api/models.md#image-input) on the Models page.

* **Base64 only:** you send each image inside the request as a base64 data URL. DeepMask refuses image links and never downloads them.
* **Other models refuse images:** a valid image part sent to any other model returns `400` with `API_IMAGE_INPUT_UNSUPPORTED`.
* **Not in the model list:** `GET /v1/models` doesn't show which models accept images.

### Send an image

This example sends a local PNG file, `photo.png`, with a question to `gpt-4o`. For another format, change `image/png` in the data URL to match the file. The cURL example writes the request to a file first, because a large image doesn't fit in a single command-line argument.

```bash cURL theme={null}
# Encode the image as base64 on one line. This works on macOS and Linux.
IMAGE_BASE64=$(base64 < photo.png | tr -d '\n')

# Write the request body to a file.
cat > request.json <<EOF
{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "What is in this picture?"},
        {"type": "image_url", "image_url": {"url": "data:image/png;base64,$IMAGE_BASE64"}}
      ]
    }
  ],
  "max_tokens": 300
}
EOF

curl https://api.deepmask.io/v1/chat/completions \
  -H "Authorization: Bearer $DEEPMASK_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @request.json
```

```python Python theme={null}
import base64
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPMASK_API_KEY"],
    base_url="https://api.deepmask.io/v1",
)

with open("photo.png", "rb") as image_file:
    image_base64 = base64.b64encode(image_file.read()).decode("ascii")

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What is in this picture?"},
                {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
            ],
        },
    ],
    max_tokens=300,
)

print(response.choices[0].message.content)
```

```javascript Node.js theme={null}
import { readFile } from "node:fs/promises";
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPMASK_API_KEY,
  baseURL: "https://api.deepmask.io/v1",
});

const imageBase64 = (await readFile("photo.png")).toString("base64");

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: "What is in this picture?" },
        { type: "image_url", image_url: { url: `data:image/png;base64,${imageBase64}` } },
      ],
    },
  ],
  max_tokens: 300,
});

console.log(response.choices[0].message.content);
```

The response has the same format as any other chat completion. See [Response](#response).

### Image parts

An image part goes in the `content` array of a user message. You can combine image parts and text parts in any order.

```json theme={null}
{
  "role": "user",
  "content": [
    {"type": "text", "text": "What is in this picture?"},
    {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo...", "detail": "auto"}}
  ]
}
```

* **Part keys:** an image part has exactly two keys: `type`, set to `"image_url"`, and `image_url`. Other keys, such as `cache_control`, are refused.
* **`image_url` keys:** `image_url` is an object with `url` and an optional `detail`. Other keys, such as `format`, are refused. A string in place of the object is also refused.
* **`detail`:** leave it out, or set it to `"auto"` or `"low"`. Other values, including `"high"` and `null`, are refused. On `gpt-4o` and `gpt-4.1`, `"low"` uses far fewer tokens. The Claude models accept `detail` but ignore it.
* **User messages only:** an image part in a `system`, `assistant`, or `tool` message is refused.
* **Images without text:** a user message can contain image parts and no text part.
* **Chat Completions format:** use `image_url` and `text` parts. Responses API parts are refused. For example, an `input_image` part with a base64 data URL returns `API_IMAGE_INVALID`, and an `input_text` part returns `API_REQUEST_UNBOUNDED`.

### Image data

The `url` must be a data URL in the form `data:image/<type>;base64,<data>`. Nothing else can appear before the comma.

* **Formats:** PNG, JPEG, GIF, and WebP. Write the type in lowercase: `image/png`, `image/jpeg`, `image/gif`, or `image/webp`. Other formats, such as SVG, HEIC, BMP, or PDF, are refused.
* **JPEG label:** `image/jpg` is also accepted. DeepMask sends it to the model as `image/jpeg`.
* **Matching type:** the declared type must match the image bytes. For example, a JPEG file labeled `image/png` is refused.
* **Standard base64:** use the standard alphabet (`A–Z`, `a–z`, `0–9`, `+`, and `/`) with `=` padding. URL-safe base64, which uses `-` and `_`, is refused. So is base64 without its padding.
* **One line:** line breaks in the base64 are refused. GNU `base64` on Linux wraps lines by default, so use `base64 -w 0` or remove the line breaks.
* **Animated images:** animated WebP images are refused. Animated GIFs are accepted, but every frame must fit within the pixel limit. A model provider can refuse a GIF it can't read, so send still images when you can.
* **No links:** `https://`, `http://`, and other URLs are refused. DeepMask doesn't download them.

### Image limits

These limits apply to each request. The count and the total size include the images in every message, including earlier turns of the conversation.

| Models | Images | Size per image | Size of all images | Pixels per side |
| - | - | - | - | - |
| `haiku-4.5`, `sonnet-4.5`, `opus-4.5`, `opus-4.6`, `sonnet-4.6` | 20 | 3.75 MB | 20 MB | 8,000 |
| `gpt-4o`, `gpt-4.1` | 20 | 5 MB | 20 MB | 8,000 |

* **Decoded size:** sizes are of the decoded image, not of the base64 text. 1 MB is 1,000,000 bytes.
* **Pixels:** each side of an image must be from 1 to 8,000 pixels.
* **Over a limit:** the request returns `400` with `API_IMAGE_INVALID`.
* **Large photos:** phone photos can be larger than 3.75 MB, and some phones save them as HEIC. Before you encode a photo, save it as JPEG with its longest side at about 2,000 pixels. The model provider scales large images down anyway, so the model sees about the same detail.
* **Long conversations:** to stay within the limits, remove images from earlier turns that the model no longer needs.
* **Request body:** the base64 text also counts toward the 32 MiB request body. See [Request size](#request-size).

### Image errors

Image refusals return `400` before the request reaches the model, so you aren't billed for them.

| Code | Cause | What to do |
| - | - | - |
| `API_IMAGE_INPUT_UNSUPPORTED` | The model doesn't accept images, or an image part is in a message other than a user message. | Use a model with image input, and send images in user messages. |
| `API_IMAGE_URL_UNSUPPORTED` | The image is a link, such as an `https://` URL, instead of a base64 data URL. | Encode the image as base64 and send it as a data URL. |
| `API_IMAGE_INVALID` | The image part has the wrong keys or `detail`, an unsupported format, invalid base64, or a type that doesn't match the bytes. It's also returned when the request is over an image limit. | Fix the image part. Don't retry it unchanged. |

* **Image checks come first:** DeepMask checks the shape of each image part before it checks whether the model accepts images. On a model without image input, a link still returns `API_IMAGE_URL_UNSUPPORTED`, and `detail: "high"` still returns `API_IMAGE_INVALID`.
* **Find the cause:** `API_IMAGE_INVALID` doesn't say which rule failed. On macOS and Linux, `file photo.png` shows the real format of the file and its size in pixels. Compare them with the type in the data URL and with the [image limits](#image-limits).
* **Other parts:** a request that also contains a file, audio, or document part returns `API_REQUEST_UNBOUNDED`.
* **Provider refusals:** if the model provider can't process an image that passed these checks, the request fails with `API_UPSTREAM_REJECTED`. Depending on the model, the status is the provider's own `4xx` status or `502`. You aren't billed for it. Check the image, for example by converting it to PNG, instead of retrying it unchanged. See [Provider errors](https://documentation.deepmask.io/api/errors.md#provider-errors-4xx-502-or-503).

### How images are billed

Images are billed as input tokens. Image tokens are part of `prompt_tokens` and are billed at the model's **Input** rate. There's no separate image price.

* **No separate count:** `usage` doesn't report image tokens or the number of images.
* **Tokens per image:** the count depends on the image size and the model. In DeepMask's measurements, a large image used up to about 1,500 tokens on the Claude models, about 1,450 on `gpt-4.1`, and about 1,700 on `gpt-4o`. A 512 × 512 pixel image used about 250 to 370 tokens.
* **`detail: "low"`:** on `gpt-4o` and `gpt-4.1`, an image with `"low"` used about 85 to 105 tokens.
* **Large images are scaled down:** the model provider scales large images down before the model reads them. An 8,000 × 8,000 pixel image cost no more tokens than the large images above.
* **Many images:** at about 1,700 tokens each, 20 large images add about 34,000 input tokens.
* **Repeated images:** on `gpt-4o` and `gpt-4.1`, an image that repeats in later requests can be billed at the cached input rate. See [Cached input](https://documentation.deepmask.io/api/models.md#cached-input).
* **Exact counts:** provider token rules can change. Read `usage.prompt_tokens` in each response for the exact count.

## Response

A successful request returns a chat completion object in the OpenAI format.

```json theme={null}
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1762790400,
  "model": "gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "An API key is a secret token that identifies your app when it calls an API."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 27,
    "completion_tokens": 18,
    "total_tokens": 45
  }
}
```

* `model` is the API model ID you sent, such as `gpt-4o`.
* `choices[0].message` holds the answer. When the model calls tools, `content` can be `null` and `tool_calls` lists the calls.
* `usage` reports the input (`prompt_tokens`) and output (`completion_tokens`) tokens of the request.

Responses can include additional fields. Ignore any fields your app doesn't use.

### Finish reasons

The most common `finish_reason` values are:

| Value | Meaning |
| - | - |
| `stop` | The model finished its answer. |
| `length` | The answer reached `max_tokens` or the model's output limit. |
| `tool_calls` | The model wants you to run one or more tools. See [Tool calling](#tool-calling). |
| `content_filter` | A content filter stopped the answer. Several Claude models can decline a request this way through the provider's safety classifiers. See [How pricing works](https://documentation.deepmask.io/api/models.md#how-pricing-works) for which ones. You're billed for the response. |

## Streaming

Set `stream` to `true` to receive the answer as server-sent events while the model writes it. Add `stream_options: {"include_usage": true}` to also receive the token counts.

```bash cURL theme={null}
curl -N https://api.deepmask.io/v1/chat/completions \
  -H "Authorization: Bearer $DEEPMASK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Write a haiku about the sea."}],
    "stream": true,
    "stream_options": {"include_usage": true}
  }'
```

```python Python theme={null}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPMASK_API_KEY"],
    base_url="https://api.deepmask.io/v1",
)

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a haiku about the sea."}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print(f"\nTokens: {chunk.usage.prompt_tokens} in, {chunk.usage.completion_tokens} out")
```

```javascript Node.js theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPMASK_API_KEY,
  baseURL: "https://api.deepmask.io/v1",
});

const stream = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Write a haiku about the sea." }],
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  const text = chunk.choices[0]?.delta?.content;
  if (text) process.stdout.write(text);
  if (chunk.usage) {
    console.log(`\nTokens: ${chunk.usage.prompt_tokens} in, ${chunk.usage.completion_tokens} out`);
  }
}
```

The response has the content type `text/event-stream`. Each event is a `data:` line with a chat completion chunk, and the stream ends with `data: [DONE]`. A shortened stream looks like this:

```text theme={null}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","model":"gpt-4o","choices":[{"index":0,"delta":{"content":"Waves fold into foam"}}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","model":"gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","model":"gpt-4o","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":17,"total_tokens":31}}

data: [DONE]
```

* **Events arrive as they're ready:** DeepMask forwards each event as soon as it's complete.
* **Empty chunks are left out:** every chunk you receive has at least one choice. The only exception is the usage chunk.
* **Usage on request:** the final chunk with a `usage` object is sent only when you set `include_usage` to `true`. Its `choices` array can be empty, so check it before you read `choices[0]`.
* **Errors before the stream starts:** if a streaming request is refused before the first chunk, you get a normal JSON error with an HTTP error status.
* **Errors during the stream:** if an error happens after the stream has started, you receive an event with an `error` object instead of a chunk, for example `data: {"error":{"message":"DeepMask API request could not be completed.","type":"api_error","code":"API_UPSTREAM_REJECTED"}}`. Check each event for an `error` field.
* **Streams that stop early:** if a request reaches the 15-minute request limit, or the connection fails on DeepMask's side, the stream closes without an error event and without `data: [DONE]`. With raw HTTP, treat a stream that ends without `data: [DONE]` as incomplete. With the OpenAI SDKs, which hide `[DONE]`, treat a stream with no chunk carrying a `finish_reason` as incomplete. See [Errors in streamed responses](https://documentation.deepmask.io/api/errors.md#errors-in-streamed-responses).
* **Unclear outcome:** a stream that ends with an error event or stops early on DeepMask's or the provider's side has an unclear outcome. It isn't billed unless usage for it still arrives later. More than 20 unclear outcomes in any 24 hours pause your organization's requests. See [Unclear outcomes](https://documentation.deepmask.io/api/limits.md#unclear-outcomes).

> [!NOTE]
>
> If your client disconnects during a stream, the request still runs to completion and is billed. To limit what an abandoned response can cost, set `max_tokens`.

## Tool calling

Tool calling lets the model ask your app to run a function, such as looking up data. The model never runs the function itself. Your code runs it and sends the result back.

**1. Send your tools**

Add `tools` to your request. Each tool is a function with a `name`, a `description`, and a JSON Schema in `parameters`.

**2. Check for tool calls**

When the model wants to use a tool, `finish_reason` is `tool_calls` and `message.tool_calls` lists the calls. Each call has an `id`, the function `name`, and its `arguments` as a JSON string.

**3. Run the functions**

Parse the arguments and run the matching function in your code.

**4. Send the results**

Append the assistant message and one `tool` message per call, with the call's `id` as `tool_call_id`. Send the request again with the same `tools`. Repeat until `finish_reason` is `stop`.

This example shows a full round trip with a `get_weather` function.

```bash cURL theme={null}
# 1. Send the question and the tool definition.
curl https://api.deepmask.io/v1/chat/completions \
  -H "Authorization: Bearer $DEEPMASK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "What is the weather in Berlin?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {"city": {"type": "string"}},
          "required": ["city"]
        }
      }
    }]
  }'

# 2. The response has finish_reason "tool_calls". Run the function.
#    Copy the assistant message from the first response, then add one tool
#    message per call. Use each call's id as tool_call_id. Send the same tools.
curl https://api.deepmask.io/v1/chat/completions \
  -H "Authorization: Bearer $DEEPMASK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "What is the weather in Berlin?"},
      {
        "role": "assistant",
        "content": null,
        "tool_calls": [{
          "id": "call_abc123",
          "type": "function",
          "function": {"name": "get_weather", "arguments": "{\"city\":\"Berlin\"}"}
        }]
      },
      {"role": "tool", "tool_call_id": "call_abc123", "content": "{\"city\":\"Berlin\",\"temperature_c\":18}"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {"city": {"type": "string"}},
          "required": ["city"]
        }
      }
    }]
  }'
```

```python Python theme={null}
import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPMASK_API_KEY"],
    base_url="https://api.deepmask.io/v1",
)

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

def get_weather(city):
    return {"city": city, "temperature_c": 18}  # Replace with your own lookup.

messages = [{"role": "user", "content": "What is the weather in Berlin?"}]

response = client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
message = response.choices[0].message

if message.tool_calls:
    messages.append(message)  # Send the SDK message back as-is.
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

    final = client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
    print(final.choices[0].message.content)
else:
    print(message.content)
```

```javascript Node.js theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPMASK_API_KEY,
  baseURL: "https://api.deepmask.io/v1",
});

const tools = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Get the current weather for a city.",
    parameters: {
      type: "object",
      properties: { city: { type: "string" } },
      required: ["city"],
    },
  },
}];

function getWeather({ city }) {
  return { city, temperature_c: 18 }; // Replace with your own lookup.
}

const messages = [{ role: "user", content: "What is the weather in Berlin?" }];

const response = await client.chat.completions.create({ model: "gpt-4o", messages, tools });
const message = response.choices[0].message;

if (message.tool_calls?.length) {
  messages.push(message); // Send the SDK message back as-is.
  for (const call of message.tool_calls) {
    const result = getWeather(JSON.parse(call.function.arguments));
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }

  const final = await client.chat.completions.create({ model: "gpt-4o", messages, tools });
  console.log(final.choices[0].message.content);
} else {
  console.log(message.content);
}
```

The first request returns a response like this one, shortened here. Copy its assistant `message` into the second request, and use each call's `id` as `tool_call_id`.

```json theme={null}
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": { "name": "get_weather", "arguments": "{\"city\":\"Berlin\"}" }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}
```

> [!TIP]
>
> Send the same `tools` array with every request in a tool-calling conversation. Some models refuse a request whose history contains tool calls when `tools` is missing.

### Tool choice

`tool_choice` controls whether and how the model uses your tools. It requires `tools`.

| Value | Effect |
| - | - |
| `"auto"` | The model decides whether to call a tool. This is the default. |
| `"none"` | The model answers without calling a tool. |
| `"required"` | The model must call at least one tool. |
| `{"type": "function", "function": {"name": "get_weather"}}` | The model must call the named function. |

### Model-specific tool restrictions

Every model supports `tools` with `tool_choice: "auto"`. Some models don't support every other tool option. A request that uses an unsupported option returns `400` with `API_REQUEST_UNBOUNDED` before it reaches the model, so it isn't billed.

| Models | `"none"` | `"required"` | Named function | `parallel_tool_calls` |
| - | - | - | - | - |
| `gpt-4o`, `gpt-4.1`, `gpt-5.4`, `o3-mini`, `mistral-large-3` | Yes | Yes | Yes | Yes |
| `haiku-4.5`, `sonnet-4.5`, `opus-4.5`, `opus-4.6`, `sonnet-4.6`, `opus-4.7`, `opus-4.8`, `opus-5`, `haiku-5.5` | No | Yes | Yes | Yes |
| `sonnet-5`, `sonnet-5.5`, `opus-5.5` | No | No | No | Yes |
| `deepseek-v3.2`, `glm-4.7`, `glm-4.7-flash`, `glm-5`, `kimi-k2.5`, `minimax-m2.1`, `minimax-m2.5`, `nemotron-3-super`, `qwen3-235b-2507` | No | Yes | No | No |

* **`parallel_tool_calls`:** on models marked **No**, the request is refused when the field is present, whatever its value. Leave it out.
* **Forced tool choice:** `sonnet-5`, `sonnet-5.5`, and `opus-5.5` don't accept `"required"` or a named function. Use `"auto"`, and describe in your prompt when the model should use a tool.
* **`mistral-large-3`:** give every function a `description`. Without one, the provider refuses the request with `422` and `API_UPSTREAM_REJECTED`. That refusal isn't billed.

If a model can't apply one of your tool settings, DeepMask refuses the request instead of running it without that setting.

### Tool definition rules

> [accordion] Function definitions
>
> * Each entry in `tools` has exactly two keys: `type`, set to `"function"`, and `function`.
> * `function` can contain `name`, `description`, `parameters`, and `strict`. Other keys are refused.
> * `name` is 1–64 characters: letters, digits, underscores, and hyphens.
> * `description` is a string.
> * `parameters` is a JSON Schema object. It can be nested up to 32 levels deep, and every number must be finite.
> * `strict` is a boolean.

> [accordion] Schemas with \$ref
>
> * Only local references work: `#`, `#/$defs/name`, `#/definitions/name`, or another JSON pointer inside the same schema.
> * Remote references and pointers with an escaped slash (`%2F`) are refused.
> * A schema that uses `$ref` can't contain `$id` below its root (or a root `$id` with a `#` fragment), `$anchor`, `$dynamicRef`, `$dynamicAnchor`, `$recursiveRef`, or `$recursiveAnchor`. It also can't declare a draft-03 or draft-04 `$schema`.
> * A property literally named `$ref` or `$id` is refused.
> * After its references are resolved, a tool's schema can be at most about 32 times the size of your `tools` array as sent and at most 64 levels deep. Messages, the resolved tools, `tool_choice`, and `stop` must still fit in 32 MiB together.
> * Recursive schemas, where a reference points back to a schema that contains it, work only on `gpt-4o`, `gpt-4.1`, `gpt-5.4`, `o3-mini`, and `mistral-large-3`.

## List models

`GET /v1/models` returns the models your API key can use. It uses the same authentication as chat requests.

```bash cURL theme={null}
curl https://api.deepmask.io/v1/models \
  -H "Authorization: Bearer $DEEPMASK_API_KEY"
```

```python Python theme={null}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPMASK_API_KEY"],
    base_url="https://api.deepmask.io/v1",
)

for model in client.models.list():
    print(model.id)
```

```javascript Node.js theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPMASK_API_KEY,
  baseURL: "https://api.deepmask.io/v1",
});

for await (const model of client.models.list()) {
  console.log(model.id);
}
```

```json theme={null}
{
  "object": "list",
  "data": [
    { "id": "gpt-4.1", "object": "model", "created": 0, "owned_by": "deepmask" },
    { "id": "gpt-4o", "object": "model", "created": 0, "owned_by": "deepmask" }
  ]
}
```

* The list contains only the models assigned to the key, sorted by ID.
* A model that DeepMask removes from the catalog disappears from the list, even if it was assigned to the key.
* Models that DeepMask adds later aren't added to existing keys.
* `created` is always `0` and `owned_by` is always `deepmask`.
* Retrieving a single model with `GET /v1/models/{id}` isn't supported and returns `404`.

Listing models isn't billed. Use [Models](https://documentation.deepmask.io/api/models.md) to compare context windows and prices.

## What you're billed for

You pay for the input and output tokens each request uses, including images, tool definitions, tool calls, tool results, and hidden reasoning tokens. For how images are counted, see [How images are billed](#how-images-are-billed). See [How pricing works](https://documentation.deepmask.io/api/models.md#how-pricing-works) for rates, cached input, and long-prompt pricing.

A request has an unclear outcome when DeepMask can't tell whether it finished. Examples are a server error or timeout at the model provider, a stream that breaks off midway, and a request that reaches the 15-minute limit. DeepMask doesn't charge for these requests. On its own, an unclear outcome doesn't pause your organization's requests. If usage for such a request still arrives later, DeepMask bills that usage like any other usage. More than 20 unclear outcomes in any 24 hours pause your organization's requests until DeepMask resolves them. See [Unclear outcomes](https://documentation.deepmask.io/api/limits.md#unclear-outcomes).

For which refused and interrupted requests are billed, see [Are failed requests billed?](https://documentation.deepmask.io/api/errors.md#are-failed-requests-billed).

## Common request errors

Errors from these endpoints share one JSON shape. The `message` never changes, so handle errors by the HTTP status and `error.code`.

```json theme={null}
{
  "error": {
    "message": "DeepMask API request could not be completed.",
    "type": "api_error",
    "code": "API_REQUEST_UNBOUNDED"
  }
}
```

| Status | Code | Cause |
| - | - | - |
| `400` | `API_REQUEST_INVALID` | The body isn't valid JSON or isn't a JSON object, `Content-Type` isn't `application/json`, the body is compressed, `model` is missing or not a string, `user` contains NUL, or a string contains invalid Unicode. |
| `413` | `API_REQUEST_INVALID` | The body is larger than 32 MiB. |
| `400` | `API_REQUEST_UNBOUNDED` | The request uses an unsupported field, value, message shape, content part, or tool option. |
| `400` | `API_IMAGE_INPUT_UNSUPPORTED`, `API_IMAGE_URL_UNSUPPORTED`, `API_IMAGE_INVALID` | DeepMask can't accept an image in the request, for example because the model has no image input, the image is a link, or it's over a limit. See [Image errors](#image-errors) for each code. |
| `403` | `API_MODEL_NOT_ALLOWED` | The key has no access to the model, or the model is no longer in the catalog. |
| `404` | `API_ENDPOINT_NOT_FOUND` | The path or method isn't supported. |
| `4xx`, `502`, or `503` | `API_UPSTREAM_REJECTED` | The model provider refused the request (`4xx`), for example because the prompt is too long or the model doesn't accept a sampling value, or had a server error (`502` or `503`). A `502` can also be a refused image. None of these is billed, unless usage for a server error still arrives later. |

For authentication, billing, rate limit, and spending cap errors, see [Errors and retries](https://documentation.deepmask.io/api/errors.md). For rate, token, and budget limits, see [Limits and fair use](https://documentation.deepmask.io/api/limits.md).

## Related pages

> [card] [Quickstart](https://documentation.deepmask.io/api/quickstart.md)
>
> Create a key and make your first request.

> [card] [Models](https://documentation.deepmask.io/api/models.md)
>
> Browse model IDs, context windows, and pricing.

> [card] [API keys](https://documentation.deepmask.io/api/keys.md)
>
> Create keys, choose their models, and revoke them.

> [card] [Limits and fair use](https://documentation.deepmask.io/api/limits.md)
>
> See the rate, token, and budget limits that apply to your requests.

> [card] [Errors and retries](https://documentation.deepmask.io/api/errors.md)
>
> Handle every error code and learn which errors to retry.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.