# OpenAI-compatible Chat Completions

Source: [OpenAI-compatible Chat Completions](<https://docs.gptunnel.ru/en/api/chat-completions/>)

<a id="_top"></a>
[Get an API key](<https://docs.gptunnel.ru/en/#get-an-api-key>) to send requests.

> **Note: Deprecated models**
>
> If the provider retires a model, the API uses its designated replacement and charges the original model’s rate. The response headers and the `warnings` array indicate the substitution. The `model` field still contains the ID you requested. If no replacement exists, the API returns `410`. See [Deprecated models](<https://docs.gptunnel.ru/en/getting-started/deprecated-models/>).

<a id="the-chat-dialogue"></a>
## The chat dialogue

`POST https://gptunnel.ru/v1/chat/completions`

Get the full model response as JSON or receive it in an SSE stream. Choose an available model from the [catalog](<https://docs.gptunnel.ru/en/api/models/>) and pass the conversation history in `messages`.

### Request headers

| Parameter | Type | Required? | Description |
| --- | --- | --- | --- |
| `Authorization` | `string` | Required | API key |

### Request body

| Parameter | Type | Required? | Description |
| --- | --- | --- | --- |
| `model`<a id="chat-request-model"></a> | `string` | Required | Exact ID from GET /v1/models catalogue, e.g. gpt-6-luna |
| `messages`<a id="chat-request-messages"></a> | `array` | Required | Conversation history that provides context for the request. |
| `stream`<a id="chat-request-stream"></a> | `bool` | Optional | Set to true to stream the response over SSE. By default, the API returns the full response as JSON. |
| `stream_options`<a id="chat-request-stream_options"></a> | `object` | Optional | With stream: true, pass {"include\_usage":true} to request token usage statistics. |
| `max_tokens`<a id="chat-request-max_tokens"></a> | `number` | Optional | Maximum number of tokens in the response. The supported limit depends on the model. |
| `max_completion_tokens`<a id="chat-request-max_completion_tokens"></a> | `number` | Optional | Alternative name used by newer OpenAI SDKs. It applies when max\_tokens is omitted. |
| `temperature`<a id="chat-request-temperature"></a> | `number` | Optional | Controls sampling randomness on a scale from 0 to 1. |
| `top_p`<a id="chat-request-top_p"></a> | `number` | Optional | Nucleus sampling. Does not apply to Claude models. |
| `frequency_penalty`<a id="chat-request-frequency_penalty"></a> | `number` | Optional | Penalty for repeated tokens. Does not apply to Claude models. |
| `presence_penalty`<a id="chat-request-presence_penalty"></a> | `number` | Optional | Presence penalty. Does not apply to Claude models. |
| `stop`<a id="chat-request-stop"></a> | `string \| string[]` | Optional | One or more stop sequences. The model ends its response before a matching sequence. |
| `functions`<a id="chat-request-functions"></a> | `object` | Optional | Definitions of functions |
| `tools`<a id="chat-request-tools"></a> | `object[]` | Optional | Definitions of tools available to models |
| `tool_choice`<a id="chat-request-tool_choice"></a> | `string \| object` | Optional | Tool choice: auto, none, required, or an object such as {"type":"function","function":{"name":"your\_function"}}. |
| `parallel_tool_calls`<a id="chat-request-parallel_tool_calls"></a> | `bool` | Optional | Set to false to limit the model to one tool call per response. |
| `response_format`<a id="chat-request-response_format"></a> | `object` | Optional | Use {"type":"json\_object"} or set type to json\_schema and include the json\_schema object. See Structured output for a complete example. |
| `reasoning_effort`<a id="chat-request-reasoning_effort"></a> | `string` | Optional | Reasoning effort, for example none, low, medium, or high. See Reasoning effort. |
| `useWalletBalance`<a id="chat-request-useWalletBalance"></a> | `bool` | Optional | Use a personal account |
| `web_search`<a id="chat-request-web_search"></a> | `bool` | Optional | Enable web search for this request. |
| `obfuscate`<a id="chat-request-obfuscate"></a> | `bool` | Optional | Mask personal data (PII) with placeholders before sending the prompt to the model. GPTunneL restores the original values in the response (alpha). |
| `obfuscate_patterns`<a id="chat-request-obfuscate_patterns"></a> | `object[]` | Optional | Custom regex patterns for masking when obfuscate is enabled. Supply up to 20 entries of the form { pattern, label? }. |

> **Note: What does not apply to Claude models**
>
> Claude models ignore OpenAI fields with no equivalent in Anthropic’s request schema, including `top_p`, `frequency_penalty`, `presence_penalty`, `seed`, `logprobs`, `n` and `logit_bias`. The API still processes the request. It maps `stop`, `parallel_tool_calls` and `max_completion_tokens` to Anthropic’s equivalents. For other model families, supported parameters depend on the model and the route.

<a id="personal-data-obfuscation-obfuscate"></a>
### Personal Data Obfuscation (obfuscate)

With `obfuscate: true`, GPTunneL replaces detected personal data in message text with placeholders before sending the request to the model. The original values are restored in the response, including streamed text and tool call arguments. The detector does not process images, and coverage depends on what it recognizes. If the masking service is unavailable, the API returns `503` without sending raw data to the provider.

See [Personal Data Obfuscation](<https://docs.gptunnel.ru/en/api/pii-obfuscation/>) for recognized data types, guarantees, and limitations.

Obfuscation costs 280 ₽ per 1 million tokens of message text scanned, in addition to the model’s price. There is no obfuscation charge for response tokens. See [pricing](<https://docs.gptunnel.ru/en/api/pii-obfuscation/#value>).

<a id="reasoning-effort-reasoning_effort"></a>
### Reasoning effort (reasoning\_effort)

Reasoning models use additional tokens before answering. Use `reasoning_effort` to control how much reasoning a model performs.

| Value | Behavior |
| --- | --- |
| `none` | Request to disable reasoning if the model supports it |
| `low` | Low reasoning level |
| `medium` | Medium reasoning level |
| `high` | High reasoning level |

```json
{
  "model": "deepseek-v4-flash",
  "messages": [{ "role": "user", "content": "Сколько будет 17 × 23?" }],
  "reasoning_effort": "none"
}
```

Parameter availability depends on the model. Reasoning tokens are included in `completion_tokens` and billed as response tokens. Disabling reasoning can reduce token usage and waiting time.

> **Note: Other parameter names**
>
> For compatibility, other options are accepted: `reasoning: {"effort": "none"}`, `reasoning: {"enabled": false}`, `thinking: {"type": "disabled"}`. Recommended method — `reasoning_effort`; do not send multiple options in a single request.

> **Caution: Models without reasoning**
>
> For models without reasoning support, do not send the parameter — the request may return an error `400`.

<a id="mandatory-function-call"></a>
#### Mandatory function call

On `deepseek-v4-flash` and `deepseek-v4-pro`, forced function calls are incompatible with reasoning. If you send `tool_choice: "required"` or `tool_choice: {"type": "function", ...}`, also set `reasoning_effort: "none"`. Otherwise, the request takes longer than usual.

<a id="structured-response-response_format"></a>
### Structured response (response\_format)

The `response_format` parameter accepts two forms.

- `{"type": "json_object"}` asks the model to return a single JSON object.
- `{"type": "json_schema", "json_schema": {"schema": {...}}}` requests a response that conforms to the supplied schema.

In OpenAI models, the parameter works as in the original API. For Claude, both forms are translated into Anthropic with different result guarantees. In other models, the field is passed directly to the provider without any modifications — see the note at the end of the section.

**`json_schema`** uses Claude’s native structured output. Anthropic requires `additionalProperties: false` on each object node. GPTunneL adds it where no value was supplied. GPTunneL does not resolve `$ref` or expand `definitions`. Inline referenced definitions in your schema before sending the request. A model that does not support structured output returns HTTP `400`.

With **`json_object`** on Claude, GPTunneL adds a system instruction asking for a single JSON object. If the model wraps the response in a Markdown code fence, GPTunneL removes the fence. Valid JSON is not guaranteed in this mode. Validate the response and retry if needed.

> **Caution: JSON object in Claude stream**
>
> When a Claude request uses both `response_format: {"type": "json_object"}` and `stream: true`, the API buffers the response text and sends it in one chunk before the final event. This lets the API strip any Markdown code fence once it has received the closing fence. The stream still uses SSE and includes `[DONE]` and `usage` as usual. Tool calls and reasoning still stream incrementally. To receive the JSON text incrementally, use `json_schema`.

If a strict JSON is needed without this layer, Claude models have a second entry point — [Anthropic-compatible `/v1/messages`](<https://docs.gptunnel.ru/en/api/anthropic-messages/>). The schema is transmitted via `output_config`; the limitations for models are described on the page for this format.

> **Caution: Support for this format in other models**
>
> The behavior above applies to OpenAI and Claude models. For other models, including Gemini, DeepSeek, and Qwen, GPTunneL forwards `response_format` to the provider unchanged.

 <a id="checked-json-schema-request"></a>
 
<a id="verified-json-schema-request"></a>
#### Verified JSON Schema request

With `gpt-6-luna`, the request below returned HTTP `200` and the string `{"answer":4}` in `choices[0].message.content`. For JSON mode without a schema, replace the entire `response_format` value with `{"type":"json_object"}`. Keep the word “JSON” in the user message. This variant returned the same string with the same model.

```bash
curl --fail-with-body --silent --show-error \
  --url 'https://gptunnel.ru/v1/chat/completions' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --json '{
    "model": "gpt-6-luna",
    "messages": [
      {
        "role": "user",
        "content": "Return JSON with an integer answer field. What is 2 + 2?"
      }
    ],
    "max_completion_tokens": 128,
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "answer",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": { "answer": { "type": "integer" } },
          "required": ["answer"],
          "additionalProperties": false
        }
      }
    }
  }'
```

<a id="example-request"></a>
### Example request

Set `GPTUNNEL_API_KEY` and select the standard response or stream.

<a id="tab-panel-0-0"></a>
**JSON**

<a id="tab-panel-1-0"></a>
**Python**

```python
import json
import os
from urllib.request import Request, urlopen

body = {
    'model': "gpt-6-luna",
    'messages': [{"role":"user","content":"What's 2 + 2? Answer with a digit."}],
    'max_completion_tokens': 128,
}
request = Request(
    'https://gptunnel.ru/v1/chat/completions',
    method='POST',
    headers={
        'Authorization': os.environ['GPTUNNEL_API_KEY'],
        'Content-Type': 'application/json',
    },
    data=json.dumps(body).encode('utf-8'),
)
with urlopen(request, timeout=30) as response:
    print(json.load(response)['choices'][0]['message']['content'])
```

<a id="tab-panel-1-1"></a>
**cURL**

```bash
curl --fail-with-body --silent --show-error \
  --url 'https://gptunnel.ru/v1/chat/completions' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --json '{
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "What'\''s 2 + 2? Answer with a digit."
    }
  ],
  "max_completion_tokens": 128
}'
```

<a id="tab-panel-1-2"></a>
**JavaScript (Node.js)**

```javascript
const apiKey = process.env.GPTUNNEL_API_KEY
if (!apiKey) throw new Error("Set GPTUNNEL_API_KEY")

const response = await fetch('https://gptunnel.ru/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: apiKey,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "What's 2 + 2? Answer with a digit."
    }
  ],
  "max_completion_tokens": 128
}),
})

if (!response.ok) throw new Error(await response.text())
console.log((await response.json()).choices[0].message.content)
```

<a id="tab-panel-0-1"></a>
**Streaming (SSE)**

<a id="tab-panel-2-0"></a>
**Python**

```python
import json
import os
from urllib.request import Request, urlopen

body = {
    'model': "gpt-6-luna",
    'messages': [{"role":"user","content":"What's 2 + 2? Answer with a digit."}],
    'max_completion_tokens': 128,
    'stream': True,
}
request = Request(
    'https://gptunnel.ru/v1/chat/completions',
    method='POST',
    headers={
        'Authorization': os.environ['GPTUNNEL_API_KEY'],
        'Content-Type': 'application/json',
    },
    data=json.dumps(body).encode('utf-8'),
)
with urlopen(request, timeout=30) as response:
    for line in response:
        print(line.decode('utf-8'), end='', flush=True)
```

<a id="tab-panel-2-1"></a>
**cURL**

```bash
curl --fail-with-body --silent --show-error --no-buffer \
  --url 'https://gptunnel.ru/v1/chat/completions' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --json '{
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "What'\''s 2 + 2? Answer with a digit."
    }
  ],
  "max_completion_tokens": 128,
  "stream": true
}'
```

<a id="tab-panel-2-2"></a>
**JavaScript (Node.js)**

```javascript
const apiKey = process.env.GPTUNNEL_API_KEY
if (!apiKey) throw new Error("Set GPTUNNEL_API_KEY")

const response = await fetch('https://gptunnel.ru/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: apiKey,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "What's 2 + 2? Answer with a digit."
    }
  ],
  "max_completion_tokens": 128,
  "stream": true
}),
})

if (!response.ok) throw new Error(await response.text())
for await (const chunk of response.body) process.stdout.write(chunk)
```

<a id="example-response"></a>
### Example response

Read the response text from `choices[0].message.content` and the total cost from `usage.total_cost`. Here is an excerpt from a verified response using `gpt-6-luna`.

```json
{
  "object": "chat.completion",
  "model": "gpt-6-luna",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "4" },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 20,
    "completion_tokens": 19,
    "total_tokens": 39,
    "prompt_cost": 0.0004,
    "completion_cost": 0.0019,
    "total_cost": 0.0023
  }
}
```

<a id="streaming-response-sse"></a>
### Streaming response (SSE)

Select **Streaming (SSE)** in the request example above. With `stream: true`, the server responds as `text/event-stream`. In the response below, `gpt-6-luna` returned the digit `4`:

```text
data: {"choices":[{"index":0,"delta":{"content":"4"},"finish_reason":null}]}
```

The [streaming guide](<https://docs.gptunnel.ru/en/api/chat-completions/streaming/>) explains how to assemble text and tool arguments, record `usage` and detect an interrupted connection.

<a id="internet-search"></a>
### Internet Search

Set `"web_search": true` in the request body. The example below returned an answer with links to MDN documentation when run with `gpt-6-luna`.

<a id="example-of-a-search-request"></a>
#### Example of a search request

```json
{
  "model": "gpt-6-luna",
  "max_completion_tokens": 128,
  "messages": [
    {
      "role": "user",
      "content": "Найди официальную страницу MDN про Server-sent events. Ответь одним предложением со ссылкой."
    }
  ],
  "web_search": true
}
```

<a id="response-and-sources"></a>
#### Response and sources

The API returns sources in `choices[].message.annotations`. This excerpt shows one source from the verified response.

```json
{
  "title": "Using server-sent events - Web APIs | MDN",
  "url": "https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events"
}
```

In a stream, look for sources in `choices[].delta.annotations`. The `usage` object includes the tokens and cost of model calls for search and the final response.

<a id="prompt-caching-and-billing"></a>
### Prompt caching and billing

For Claude models, GPTunneL automatically enables prompt caching at the provider. Caching can speed up requests with the same long prefix, such as a system prompt, instructions, or a catalog. You can also set `cache_control` breakpoints on message blocks or pass `prompt_cache_key` for OpenAI-compatible models. The request format stays the same.

Billing depends on the account that pays for the request.

**Personal account.** All prompt tokens are charged at the model’s standard input rate, regardless of provider-side cache hits. GPTunneL retains any cache savings. Billable input for the same request remains consistent.

**Business account.** An organization owner or administrator enables prompt caching in the business dashboard under **API** → **Prompt caching in API**. It is off by default.

- **Enabled.** Cache reads cost less than regular input and cache writes cost more. GPTunneL sets Claude cache breakpoints even if you omit `cache_control`. The first request with a new long prefix writes it to the cache and costs more. A repeated request with the same prefix can read the cache and costs less. Claude uses Anthropic multipliers relative to the regular input price: ×0.1 for reads, ×1.25 for a 5-minute write, and ×2.0 for a 1-hour write. Other model families offer different read discounts, such as ×0.5 for OpenAI models, and charge standard input rates for writes.
- **Disabled.** GPTunneL adds no breakpoints and removes `cache_control` and `prompt_cache_key` from your request. All prompt tokens are charged at the standard input rate. Some providers, such as OpenAI, still cache automatically. This automatic cache has no effect on the price when the setting is off.

The provider’s cache counters appear in `usage` when available:

```json
{
  "usage": {
    "prompt_tokens": 12480,
    "prompt_tokens_details": { "cached_tokens": 11900, "cache_write_tokens": 520 },
    "completion_tokens": 210,
    "total_tokens": 12690,
    "prompt_cost": 0.3744,
    "completion_cost": 0.0189,
    "total_cost": 0.3933
  }
}
```

- `prompt_tokens` is the total prompt token count, including cache reads and writes.
- `prompt_tokens_details.cached_tokens` is the number of prompt tokens read from cache.
- `prompt_tokens_details.cache_write_tokens` is the number written by this request. The field name follows OpenRouter. It appears when the provider reports cache writes, for example Claude or OpenRouter. Providers with fully automatic caching may not report writes.
- `prompt_cost` is the input cost for your tariff. With caching off it is `prompt_tokens` multiplied by the input price. With caching on, the relevant multipliers apply.

Streaming returns the same fields in the last chunk containing `usage`. To see cost and cache usage by key and model, go to the business dashboard and open **Analytics** → **API**.

> **Note: Claude-compatible endpoint**
>
> On `/v1/messages` (Anthropic Messages API for Claude Code and other compatible clients), the client sets `cache_control` breakpoints. Anthropic rates apply: ×0.1 for reads, ×1.25 for a 5-minute write, and ×2.0 for a 1-hour write. If the organization disables API caching, GPTunneL removes `cache_control` here as well and charges all prompt tokens at the standard input rate.

<a id="errors"></a>
### Errors

Check the HTTP status, then read `error.type`, `error.code`, and `error.param`. When `error.param` is set, it identifies the field to check in the request body. For errors from other services, see [API Error Diagnostics](<https://docs.gptunnel.ru/en/getting-started/api-errors/>).

**Unknown model (404)** <a id="chat-invalid-model"></a>

Find the exact ID in the [catalog of models available to your key](<https://docs.gptunnel.ru/en/api/models/>) and pass it in the [`model` field](<https://docs.gptunnel.ru/en/api/chat-completions/#chat-request-model>). For an unknown ID, the verified response is shown below.

```json
{
  "error": {
    "message": "Model not found",
    "type": "invalid_model_error",
    "param": "model",
    "code": null
  }
}
```

**No model field (400)** <a id="chat-missing-model"></a>

Include [`model`](<https://docs.gptunnel.ru/en/api/chat-completions/#chat-request-model>) as a top-level field alongside `messages`.

```json
{
  "error": {
    "message": "model is required",
    "type": "invalid_request_error",
    "param": "model",
    "code": null
  }
}
```

| HTTP | What to check |
| --- | --- |
| `401` | Check that the [`Authorization` header](<https://docs.gptunnel.ru/en/#get-an-api-key>) contains an active API key. |
| `402` | Check the [balance](<https://docs.gptunnel.ru/en/getting-started/balance/>) of the account selected for the request. |
| `403` / `model_not_allowed` | Check the allowed models in your key settings and the [model catalog](<https://docs.gptunnel.ru/en/api/models/>). |
| `503` / `obfuscation_unavailable` | The [PII masking service](<https://docs.gptunnel.ru/en/api/pii-obfuscation/>) is temporarily unavailable. |
