# Создание сообщения Claude

**API:** Model API

**Endpoint:** `POST /api/v1/messages`

Эндпоинт, совместимый с Claude Messages API. Установите stream=true, чтобы получать потоковые события сообщений в стиле Claude. Поля запроса, ответа и ошибок валидации соответствуют протоколу Claude Messages; при сбоях инфраструктуры Router также может возвращать очищенный конверт ошибок шлюза.

## 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: `ClaudeMessagesRequest` (`#/components/schemas/ClaudeMessagesRequest`)

```json
{
  "type": "object",
  "required": [
    "model",
    "max_tokens",
    "messages"
  ],
  "properties": {
    "model": {
      "type": "string"
    },
    "max_tokens": {
      "type": "integer",
      "minimum": 1
    },
    "messages": {
      "type": "array",
      "minItems": 1,
      "items": {
        "$ref": "#/components/schemas/ClaudeMessage"
      },
      "description": "Use a document block for a PDF or an image block for a picture. Set source to {type: 'file', file_id: 'felo_file_...'} for an uploaded Felo attachment, {type: 'url', url: 'https://...'} for an HTTPS URL, or provide type, media_type and data for a base64 source. PDF and image URL support are enabled per model."
    },
    "system": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": true
          }
        }
      ]
    },
    "stream": {
      "type": "boolean",
      "default": false
    },
    "temperature": {
      "type": "number",
      "minimum": 0,
      "maximum": 1
    },
    "top_p": {
      "type": "number",
      "minimum": 0,
      "maximum": 1
    },
    "top_k": {
      "type": "integer",
      "minimum": 0
    },
    "stop_sequences": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "tools": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": true
      }
    },
    "tool_choice": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "object",
          "additionalProperties": true
        }
      ]
    },
    "metadata": {
      "type": "object",
      "additionalProperties": true
    },
    "thinking": {
      "type": "object",
      "additionalProperties": true
    },
    "service_tier": {
      "type": [
        "string",
        "null"
      ],
      "default": "default",
      "description": "Сейчас поддерживается только default (стандартный). Если поле опущено, равно null, содержит псевдоним или неподдерживаемую строку, используется значение по умолчанию; другие типы возвращают HTTP 400. Настроенные каналы и цены не меняются. Текстовые API передают стандартное значение провайдера; Decisions и API генерации опускают поле upstream."
    }
  },
  "additionalProperties": true
}
```

Example:

```json
{
  "model": "claude-sonnet-4-5",
  "max_tokens": 256,
  "messages": [
    {
      "role": "user",
      "content": "Write a one-sentence greeting."
    }
  ],
  "stream": false
}
```

## Responses

### 200 — Сообщение Claude или потоковый ответ

**application/json**

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

**text/event-stream**

Schema: string

```json
{
  "type": "string",
  "description": "SSE-события Claude Messages."
}
```

### 400 — Claude invalid_request_error или ошибка валидации запроса в Router

**application/json**

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

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

**application/json**

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

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

**application/json**

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

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

**application/json**

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

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

**application/json**

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

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

**application/json**

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

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

**application/json**

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

## Schema definitions

### ClaudeContentBlock

`#/components/schemas/ClaudeContentBlock`

```json
{
  "type": "object",
  "required": [
    "type"
  ],
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "text",
        "image",
        "document",
        "tool_use",
        "tool_result",
        "thinking"
      ]
    },
    "text": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "input": {
      "type": "object",
      "additionalProperties": true
    },
    "content": {
      "type": [
        "string",
        "array"
      ]
    },
    "source": {
      "type": "object",
      "additionalProperties": true
    }
  },
  "additionalProperties": true
}
```

### ClaudeErrorResponse

`#/components/schemas/ClaudeErrorResponse`

```json
{
  "type": "object",
  "description": "Конверт ошибок, совместимый с Claude Errors API, для запросов Messages.",
  "required": [
    "type",
    "error"
  ],
  "properties": {
    "type": {
      "type": "string",
      "const": "error"
    },
    "error": {
      "type": "object",
      "required": [
        "type",
        "message"
      ],
      "properties": {
        "type": {
          "type": "string"
        },
        "message": {
          "type": "string"
        }
      },
      "additionalProperties": true
    },
    "request_id": {
      "type": "string"
    }
  },
  "additionalProperties": true
}
```

### ClaudeMessage

`#/components/schemas/ClaudeMessage`

```json
{
  "type": "object",
  "required": [
    "role",
    "content"
  ],
  "properties": {
    "role": {
      "type": "string",
      "enum": [
        "user",
        "assistant"
      ]
    },
    "content": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "array",
          "items": {
            "$ref": "#/components/schemas/ClaudeContentBlock"
          }
        }
      ]
    }
  },
  "additionalProperties": true
}
```

### ClaudeMessageResponse

`#/components/schemas/ClaudeMessageResponse`

```json
{
  "type": "object",
  "required": [
    "id",
    "type",
    "role",
    "content",
    "model",
    "stop_reason"
  ],
  "properties": {
    "id": {
      "type": "string"
    },
    "type": {
      "type": "string",
      "const": "message"
    },
    "role": {
      "type": "string",
      "const": "assistant"
    },
    "content": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/ClaudeContentBlock"
      }
    },
    "model": {
      "type": "string"
    },
    "stop_reason": {
      "type": [
        "string",
        "null"
      ]
    },
    "stop_sequence": {
      "type": [
        "string",
        "null"
      ]
    },
    "usage": {
      "$ref": "#/components/schemas/Usage"
    }
  },
  "additionalProperties": true
}
```

### Usage

`#/components/schemas/Usage`

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