# Создание чат-завершения

**API:** Model API

**Endpoint:** `POST /api/v1/chat/completions`

OpenAI-совместимый API Chat Completions. Установите stream=true, чтобы получать Server-Sent Events. Формат ответа и конверт ошибок соответствуют Chat Completions/OpenAI-совместимому формату.

## Base URL

- `https://openapi.felo.ai` — Боевая среда

## Authentication

- `FeloBearerAuth` (http bearer) — API-ключ Felo, передаваемый как `Authorization: Bearer <key>`.
- `FeloApiKey` (apiKey in header `X-API-Key`) — API-ключ Felo, передаваемый как `X-API-Key: <key>`.

## Parameters

| Name | In | Required | Type | Description |
| --- | --- | --- | --- | --- |
| `X-Felo-Channel` | header | no | string, default: "default" | Упорядоченные публичные коды каналов через запятую. Опустите этот заголовок, чтобы использовать значение по умолчанию; default должен использоваться только сам по себе. В режиме wallet значение по умолчанию просматривает эффективный публичный порядок каналов модели в обратном направлении, пропускает неопубликованные и недоступные каналы и выбирает провайдера первого доступного канала. Оно включает доступные эндпоинты этого провайдера с тем же upstream ID модели и уровнем обслуживания. Явные каналы проверяются в порядке, указанном клиентом; отправляется только группа провайдера первого канала. Автоматического переключения на других провайдеров нет. Устаревшие заголовки провайдеров не могут переопределить маршрутизацию по каналам. |

## Request body

Required: **yes**

### application/json

Schema: `ChatCompletionRequest` (`#/components/schemas/ChatCompletionRequest`)

```json
{
  "type": "object",
  "required": [
    "model",
    "messages"
  ],
  "properties": {
    "model": {
      "type": "string"
    },
    "messages": {
      "type": "array",
      "minItems": 1,
      "items": {
        "$ref": "#/components/schemas/ChatMessage"
      }
    },
    "stream": {
      "type": "boolean",
      "default": false
    },
    "temperature": {
      "type": "number",
      "minimum": 0
    },
    "top_p": {
      "type": "number",
      "minimum": 0,
      "maximum": 1
    },
    "n": {
      "type": "integer",
      "minimum": 1
    },
    "max_tokens": {
      "type": "integer",
      "minimum": 1
    },
    "max_completion_tokens": {
      "type": "integer",
      "minimum": 1
    },
    "stop": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        {
          "type": "null"
        }
      ]
    },
    "tools": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": true
      }
    },
    "tool_choice": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "object",
          "additionalProperties": true
        }
      ]
    },
    "response_format": {
      "type": "object",
      "additionalProperties": true
    },
    "user": {
      "type": "string"
    },
    "service_tier": {
      "type": [
        "string",
        "null"
      ],
      "default": "default",
      "description": "Сейчас поддерживается только default (стандартный). Если поле опущено, равно null, содержит псевдоним или неподдерживаемую строку, используется значение по умолчанию; другие типы возвращают HTTP 400. Настроенные каналы и цены не меняются. Текстовые API передают стандартное значение провайдера; Decisions и API генерации опускают поле upstream."
    }
  },
  "additionalProperties": true
}
```

Example:

```json
{
  "model": "gpt-5.5",
  "messages": [
    {
      "role": "user",
      "content": "Write a one-sentence greeting."
    }
  ],
  "stream": false
}
```

## Responses

### 200 — Чат-завершение или потоковый ответ

**application/json**

Schema: `ChatCompletionResponse` (`#/components/schemas/ChatCompletionResponse`)

**text/event-stream**

Schema: string

```json
{
  "type": "string",
  "description": "Фрагменты SSE с событиями данных chat.completion.chunk."
}
```

### 400 — Некорректный запрос, модель или сопоставление провайдера

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

### 401 — Недействительный или отсутствующий API-ключ Felo

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

### 402 — Недостаточно средств на балансе

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

### 403 — Аккаунт не имеет права использовать модель. Отключённые модели также отклоняются до вызова upstream. Уже принятые запросы и задачи продолжают выполняться.

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

### 429 — Достигнут лимит расходов или запросов

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

### 502 — Сбой запроса к upstream-провайдеру

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

### 503 — Провайдер или сервис биллинга недоступен

**application/json**

Schema: `OpenAIErrorResponse` (`#/components/schemas/OpenAIErrorResponse`)

## Schema definitions

### ChatChoice

`#/components/schemas/ChatChoice`

```json
{
  "type": "object",
  "properties": {
    "index": {
      "type": "integer"
    },
    "message": {
      "$ref": "#/components/schemas/ChatMessage"
    },
    "finish_reason": {
      "type": [
        "string",
        "null"
      ]
    },
    "logprobs": {
      "type": [
        "object",
        "null"
      ],
      "additionalProperties": true
    }
  },
  "additionalProperties": true
}
```

### ChatCompletionResponse

`#/components/schemas/ChatCompletionResponse`

```json
{
  "type": "object",
  "required": [
    "id",
    "object",
    "choices"
  ],
  "properties": {
    "id": {
      "type": "string"
    },
    "object": {
      "type": "string",
      "description": "Обычно chat.completion для непотоковых ответов."
    },
    "created": {
      "type": "integer",
      "format": "int64"
    },
    "model": {
      "type": "string"
    },
    "choices": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/ChatChoice"
      }
    },
    "usage": {
      "$ref": "#/components/schemas/Usage"
    },
    "system_fingerprint": {
      "type": "string"
    }
  },
  "additionalProperties": true
}
```

### ChatMessage

`#/components/schemas/ChatMessage`

```json
{
  "type": "object",
  "required": [
    "role",
    "content"
  ],
  "properties": {
    "role": {
      "type": "string",
      "enum": [
        "system",
        "developer",
        "user",
        "assistant",
        "tool"
      ]
    },
    "content": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": true
          }
        },
        {
          "type": "null"
        }
      ]
    },
    "name": {
      "type": "string"
    },
    "tool_call_id": {
      "type": "string"
    },
    "tool_calls": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": true
      }
    }
  },
  "additionalProperties": true
}
```

### OpenAIErrorResponse

`#/components/schemas/OpenAIErrorResponse`

```json
{
  "type": "object",
  "description": "Конверт ошибок, совместимый с OpenAI. Router может включать code и message без всех необязательных полей upstream.",
  "required": [
    "error"
  ],
  "properties": {
    "error": {
      "type": "object",
      "required": [
        "message"
      ],
      "properties": {
        "message": {
          "type": "string"
        },
        "type": {
          "type": "string",
          "description": "Тип ошибки, совместимый с OpenAI, если он передан."
        },
        "param": {
          "type": [
            "string",
            "null"
          ]
        },
        "code": {
          "type": [
            "string",
            "null"
          ]
        }
      },
      "additionalProperties": true
    }
  },
  "additionalProperties": true
}
```

### Usage

`#/components/schemas/Usage`

```json
{
  "type": "object",
  "description": "Объект использования провайдера. Поля зависят от эндпоинта и провайдера.",
  "additionalProperties": true
}
```
