---
title: "Создать chat completion"
method: POST
path: "/v1/chat/completions"
tags: ["Chat"]
---

# Создать chat completion

`POST /v1/chat/completions`

## Request

- Base URL: `https://api.hubris.pw`
- URL: `https://api.hubris.pw/v1/chat/completions`
- Auth: one of:
  - HTTP bearer
  - OAuth 2 (authorization code, authorization URL `https://api.hubris.pw/oauth/authorize`, token URL `https://api.hubris.pw/oauth/token`, scopes: `chat:write`)

OpenAI-совместимый chat completions endpoint.

При `stream: true` возвращает Server-Sent Events стрим из chunk-ов в формате `chat.completion.chunk`.
Подробности SSE-формата — на странице [Streaming](/docs/api/streaming).

Hubris автоматически добавляет `stream_options: { include_usage: true }` ко всем stream-запросам, поэтому usage приходит в последнем chunk-е перед `[DONE]`.

## Request body

- ChatCompletionRequest
  - `model` string, required
  - `models` string[]: Список fallback-моделей. Если основная (`model`) недоступна — попробует следующие по порядку. Биллинг по фактически использованной (см. `model` в ответе).
  - `messages` Message[], required
    - union
      - SystemMessage
        - `role` 'system', required
        - `content` union, required
          - string
          - ContentPart[]
            - union
              - …
        - `name` string
        - `cache_control` object, nullable: Маркер кеша на весь элемент — для клиентов, которые ставят его сюда. Основное место — `cache_control` на content-блоке.
          - `type` 'ephemeral', required
          - `ttl` '5m' | '1h'
      - UserMessage
        - `role` 'user', required
        - `content` union, required
          - string
          - ContentPart[]
            - union
              - …
        - `name` string
        - `cache_control` object, nullable: Маркер кеша на весь элемент — для клиентов, которые ставят его сюда. Основное место — `cache_control` на content-блоке.
          - `type` 'ephemeral', required
          - `ttl` '5m' | '1h'
      - AssistantMessageInput
        - `role` 'assistant', required
        - `content` union
          - string
          - TextContentPart[]
            - `type` 'text', required
            - `text` string, required
            - `cache_control` CacheControl
              - …
          - unknown
        - `tool_calls` object[]
          - `id` string, required
          - `type` 'function', required
          - `function` object, required
            - `name` string, required
            - `arguments` string, required: JSON-строка с аргументами функции.
          - `cache_control` object, nullable: Маркер кеша на весь элемент — для клиентов, которые ставят его сюда. Основное место — `cache_control` на content-блоке.
            - `type` 'ephemeral', required
            - `ttl` '5m' | '1h'
        - `name` string
        - `refusal` string, nullable
        - `images` GeneratedImage[]
          - `type` 'image_url', required
          - `image_url` object, required
            - `url` string, required: Base64 data URL вида `data:image/png;base64,...`
        - `audio` AudioOutput
          - `id` string
          - `data` string: Аудио ответа в base64 (формат — из запроса `audio.format`).
          - `transcript` string: Текстовая расшифровка сказанного.
          - `expires_at` number
        - `cache_control` object, nullable: Маркер кеша на весь элемент — для клиентов, которые ставят его сюда. Основное место — `cache_control` на content-блоке.
          - `type` 'ephemeral', required
          - `ttl` '5m' | '1h'
      - ToolMessage
        - `role` 'tool', required
        - `content` union, required
          - string
          - TextContentPart[]
            - `type` 'text', required
            - `text` string, required
            - `cache_control` CacheControl
              - …
        - `tool_call_id` string, required
        - `cache_control` object, nullable: Маркер кеша на весь элемент — для клиентов, которые ставят его сюда. Основное место — `cache_control` на content-блоке.
          - `type` 'ephemeral', required
          - `ttl` '5m' | '1h'
  - `tools` ToolDefinition[]
    - union
      - FunctionToolDefinition
        - `type` 'function', required
        - `function` object, required
          - `name` string, required
          - `description` string
          - `parameters` object: JSON Schema объект с описанием параметров функции. Без него — функция без аргументов.
          - `strict` boolean, nullable
        - `cache_control` object, nullable: Маркер кеша на весь элемент — для клиентов, которые ставят его сюда. Основное место — `cache_control` на content-блоке.
          - `type` 'ephemeral', required
          - `ttl` '5m' | '1h'
      - ServerToolDefinition
        - `type` string, required
  - `tool_choice` union
    - 'none' | 'auto' | 'required'
    - object
      - `type` 'function', required
      - `function` object, required
        - `name` string, required
  - `parallel_tool_calls` boolean
  - `response_format` union
    - object
      - `type` 'text', required
    - object
      - `type` 'json_object', required
    - object
      - `type` 'json_schema', required
      - `json_schema` object, required
        - `name` string, required
        - `description` string
        - `schema` object, required
        - `strict` boolean
  - `temperature` number
  - `top_p` number
  - `n` integer
  - `stop` union
    - string
    - string[]
  - `max_tokens` integer
  - `max_completion_tokens` integer
  - `frequency_penalty` number
  - `presence_penalty` number
  - `logit_bias` object
  - `seed` integer
  - `logprobs` boolean
  - `top_logprobs` integer
  - `modalities` string[]: Какие модальности должна вернуть модель. По умолчанию `["text"]`. Для генерации изображений: `["image","text"]` (модели типа gemini-flash-image) либо `["image"]` (модели типа flux/sdxl). Для голосового ответа: `["text","audio"]` вместе с полем `audio` и обязательным `stream: true`. Поддерживается только моделями, у которых соответствующая модальность есть в `output_modalities`.
  - `audio` object: Настройки голосового ответа. Требует `modalities: ["text","audio"]` и `stream: true`.
    - `voice` string, required: Голос озвучки, например `alloy`.
    - `format` string, required: Формат аудио ответа: `wav`, `mp3`, `pcm16` и т.п.
  - `image_config` object: Параметры image-gen моделей: aspect_ratio (`1:1`, `16:9`, `9:16` и т.д.), image_size (`0.5K`, `1K`, `2K`, `4K`), а также model-specific поля. Конкретный набор зависит от модели — см. карточку модели в каталоге.
  - `stream` boolean
  - `stream_options` StreamOptions
    - `include_usage` boolean: Hubris автоматически выставляет true для всех stream-запросов. Указывать необязательно.
  - `user` string
  - `reasoning_effort` 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'

