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

# Ответ модели

> Генерирует ответ модели в формате OpenAI Chat Completions, обычным JSON или потоком.



## OpenAPI

````yaml ru/openapi/ru-openai-api-openapi.yaml POST /v1/chat/completions
openapi: 3.1.0
info:
  title: ER:LC Россия — OpenAI-Совместимый API
  version: 1.0.0
  description: >-
    OpenAI-совместимые методы Chat Completions, получения моделей и синтеза речи
    ER:LC Россия. Поддерживаемые параметры приведены в описании каждого метода.
servers:
  - url: https://api.erlcrussia.com
    description: Основной сервер
  - url: https://api.erlcrussia.xyz
    description: Резервный сервер
security: []
paths:
  /v1/chat/completions:
    post:
      tags:
        - Chat Completions
      summary: Ответ модели
      description: >-
        Генерирует ответ модели в формате OpenAI Chat Completions, обычным JSON
        или потоком.
      parameters:
        - name: X-Session-ID
          in: header
          required: false
          schema:
            type: string
          description: >-
            Идентификатор сессии диалога (альтернатива полю session_id в теле
            запроса).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatCompletionRequest'
            example:
              model: niya-1
              messages:
                - role: system
                  content: Ты — Ния, официальный ассистент сервера ER:LC Россия.
                - role: user
                  content: Как получить лицензию на оружие в игре?
              stream: false
      responses:
        '200':
          description: Успешный ответ модели или поток чанков (SSE).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatCompletionResponse'
              example:
                id: chatcmpl-9b2f6c1e4a7d4c0e9f1a2b3c
                session_id: session_1726838400000_a1b2c3
                object: chat.completion
                created: 1726838400
                model: niya-1
                choices:
                  - index: 0
                    message:
                      role: assistant
                      content: >-
                        Для получения лицензии на оружие вам необходимо прибыть
                        в полицейский департамент...
                    finish_reason: stop
                usage:
                  prompt_tokens: 812
                  completion_tokens: 96
                  total_tokens: 908
                  completion_tokens_details:
                    reasoning_tokens: 0
                  prompt_tokens_details:
                    cached_tokens: 512
                  cost_credits: 0.42
            text/event-stream:
              schema:
                type: string
                description: >-
                  Поток Server-Sent Events в формате OpenAI. Каждое событие —
                  строка `data: {...}` с объектом `chat.completion.chunk`. В
                  первом чанке `delta.role` равно `assistant`, у каждого чанка
                  есть `finish_reason`: `null`, пока ответ идёт, и `stop` или
                  `tool_calls` в последнем. При `stream_options.include_usage:
                  true` перед концом приходит чанк с `choices: []` и `usage`.
                  Поток заканчивается строкой `data: [DONE]`. Если генерация
                  оборвалась, приходит событие `{"error": {...}}`, а за ним
                  `data: [DONE]`.
              example: >+
                data:
                {"id":"chatcmpl-9b2f6c1e4a7d4c0e9f1a2b3c","object":"chat.completion.chunk","created":1726838400,"model":"niya-1","choices":[{"index":0,"delta":{"role":"assistant","content":"Для
                получения "},"finish_reason":null}]}


                data:
                {"id":"chatcmpl-9b2f6c1e4a7d4c0e9f1a2b3c","object":"chat.completion.chunk","created":1726838400,"model":"niya-1","choices":[{"index":0,"delta":{"content":"лицензии..."},"finish_reason":null}]}


                data:
                {"id":"chatcmpl-9b2f6c1e4a7d4c0e9f1a2b3c","object":"chat.completion.chunk","created":1726838400,"model":"niya-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}


                data:
                {"id":"chatcmpl-9b2f6c1e4a7d4c0e9f1a2b3c","object":"chat.completion.chunk","created":1726838400,"model":"niya-1","choices":[],"usage":{"prompt_tokens":812,"completion_tokens":96,"total_tokens":908}}


                data: [DONE]

          headers:
            x-request-id:
              $ref: '#/components/headers/RequestId'
            openai-processing-ms:
              $ref: '#/components/headers/ProcessingMs'
            x-ratelimit-limit-requests:
              $ref: '#/components/headers/RateLimitRequests'
            x-ratelimit-remaining-requests:
              $ref: '#/components/headers/RateLimitRemainingRequests'
            x-ratelimit-reset-requests:
              $ref: '#/components/headers/RateLimitResetRequests'
        '400':
          description: Некорректное тело запроса.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  message: >-
                    We could not parse the JSON body of your request. Make sure
                    it is valid JSON.
                  type: invalid_request_error
                  param: null
                  code: null
                  erlc_code: '5034'
        '401':
          description: Ключ не передан или недействителен.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  message: >-
                    Incorrect API key provided. Check the key or create a new
                    one in the dashboard.
                  type: invalid_request_error
                  param: null
                  code: invalid_api_key
                  erlc_code: '5008'
        '429':
          description: >-
            Превышен лимит запросов (`type: requests`) или закончились
            AI-кредиты (`type: insufficient_quota`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                rate_limit:
                  value:
                    error:
                      message: Rate limit reached. Please slow down and retry later.
                      type: requests
                      param: null
                      code: rate_limit_exceeded
                      erlc_code: '5016'
                insufficient_quota:
                  value:
                    error:
                      message: >-
                        You exceeded your current quota, please check your plan
                        and billing details.
                      type: insufficient_quota
                      param: null
                      code: insufficient_quota
                      erlc_code: '5038'
        '503':
          description: Модель временно недоступна, повторите запрос позже.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                error:
                  message: AI model temporarily unavailable
                  type: server_error
                  param: null
                  code: '5141'
      security:
        - BearerAuth: []
        - ApiKeyAuth: []
components:
  schemas:
    ChatCompletionRequest:
      type: object
      required:
        - messages
      properties:
        model:
          type: string
          enum:
            - niya-1
            - emmy-1
            - hubert-1
            - default
          default: niya-1
          description: >
            Идентификатор модели:

            - `niya-1` — Ния (основная модель для общих задач и модерации, 1M
            контекст)

            - `emmy-1` — Эмми (интеллектуальная модель с пошаговым рассуждением,
            1M контекст)

            - `hubert-1` — Хуберт (кастомная модель, 1M контекст)
          example: niya-1
        messages:
          type: array
          minItems: 1
          description: Список предшествующих сообщений беседы.
          items:
            $ref: '#/components/schemas/ChatMessage'
        files:
          type: array
          description: >-
            Дополнительный список файлов или изображений, прикреплённых к
            запросу.
          items:
            $ref: '#/components/schemas/FilePart'
        stream:
          type: boolean
          default: false
          description: Включение потоковой передачи ответов Server-Sent Events (SSE).
        stream_options:
          type: object
          properties:
            include_usage:
              type: boolean
              default: false
              description: >-
                Если `true`, перед `data: [DONE]` приходит отдельный чанк с
                пустым `choices` и полем `usage`. Без этого флага `usage` в
                потоке не отправляется.
        thinking:
          type: boolean
          description: Включение режима пошагового размышления (цепочки рассуждений).
          example: true
        surzhyk:
          type: boolean
          default: false
          description: >-
            Для модели hubert-1 включает фирменный суржик. По умолчанию Хуберт
            отвечает на языке последнего сообщения пользователя.
        effort:
          type: string
          enum:
            - low
            - medium
            - high
            - extra
            - max
          description: |
            Степень детализации рассуждений (уровень размышлений):
            - `low` — базовая проверка фактов;
            - `medium` — сбалансированный анализ (по умолчанию);
            - `high` — исчерпывающий пошаговый разбор;
            - `extra` / `max` — предельный уровень аналитики.
          example: medium
        session_id:
          type: string
          description: >-
            Публичный идентификатор сессии чата (UUIDv4). Позволяет сохранять
            контекст между запросами.
          example: f47ac10b-58cc-4372-a567-0e02b2c3d479
        regenerate:
          type: boolean
          description: Флаг принудительной повторной генерации последнего ответа.
        tools:
          type: array
          items:
            type: object
          description: >-
            Инструменты в формате OpenAI. Работают только с агентским ключом
            (`sk-agent-…`); для чат-ключа игнорируются.
        tool_choice:
          description: Выбор инструмента в формате OpenAI.
          oneOf:
            - type: string
            - type: object
        reasoning_effort:
          type: string
          description: Уровень рассуждений в формате OpenAI. То же, что `effort`.
        web_search:
          type: boolean
          description: Разрешить модели поиск в интернете.
      description: >-
        Стандартные поля OpenAI `temperature`, `top_p`, `max_tokens`,
        `max_completion_tokens`, `stop`, `n` и `response_format` принимаются, но
        не применяются.
    ChatCompletionResponse:
      type: object
      properties:
        id:
          type: string
          example: chatcmpl-9b2f6c1e4a7d4c0e9f1a2b3c
        session_id:
          type: string
          example: f47ac10b-58cc-4372-a567-0e02b2c3d479
        object:
          type: string
          example: chat.completion
        created:
          type: integer
          example: 1726838400
        model:
          type: string
          example: niya-1
        choices:
          type: array
          items:
            type: object
            properties:
              index:
                type: integer
                example: 0
              message:
                type: object
                properties:
                  role:
                    type: string
                    example: assistant
                  content:
                    type: string
                    example: Здравствуйте! Чем я могу вам помочь?
                  reasoning:
                    type: string
                    description: Текст цепочки рассуждений модели (если включен thinking).
                  reasoning_content:
                    type: string
                    description: >-
                      Дублирующее поле reasoning для совместимости с различными
                      клиентами (DeepSeek/vLLM формат).
              finish_reason:
                type: string
                example: stop
        usage:
          type: object
          description: >-
            Расход токенов. `prompt_tokens` включает кэшированные токены,
            `total_tokens = prompt_tokens + completion_tokens`. `cost_credits` —
            списанные AI-кредиты.
          properties:
            prompt_tokens:
              type: integer
              example: 812
            completion_tokens:
              type: integer
              example: 96
            total_tokens:
              type: integer
              example: 908
            completion_tokens_details:
              type: object
              properties:
                reasoning_tokens:
                  type: integer
                  example: 0
            prompt_tokens_details:
              type: object
              properties:
                cached_tokens:
                  type: integer
                  example: 512
            cost_credits:
              type: number
              description: Списано AI-кредитов.
              example: 0.42
    ErrorResponse:
      type: object
      description: >-
        Ошибка в формате OpenAI. `code` — строковый код OpenAI
        (`invalid_api_key`, `model_not_found`, `insufficient_quota`,
        `rate_limit_exceeded`) или `null`. Числовой код ER:LC Россия — в
        `erlc_code`, см. [коды ошибок](/ru/documentation/error-codes).
      properties:
        error:
          type: object
          properties:
            message:
              type: string
              example: Insufficient AI Credits
            type:
              type: string
              enum:
                - invalid_request_error
                - insufficient_quota
                - requests
                - server_error
              example: insufficient_quota
            param:
              type:
                - string
                - 'null'
              example: null
            code:
              type:
                - string
                - 'null'
              example: insufficient_quota
            erlc_code:
              type: string
              description: ER:LC Russia numeric error code.
              example: '5038'
    ChatMessage:
      type: object
      required:
        - role
        - content
      properties:
        role:
          type: string
          enum:
            - system
            - user
            - assistant
          description: |
            Роль автора сообщения:
            - `system` — системные инструкции и правила поведения модели;
            - `user` — запрос или реплика пользователя;
            - `assistant` — предыдущий ответ модели для сохранения контекста.
          example: user
        content:
          oneOf:
            - type: string
              description: Текстовое содержимое сообщения.
              example: Привет! Чем ты можешь помочь?
            - type: array
              description: Мультимодальный массив блоков (текст, изображения, файлы).
              items:
                type: object
                properties:
                  type:
                    type: string
                    enum:
                      - text
                      - image_url
                      - file
                  text:
                    type: string
                  image_url:
                    type: object
                    properties:
                      url:
                        type: string
                        example: https://cdn.erlcrussia.com/images/screenshot.png
                  file:
                    type: object
                    properties:
                      url:
                        type: string
                      mime:
                        type: string
                      filename:
                        type: string
    FilePart:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          enum:
            - file
          example: file
        mime:
          type: string
          example: image/png
        filename:
          type: string
          example: screenshot.png
        url:
          type: string
          example: https://cdn.erlcrussia.com/images/screenshot.png
  headers:
    RequestId:
      description: Идентификатор запроса для поддержки.
      schema:
        type: string
        example: req_8f2c1e9b4a7d4c0e9f1a2b3c4d5e6f70
    ProcessingMs:
      description: Время обработки запроса в миллисекундах.
      schema:
        type: integer
        example: 412
    RateLimitRequests:
      description: Лимит запросов в текущем окне.
      schema:
        type: integer
        example: 120
    RateLimitRemainingRequests:
      description: Сколько запросов осталось в текущем окне.
      schema:
        type: integer
        example: 119
    RateLimitResetRequests:
      description: Через сколько сбросится лимит, например `1s` или `6m0s`.
      schema:
        type: string
        example: 1s
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: 'Передача токена авторизации в заголовке Authorization: Bearer <token>.'
    ApiKeyAuth:
      type: apiKey
      in: header
      name: erlcrussia-api-ai-key
      description: Ключ в заголовке erlcrussia-api-ai-key.

````

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