## Response `200`

Успешный ответ. При `stream: false` — `chat.completion`. При `stream: true` — `text/event-stream` с chunk-ами `chat.completion.chunk`.

- ChatCompletionResponse
  - `id` string, required
  - `object` 'chat.completion', required
  - `created` integer, required: Unix-timestamp в секундах.
  - `model` string, required
  - `choices` Choice[], required
    - `index` integer, required
    - `message` AssistantMessage, required
      - `role` 'assistant', required
      - `content` union
        - string
        - TextContentPart[]
          - `type` 'text', required
          - `text` string, required
          - `cache_control` CacheControl
            - `type` 'ephemeral', required
            - `ttl` '5m' | '1h'
        - unknown
      - `tool_calls` ToolCall[]
        - `id` string, required
        - `type` 'function', required
        - `function` object, required
          - `name` string, required
          - `arguments` string, required: JSON-строка с аргументами функции.
      - `name` string
      - `refusal` string, nullable
      - `images` GeneratedImage[]
        - `type` 'image_url', required
        - `image_url` object, required
          - `url` string, required: Base64 data URL вида `data:image/png;base64,...`
      - `audio` AudioOutput
        - `id` string
        - `data` string: Аудио ответа в base64 (формат — из запроса `audio.format`).
        - `transcript` string: Текстовая расшифровка сказанного.
        - `expires_at` number
    - `finish_reason` 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call', nullable, required
    - `logprobs` unknown
  - `usage` Usage, required
    - `prompt_tokens` integer, required
    - `completion_tokens` integer, required
    - `total_tokens` integer, required
    - `completion_tokens_details` object
      - `reasoning_tokens` integer
    - `prompt_tokens_details` object
      - `cached_tokens` integer
  - `system_fingerprint` string

## Other responses

- `400`: Невалидное тело запроса
- `401`: Невалидный API-ключ
- `402`: Недостаточно средств на балансе
- `404`: Модель не найдена
- `429`: Превышен дневной лимит ключа
- `502`: Ошибка апстрима
- `503`: Курс ЦБ РФ временно недоступен
- `504`: Таймаут апстрима

---

[API](https://skmtc.dev/hubris/apis/hubris-api.md) · [All operations](https://skmtc.dev/hubris/apis/hubris-api/llms.txt) · [OpenAPI document](https://skmtc.dev/hubris/apis/hubris-api/revisions/79ea91ed8f10?raw)
