{
  "openapi": "3.1.0",
  "info": {
    "title": "WorkAI API",
    "version": "1.0.0",
    "summary": "Шлюз к моделям WorkAI: OpenAI-совместимый и Anthropic-совместимый протоколы.",
    "description": "Ключ `wai-…` создаётся в кабинете WorkAI API. Оплата с API-счёта в рублях; WorkCoins подписки на API не тратятся. Неизвестные поля запроса отклоняются кодом 400 `unsupported_parameter` с именем поля. Документация: https://workai.su/docs/api",
    "contact": {
      "name": "Поддержка WorkAI",
      "email": "support@workai.su"
    }
  },
  "servers": [
    {
      "url": "https://api.workai.su",
      "description": "WorkAI API"
    }
  ],
  "tags": [
    {
      "name": "OpenAI",
      "description": "Протокол OpenAI Chat Completions."
    },
    {
      "name": "Anthropic",
      "description": "Протокол Anthropic Messages, только модели Claude."
    }
  ],
  "security": [
    {
      "bearerAuth": []
    },
    {
      "apiKeyHeader": []
    }
  ],
  "paths": {
    "/v1/models": {
      "get": {
        "operationId": "listModels",
        "tags": [
          "OpenAI"
        ],
        "summary": "Список моделей",
        "description": "Модели, доступные ключу. Если у ключа задан список разрешённых моделей, возвращаются только они. Значение `id` (`<провайдер>/<модель>`) — то, что передаётся в поле `model`. С заголовком `anthropic-version` ответ в формате Anthropic: у каждой модели `type: \"model\"`, `display_name`, `created_at`, а у списка — `has_more`, `first_id`, `last_id`. Без `limit` приходит весь список.",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Сколько моделей вернуть, 1–1000.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 1000
            }
          },
          {
            "name": "after_id",
            "in": "query",
            "required": false,
            "description": "Вернуть модели после этого id.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "before_id",
            "in": "query",
            "required": false,
            "description": "Вернуть модели до этого id. Вместе с `after_id` не используется.",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Список моделей.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ModelList"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Аккаунт ограничен или запрос с IP, которого нет в списке разрешённых для ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          }
        }
      }
    },
    "/v1/key": {
      "get": {
        "operationId": "getKey",
        "tags": [
          "OpenAI"
        ],
        "summary": "Возможности ключа",
        "description": "Состояние ключа, которым сделан запрос: бюджет и расход за период, разрешённые модели, срок действия. Секрета и баланса API-счёта в ответе нет.",
        "responses": {
          "200": {
            "description": "Описание ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/KeyInfo"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Запрос с IP, которого нет в списке разрешённых для ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          }
        }
      }
    },
    "/v1/generation": {
      "get": {
        "operationId": "getGenerationByQuery",
        "tags": [
          "OpenAI"
        ],
        "summary": "Данные запроса (id в query)",
        "description": "Стоимость, токены и время запроса того же ключа по коду из заголовка ответа `X-Request-Id` (`apigw_<uuid>`). Чужой, неизвестный или устаревший код — 404. Ответ не кэшируется.",
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "required": true,
            "description": "Код запроса из `X-Request-Id`.",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Данные запроса.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerationInfo"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Запрос с IP, которого нет в списке разрешённых для ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Запись не найдена.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          }
        }
      }
    },
    "/v1/generation/{id}": {
      "get": {
        "operationId": "getGeneration",
        "tags": [
          "OpenAI"
        ],
        "summary": "Данные запроса",
        "description": "То же, что `GET /v1/generation?id=`, код запроса в пути.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Код запроса из `X-Request-Id`.",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Данные запроса.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerationInfo"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Запрос с IP, которого нет в списке разрешённых для ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Запись не найдена.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          }
        }
      }
    },
    "/v1/chat/completions": {
      "post": {
        "operationId": "createChatCompletion",
        "tags": [
          "OpenAI"
        ],
        "summary": "Чат (OpenAI Chat Completions)",
        "description": "Любая модель из `GET /v1/models`. С `stream: true` ответ — SSE: кадры `data: {…}` (`chat.completion.chunk`) и завершающий `data: [DONE]`; ошибка посреди потока — кадр `data: {\"error\": {…}}`, затем `[DONE]`. В ответе без потока `usage.cost` — сумма списания в рублях; если провайдер не прислал `usage`, он собирается по оценке и помечается `is_estimated: true`.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ChatCompletionRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Ответ модели. JSON без потока; `text/event-stream` при `stream: true`.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatCompletionResponse"
                }
              },
              "text/event-stream": {
                "schema": {
                  "type": "string",
                  "description": "Кадры SSE, завершение — `data: [DONE]`."
                }
              }
            }
          },
          "400": {
            "description": "Неверный запрос: нет `model`, битый JSON (`invalid_json`), неизвестный параметр (`unsupported_parameter`) и т. п.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "402": {
            "description": "Не хватает денег на API-счёте (`insufficient_balance`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Бюджет ключа исчерпан (`key_budget_exceeded`), счёт заморожен (`account_frozen`), модель не разрешена ключу (`model_not_allowed_for_key`), IP не разрешён (`ip_not_allowed_for_key`) или аккаунт ограничен (`account_restricted`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена (`model_not_found`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа или одновременных запросов на счёт; лимит бесплатного тарифа (`free_tier_limit`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка (`internal_error`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "503": {
            "description": "Сервис временно недоступен (`service_unavailable`) или лицензия инсталляции требует обновления (`license_degraded`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/responses": {
      "post": {
        "operationId": "createResponse",
        "tags": [
          "OpenAI"
        ],
        "summary": "Ответ модели (OpenAI Responses)",
        "description": "Для клиентов на протоколе OpenAI Responses. Любая модель из `GET /v1/models`. Шлюз ничего не хранит: `previous_response_id`, `conversation`, `store: true`, `background: true`, элементы `item_reference` и `compaction` — 400, историю присылайте в `input` целиком. Поддерживаются инструменты `function` и `custom`; встроенные инструменты OpenAI (`web_search` и т. п.) отбрасываются. С `stream: true` ответ — SSE-события `response.created`, `response.output_text.delta`, `response.completed` и другие; ошибка посреди потока — `response.failed`.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "model",
                  "input"
                ],
                "description": "Тело OpenAI Responses: `model`, `input`, `instructions`, `tools`, `tool_choice`, `stream` и др."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Объект `response`. JSON без потока; `text/event-stream` при `stream: true`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "description": "Объект `response` (`object: \"response\"`, `output`, `usage`)."
                }
              },
              "text/event-stream": {
                "schema": {
                  "type": "string",
                  "description": "События `response.*`, завершение — `response.completed`."
                }
              }
            }
          },
          "400": {
            "description": "Неверный запрос или неподдерживаемый параметр (`unsupported_parameter`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "402": {
            "description": "Не хватает денег на API-счёте (`insufficient_balance`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Бюджет ключа исчерпан, счёт заморожен, модель или IP не разрешены ключу, аккаунт ограничен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена (`model_not_found`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа или одновременных запросов на счёт; лимит бесплатного тарифа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка (`internal_error`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "503": {
            "description": "Сервис временно недоступен или лицензия инсталляции требует обновления.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/images/generations": {
      "post": {
        "operationId": "createImage",
        "tags": [
          "OpenAI"
        ],
        "summary": "Создание картинок (OpenAI Images)",
        "description": "Картинки по текстовому описанию, модели с `type: image` из `GET /v1/models`. `n` — от 1 до 10; `quality` — только `auto`; `response_format` — только `b64_json`. Списание — за фактически полученные картинки; только после пополнения счёта.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "model",
                  "prompt"
                ],
                "additionalProperties": false,
                "properties": {
                  "model": {
                    "type": "string",
                    "example": "openai/gpt-image-2"
                  },
                  "prompt": {
                    "type": "string",
                    "maxLength": 32000
                  },
                  "n": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 10,
                    "default": 1
                  },
                  "size": {
                    "type": "string",
                    "example": "1024x1024",
                    "description": "`WxH` или `auto`."
                  },
                  "quality": {
                    "type": "string",
                    "enum": [
                      "auto"
                    ]
                  },
                  "response_format": {
                    "type": "string",
                    "enum": [
                      "b64_json"
                    ]
                  },
                  "user": {
                    "type": "string",
                    "maxLength": 256
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Картинки в `data[].b64_json`; `usage.cost` — списанная сумма в рублях.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "created",
                    "data"
                  ],
                  "properties": {
                    "created": {
                      "type": "integer"
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "b64_json"
                        ],
                        "properties": {
                          "b64_json": {
                            "type": "string"
                          }
                        }
                      }
                    },
                    "usage": {
                      "type": "object",
                      "properties": {
                        "cost": {
                          "type": "number"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Запрос не по контракту (`invalid_request_error`, `unsupported_parameter`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ неверный, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "402": {
            "description": "На API-счёте не хватает денег.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Бесплатный тариф или ключ не допускает эту модель.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена (`model_not_found`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "413": {
            "description": "Слишком много картинок или файл больше 20 МБ (`request_too_large`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка (`internal_error`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/images/edits": {
      "post": {
        "operationId": "editImage",
        "tags": [
          "OpenAI"
        ],
        "summary": "Правка картинок (OpenAI Images, multipart)",
        "description": "Правка по описанию: до 16 исходных файлов в поле `image` (или `image[]`) и необязательная `mask`; PNG, WebP или JPEG, каждый файл до 20 МБ, всё тело до 32 МБ. Остальные поля и списание — как у `/v1/images/generations`.",
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "model",
                  "prompt",
                  "image"
                ],
                "properties": {
                  "model": {
                    "type": "string",
                    "example": "openai/gpt-image-2"
                  },
                  "prompt": {
                    "type": "string",
                    "maxLength": 32000
                  },
                  "image": {
                    "type": "string",
                    "format": "binary"
                  },
                  "mask": {
                    "type": "string",
                    "format": "binary"
                  },
                  "n": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 10,
                    "default": 1
                  },
                  "size": {
                    "type": "string",
                    "example": "1024x1024"
                  },
                  "quality": {
                    "type": "string",
                    "enum": [
                      "auto"
                    ]
                  },
                  "response_format": {
                    "type": "string",
                    "enum": [
                      "b64_json"
                    ]
                  },
                  "user": {
                    "type": "string",
                    "maxLength": 256
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Картинки в `data[].b64_json`; `usage.cost` — списанная сумма в рублях.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "created",
                    "data"
                  ],
                  "properties": {
                    "created": {
                      "type": "integer"
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "b64_json"
                        ],
                        "properties": {
                          "b64_json": {
                            "type": "string"
                          }
                        }
                      }
                    },
                    "usage": {
                      "type": "object",
                      "properties": {
                        "cost": {
                          "type": "number"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Запрос не по контракту (`invalid_request_error`, `unsupported_parameter`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ неверный, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "402": {
            "description": "На API-счёте не хватает денег.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Бесплатный тариф или ключ не допускает эту модель.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена (`model_not_found`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "413": {
            "description": "Слишком много картинок или файл больше 20 МБ (`request_too_large`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка (`internal_error`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/embeddings": {
      "post": {
        "operationId": "createEmbedding",
        "tags": [
          "OpenAI"
        ],
        "summary": "Эмбеддинги (OpenAI Embeddings)",
        "description": "Векторы для поиска и RAG, модель `openai/text-embedding-3-small`. Модель есть в `GET /v1/models` с `type: \"embedding\"`. `input` — строка или массив строк (до 2048, без пустых); массивы токенов не принимаются. Списание — по `usage.prompt_tokens` провайдера, сумма в рублях — в `usage.cost`. Бесплатного тарифа у эмбеддингов нет.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "model",
                  "input"
                ],
                "additionalProperties": false,
                "properties": {
                  "model": {
                    "type": "string",
                    "example": "openai/text-embedding-3-small"
                  },
                  "input": {
                    "oneOf": [
                      {
                        "type": "string",
                        "minLength": 1
                      },
                      {
                        "type": "array",
                        "minItems": 1,
                        "maxItems": 2048,
                        "items": {
                          "type": "string",
                          "minLength": 1
                        }
                      }
                    ]
                  },
                  "encoding_format": {
                    "type": "string",
                    "enum": [
                      "float",
                      "base64"
                    ],
                    "default": "float"
                  },
                  "dimensions": {
                    "type": "integer",
                    "minimum": 1
                  },
                  "user": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Векторы в порядке `input`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "object",
                    "data",
                    "model",
                    "usage"
                  ],
                  "properties": {
                    "object": {
                      "type": "string",
                      "enum": [
                        "list"
                      ]
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "object",
                          "index",
                          "embedding"
                        ],
                        "properties": {
                          "object": {
                            "type": "string",
                            "enum": [
                              "embedding"
                            ]
                          },
                          "index": {
                            "type": "integer",
                            "minimum": 0
                          },
                          "embedding": {
                            "oneOf": [
                              {
                                "type": "array",
                                "items": {
                                  "type": "number"
                                }
                              },
                              {
                                "type": "string",
                                "description": "base64 при `encoding_format: base64`."
                              }
                            ]
                          }
                        }
                      }
                    },
                    "model": {
                      "type": "string"
                    },
                    "usage": {
                      "type": "object",
                      "properties": {
                        "prompt_tokens": {
                          "type": "integer",
                          "minimum": 0
                        },
                        "total_tokens": {
                          "type": "integer",
                          "minimum": 0
                        },
                        "cost": {
                          "type": "number",
                          "description": "Списано с API-счёта, ₽."
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Неверный запрос: нет `model` или `input`, неизвестный параметр (`unsupported_parameter`), массив токенов (`unsupported_input_type`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "402": {
            "description": "Не хватает денег на API-счёте (`insufficient_balance`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Бюджет ключа исчерпан, счёт заморожен, модель или IP не разрешены ключу, аккаунт ограничен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена (`model_not_found`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа или одновременных запросов на счёт.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка (`internal_error`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "503": {
            "description": "Сервис временно недоступен (`service_unavailable`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/rerank": {
      "post": {
        "operationId": "createRerank",
        "tags": [
          "OpenAI"
        ],
        "summary": "Ранжирование документов (Cohere Rerank)",
        "description": "Сортирует `documents` по релевантности `query`; формат Cohere Rerank, ключ и API-счёт те же, что у чата. Модели — с `type: \"reranking\"` в `GET /v1/models`. `documents` — только массив непустых строк (до 1000, каждая до 128 КиБ), `query` до 32 КиБ. Списание — по входным токенам вендора, бесплатного тарифа нет. Есть и `POST /v2/rerank` (Cohere v2): без `return_documents`. Ошибки — в общем формате шлюза, не Cohere.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "model",
                  "query",
                  "documents"
                ],
                "properties": {
                  "model": {
                    "type": "string",
                    "description": "id модели с `type: \"reranking\"` из `GET /v1/models`."
                  },
                  "query": {
                    "type": "string",
                    "minLength": 1
                  },
                  "documents": {
                    "type": "array",
                    "minItems": 1,
                    "maxItems": 1000,
                    "items": {
                      "type": "string",
                      "minLength": 1
                    }
                  },
                  "top_n": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "Сколько лучших вернуть; больше числа документов — вернутся все."
                  },
                  "max_tokens_per_doc": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 32768
                  },
                  "return_documents": {
                    "type": "boolean",
                    "default": false,
                    "description": "Только `/v1/rerank`: вернуть тексты документов в ответе."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Документы по убыванию релевантности.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "id",
                    "results",
                    "meta"
                  ],
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "results": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "required": [
                          "index",
                          "relevance_score"
                        ],
                        "properties": {
                          "index": {
                            "type": "integer",
                            "minimum": 0,
                            "description": "Номер документа в `documents`."
                          },
                          "relevance_score": {
                            "type": "number"
                          },
                          "document": {
                            "type": "object",
                            "properties": {
                              "text": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      }
                    },
                    "meta": {
                      "type": "object",
                      "properties": {
                        "api_version": {
                          "type": "object",
                          "properties": {
                            "version": {
                              "type": "string"
                            }
                          }
                        },
                        "billed_units": {
                          "type": "object",
                          "properties": {
                            "input_tokens": {
                              "type": "integer",
                              "minimum": 0
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Неверный запрос: нет `model`, `query` или `documents`, неизвестное поле (`unsupported_parameter`), не строки в `documents` (`unsupported_input_type`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "402": {
            "description": "Не хватает денег на API-счёте (`insufficient_balance`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "403": {
            "description": "Бюджет ключа исчерпан, счёт заморожен, модель или IP не разрешены ключу, аккаунт ограничен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена (`model_not_found`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "413": {
            "description": "Запрос слишком большой (`request_too_large`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов с ключа или одновременных запросов на счёт.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка (`internal_error`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          },
          "503": {
            "description": "Сервис временно недоступен (`service_unavailable`).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpenAiError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages": {
      "post": {
        "operationId": "createMessage",
        "tags": [
          "Anthropic"
        ],
        "summary": "Сообщения (Anthropic Messages)",
        "description": "Только модели Claude: для других моделей — 400 `model_not_supported_on_endpoint`, используйте `/v1/chat/completions`. Модель — id из `GET /v1/models` (`anthropic/claude-…`) либо собственный id Claude (id каталога или id у Anthropic). Тело ответа и поток SSE передаются в формате Anthropic как есть. Заголовки `anthropic-version` (дата `YYYY-MM-DD`) и `anthropic-beta` (имена возможностей через запятую) проверяются по форме и передаются провайдеру.",
        "parameters": [
          {
            "$ref": "#/components/parameters/AnthropicVersion"
          },
          {
            "$ref": "#/components/parameters/AnthropicBeta"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnthropicMessagesRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Ответ модели в формате Anthropic Messages. JSON без потока; `text/event-stream` при `stream: true`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true
                }
              },
              "text/event-stream": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "description": "Неверный запрос.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "402": {
            "description": "Не хватает денег на API-счёте.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "403": {
            "description": "Бюджет ключа, заморожен счёт, модель или IP не разрешены, аккаунт ограничен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "503": {
            "description": "Сервис временно недоступен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "529": {
            "description": "Провайдер модели перегружен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages/count_tokens": {
      "post": {
        "operationId": "countMessageTokens",
        "tags": [
          "Anthropic"
        ],
        "summary": "Подсчёт входных токенов (Anthropic)",
        "description": "Точный подсчёт входа у провайдера; бесплатно, без резерва на счёте. Лимит частоты на ключ строже, чем у остальных маршрутов. Принимает `model`, `messages`, `system`, `thinking`, `tools`, `tool_choice`, `context_management`, `output_config`; `max_tokens` не нужен.",
        "parameters": [
          {
            "$ref": "#/components/parameters/AnthropicVersion"
          },
          {
            "$ref": "#/components/parameters/AnthropicBeta"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnthropicCountTokensRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Число входных токенов.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "input_tokens"
                  ],
                  "properties": {
                    "input_tokens": {
                      "type": "integer",
                      "minimum": 0
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Неверный запрос.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "401": {
            "description": "Ключ не передан, неверного формата, не найден, отозван или истёк.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "403": {
            "description": "Модель или IP не разрешены ключу, аккаунт ограничен.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "404": {
            "description": "Модель не найдена.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          },
          "429": {
            "description": "Слишком много запросов.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            },
            "headers": {
              "Retry-After": {
                "description": "Секунд до повтора (целое число, не меньше 1).",
                "schema": {
                  "type": "integer",
                  "minimum": 1
                }
              }
            }
          },
          "500": {
            "description": "Внутренняя ошибка.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnthropicError"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "wai-…",
        "description": "Ключ WorkAI API: `Authorization: Bearer wai-…`. Проверяется раньше `x-api-key`."
      },
      "apiKeyHeader": {
        "type": "apiKey",
        "in": "header",
        "name": "x-api-key",
        "description": "Тот же ключ `wai-…` в заголовке `x-api-key` (так шлёт Anthropic SDK). Работает на всех маршрутах."
      }
    },
    "parameters": {
      "AnthropicVersion": {
        "name": "anthropic-version",
        "in": "header",
        "required": false,
        "description": "Дата вида 2023-06-01; иначе 400.",
        "schema": {
          "type": "string",
          "pattern": "^\\d{4}-\\d{2}-\\d{2}$"
        }
      },
      "AnthropicBeta": {
        "name": "anthropic-beta",
        "in": "header",
        "required": false,
        "description": "Имена возможностей через запятую, не длиннее 4096 символов; неизвестные шлюзу отклоняются.",
        "schema": {
          "type": "string",
          "maxLength": 4096
        }
      }
    },
    "schemas": {
      "OpenAiError": {
        "type": "object",
        "description": "Ошибка в форме OpenAI. Все четыре поля присутствуют (`param`, `code` могут быть null). Примеры `code`: invalid_api_key, account_restricted, rate_limit_exceeded, insufficient_balance, key_budget_exceeded, account_frozen, model_not_found, model_not_allowed_for_key, ip_not_allowed_for_key, unsupported_parameter, invalid_json, too_many_messages, too_many_images, model_not_supported_on_endpoint, service_unavailable, license_degraded, internal_error; полный список не фиксирован.",
        "required": [
          "error"
        ],
        "properties": {
          "error": {
            "type": "object",
            "required": [
              "message",
              "type",
              "param",
              "code"
            ],
            "properties": {
              "message": {
                "type": "string"
              },
              "type": {
                "type": "string",
                "enum": [
                  "invalid_request_error",
                  "not_found_error",
                  "authentication_error",
                  "rate_limit_error",
                  "api_error",
                  "upstream_error",
                  "insufficient_quota",
                  "permission_error"
                ]
              },
              "param": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Имя поля запроса, из-за которого отказ."
              },
              "code": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "metadata": {
                "type": "object",
                "description": "Необязательное. Причина отказа провайдера, когда она известна.",
                "required": [
                  "provider_code"
                ],
                "properties": {
                  "provider_code": {
                    "type": "string"
                  }
                }
              }
            },
            "additionalProperties": true
          }
        }
      },
      "AnthropicError": {
        "type": "object",
        "description": "Ошибка в форме Anthropic. `error.code` — расширение WorkAI (`free_tier_*`, `license_degraded`).",
        "required": [
          "type",
          "error"
        ],
        "properties": {
          "type": {
            "type": "string",
            "const": "error"
          },
          "error": {
            "type": "object",
            "required": [
              "type",
              "message"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "invalid_request_error",
                  "authentication_error",
                  "billing_error",
                  "permission_error",
                  "not_found_error",
                  "request_too_large",
                  "rate_limit_error",
                  "api_error",
                  "timeout_error",
                  "overloaded_error"
                ]
              },
              "message": {
                "type": "string"
              },
              "code": {
                "type": "string"
              }
            },
            "additionalProperties": true
          },
          "request_id": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "KeyInfo": {
        "type": "object",
        "required": [
          "id",
          "name",
          "prefix",
          "status",
          "budget",
          "allowedModels",
          "expiresAt"
        ],
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "prefix": {
            "type": "string",
            "description": "Видимая часть ключа `wai-…`, не секрет."
          },
          "status": {
            "type": "string",
            "const": "active"
          },
          "budget": {
            "type": "object",
            "required": [
              "monthlyRub",
              "spentRub",
              "resetsAt"
            ],
            "properties": {
              "monthlyRub": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Месячный лимит ключа в рублях строкой; null - без лимита."
              },
              "spentRub": {
                "type": "string",
                "description": "Списано по ключу в текущем периоде, рубли строкой."
              },
              "resetsAt": {
                "type": "string",
                "format": "date-time",
                "description": "Начало следующего периода бюджета."
              },
              "remainingRub": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Остаток лимита в рублях строкой с учётом резервов под выполняющиеся запросы; null - без лимита."
              },
              "period": {
                "type": "string",
                "const": "monthly",
                "description": "Период лимита: календарный месяц."
              },
              "resetDay": {
                "type": "integer",
                "description": "День месяца, в который лимит обнуляется (по Москве)."
              }
            }
          },
          "allowedModels": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "Идентификаторы моделей, доступных ключу; null - без ограничений."
          },
          "expiresAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          }
        }
      },
      "GenerationInfo": {
        "type": "object",
        "required": [
          "data"
        ],
        "properties": {
          "data": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "description": "Код запроса `apigw_<uuid>`."
              },
              "created_at": {
                "type": "string",
                "format": "date-time"
              },
              "endpoint": {
                "type": "string"
              },
              "model": {
                "type": "string"
              },
              "streamed": {
                "type": "boolean"
              },
              "is_byok": {
                "type": "boolean",
                "const": false
              },
              "currency": {
                "type": "string",
                "const": "RUB"
              },
              "total_cost": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Списано, рубли строкой; null - не тарифицировалось."
              },
              "usage": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "То же, что `total_cost`."
              },
              "free": {
                "type": "boolean"
              },
              "unit_kind": {
                "type": "string",
                "description": "`token` или другая единица учёта."
              },
              "unit_qty": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Количество не токенной единицы."
              },
              "tokens_prompt": {
                "type": "integer"
              },
              "tokens_completion": {
                "type": "integer"
              },
              "native_tokens_cached": {
                "type": "integer"
              },
              "native_tokens_cache_creation": {
                "type": "integer"
              },
              "generation_time": {
                "type": "integer",
                "description": "Полное время запроса, мс."
              },
              "http_status": {
                "type": "integer"
              },
              "error_code": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          }
        }
      },
      "ModelList": {
        "type": "object",
        "required": [
          "object",
          "data"
        ],
        "properties": {
          "object": {
            "type": "string",
            "const": "list"
          },
          "has_more": {
            "type": "boolean",
            "description": "Только в формате Anthropic: есть ли модели дальше."
          },
          "first_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Только в формате Anthropic."
          },
          "last_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Только в формате Anthropic."
          },
          "data": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "id",
                "object",
                "created",
                "owned_by"
              ],
              "properties": {
                "type": {
                  "type": "string",
                  "const": "model",
                  "description": "Только в формате Anthropic."
                },
                "display_name": {
                  "type": "string",
                  "description": "Только в формате Anthropic."
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time",
                  "description": "Только в формате Anthropic."
                },
                "id": {
                  "type": "string",
                  "description": "`<провайдер>/<модель>`, например `anthropic/claude-sonnet-5-5`."
                },
                "object": {
                  "type": "string",
                  "const": "model"
                },
                "created": {
                  "type": "integer",
                  "description": "Дата релиза модели, секунды Unix; 0, если даты нет."
                },
                "owned_by": {
                  "type": "string",
                  "description": "Провайдер модели."
                },
                "free": {
                  "type": "boolean",
                  "const": true,
                  "description": "Есть, только если модель бесплатна для вашего тарифа."
                }
              }
            }
          }
        }
      },
      "ChatMessage": {
        "type": "object",
        "required": [
          "role"
        ],
        "description": "Реплика. Поля сверх перечисленных для роли отклоняются (400 `unsupported_parameter`).",
        "properties": {
          "role": {
            "type": "string",
            "enum": [
              "system",
              "developer",
              "user",
              "assistant",
              "tool"
            ]
          },
          "content": {
            "description": "Строка или массив частей: `text`, `image_url` (user, tool), `refusal` (assistant).",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "type"
                  ],
                  "properties": {
                    "type": {
                      "type": "string",
                      "enum": [
                        "text",
                        "image_url",
                        "refusal"
                      ]
                    }
                  },
                  "additionalProperties": true
                }
              },
              {
                "type": "null"
              }
            ]
          },
          "name": {
            "type": "string"
          },
          "tool_calls": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "tool_call_id": {
            "type": "string",
            "description": "Обязателен для role=tool."
          }
        },
        "additionalProperties": true
      },
      "ChatCompletionRequest": {
        "type": "object",
        "required": [
          "model",
          "messages"
        ],
        "description": "Принимаются только перечисленные поля. Неизвестное поле — 400 `unsupported_parameter`; `n` — только 1; `modalities` — только [\"text\"]; `store: true` и `prediction` отклоняются. `user`, `store: false`, `metadata`, `safety_identifier`, `prompt_cache_key` принимаются и игнорируются.",
        "properties": {
          "model": {
            "type": "string",
            "description": "id из `GET /v1/models`. Режим рассуждения задаётся суффиксом `<id>:<режим>` (Claude, Gemini, DeepSeek, xAI); список режимов модели — `reasoning.modes` в публичном прайсе `GET https://workai.su/api/v1/pricing/api-prices` (у DeepSeek это `none`, `high`, `max`). Режим вне списка — 400 `reasoning_effort_not_supported` до резерва; у OpenAI режим — отдельная модель каталога, неизвестный суффикс — 404. Цена режима равна цене базовой модели."
          },
          "reasoning_effort": {
            "type": "string",
            "description": "Режим рассуждения телом. Вместе с суффиксом допустим только тот же режим, иначе 400 `reasoning_effort_conflict`. У OpenAI и xAI значение вне списка модели — 400; у Claude, Gemini и DeepSeek поле вне списка отбрасывается и провайдеру не уходит."
          },
          "messages": {
            "type": "array",
            "minItems": 1,
            "items": {
              "$ref": "#/components/schemas/ChatMessage"
            }
          },
          "tools": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            },
            "description": "Только `type: function`."
          },
          "tool_choice": {
            "description": "`none`, `auto`, `required` или `{type:\"function\", function:{name}}`."
          },
          "parallel_tool_calls": {
            "type": "boolean"
          },
          "stream": {
            "type": "boolean",
            "default": false
          },
          "stream_options": {
            "type": "object",
            "description": "Только вместе с `stream: true`.",
            "properties": {
              "include_usage": {
                "type": "boolean"
              },
              "include_obfuscation": {
                "type": "boolean"
              }
            },
            "additionalProperties": false
          },
          "max_tokens": {
            "type": "integer",
            "minimum": 1
          },
          "max_completion_tokens": {
            "type": "integer",
            "minimum": 1,
            "description": "Если заданы оба, значения должны совпадать. Размер лимита влияет на резерв на счёте."
          },
          "temperature": {
            "type": "number",
            "minimum": 0,
            "maximum": 2
          },
          "top_p": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          },
          "stop": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            ]
          },
          "n": {
            "type": "integer",
            "const": 1
          },
          "frequency_penalty": {
            "type": "number"
          },
          "presence_penalty": {
            "type": "number"
          },
          "seed": {
            "type": "integer"
          },
          "logit_bias": {
            "type": "object",
            "additionalProperties": {
              "type": "number"
            }
          },
          "logprobs": {
            "type": "boolean"
          },
          "top_logprobs": {
            "type": "integer"
          },
          "response_format": {
            "type": "object",
            "additionalProperties": true
          },
          "verbosity": {
            "type": "string"
          },
          "service_tier": {
            "type": "string"
          },
          "modalities": {
            "type": "array",
            "items": {
              "type": "string",
              "const": "text"
            },
            "maxItems": 1
          },
          "user": {
            "type": "string"
          },
          "store": {
            "type": "boolean",
            "const": false,
            "description": "`true` отклоняется (400): хранение ответов не поддерживается."
          },
          "metadata": {
            "type": "object",
            "additionalProperties": true
          },
          "safety_identifier": {
            "type": "string"
          },
          "prompt_cache_key": {
            "type": "string"
          },
          "models": {
            "type": "array",
            "maxItems": 3,
            "items": {
              "type": "string"
            },
            "description": "Запасные модели: пробуются по порядку, если `model` не ответила. Без дублей и без повтора `model`."
          },
          "caching": {
            "type": "string",
            "const": "auto",
            "description": "Автоматические точки кэша (как `caching: \"auto\"` у Vercel AI Gateway). У Claude шлюз сам ставит `cache_control` на два места — последнее сообщение и сообщение перед последним `user` (запасной вариант — `system`); OpenAI, Google и DeepSeek кэшируют сами, и запрос к ним не меняется. Своя разметка `cache_control` в запросе отключает автоматическую: ручная точнее, а у Claude число точек кэша ограничено. Любое другое значение — 400 `invalid_caching`. Можно передать и как `providerOptions.gateway.caching`."
          },
          "providerOptions": {
            "type": "object",
            "additionalProperties": true,
            "description": "Запасные модели в `gateway.models` (если задано и `models`, списки должны совпасть), `gateway.caching` и метки журнала запросов. Провайдеру не передаётся."
          }
        },
        "additionalProperties": true
      },
      "ChatCompletionResponse": {
        "type": "object",
        "description": "Ответ `chat.completion` (формат OpenAI) с расширением `usage.cost`.",
        "required": [
          "choices"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "object": {
            "type": "string"
          },
          "model": {
            "type": "string"
          },
          "choices": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "usage": {
            "type": "object",
            "properties": {
              "prompt_tokens": {
                "type": "integer"
              },
              "completion_tokens": {
                "type": "integer"
              },
              "total_tokens": {
                "type": "integer"
              },
              "cost": {
                "type": "number",
                "description": "Списано с API-счёта, ₽. Поля нет, если списания нет."
              },
              "is_estimated": {
                "type": "boolean",
                "const": true,
                "description": "Токены оценены шлюзом: провайдер `usage` не прислал."
              }
            },
            "additionalProperties": true
          }
        },
        "additionalProperties": true
      },
      "AnthropicMessagesRequest": {
        "type": "object",
        "required": [
          "model",
          "max_tokens",
          "messages"
        ],
        "description": "Поля `messages`, `system`, `stop_sequences`, `temperature`, `top_k`, `top_p`, `thinking`, `tools`, `tool_choice`, `cache_control`, `output_config`, `context_management`, `diagnostics` уходят провайдеру после проверки. `speed` — только \"standard\"; `service_tier` всегда исполняется как standard_only; `metadata` провайдеру не передаётся. Отклоняются: `container`, `mcp_servers`, `inference_geo`, `fallbacks`, `compaction`, `fallback_credit_token`.",
        "properties": {
          "model": {
            "type": "string",
            "description": "id модели Claude, с префиксом `anthropic/` или без. Суффикс `:<режим>` задаёт `output_config.effort`; расходящийся `output_config.effort` в теле — 400 `reasoning_effort_conflict`, effort вне списка модели без суффикса отбрасывается."
          },
          "max_tokens": {
            "type": "integer",
            "minimum": 1
          },
          "stream": {
            "type": "boolean"
          },
          "messages": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "system": {},
          "stop_sequences": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "temperature": {
            "type": "number"
          },
          "top_k": {
            "type": "integer"
          },
          "top_p": {
            "type": "number"
          },
          "thinking": {
            "type": "object",
            "additionalProperties": true
          },
          "models": {
            "type": "array",
            "maxItems": 3,
            "items": {
              "type": "string"
            },
            "description": "Запасные модели: пробуются по порядку, если `model` не ответила. Без дублей и без повтора `model`."
          },
          "caching": {
            "type": "string",
            "const": "auto",
            "description": "Автоматические точки кэша (как `caching: \"auto\"` у Vercel AI Gateway). У Claude шлюз сам ставит `cache_control` на два места — последнее сообщение и сообщение перед последним `user` (запасной вариант — `system`); OpenAI, Google и DeepSeek кэшируют сами, и запрос к ним не меняется. Своя разметка `cache_control` в запросе отключает автоматическую: ручная точнее, а у Claude число точек кэша ограничено. Любое другое значение — 400 `invalid_caching`. Можно передать и как `providerOptions.gateway.caching`."
          },
          "providerOptions": {
            "type": "object",
            "additionalProperties": true,
            "description": "Запасные модели в `gateway.models` (если задано и `models`, списки должны совпасть), `gateway.caching` и метки журнала запросов. Провайдеру не передаётся."
          },
          "tools": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "tool_choice": {
            "type": "object",
            "additionalProperties": true
          },
          "cache_control": {
            "type": "object",
            "additionalProperties": true
          },
          "output_config": {
            "type": "object",
            "additionalProperties": true
          },
          "context_management": {
            "type": "object",
            "additionalProperties": true
          },
          "diagnostics": {
            "type": "object",
            "additionalProperties": true
          },
          "metadata": {
            "type": "object",
            "additionalProperties": true
          },
          "service_tier": {
            "type": "string",
            "enum": [
              "auto",
              "standard_only"
            ]
          },
          "speed": {
            "type": "string",
            "const": "standard"
          }
        },
        "additionalProperties": true
      },
      "AnthropicCountTokensRequest": {
        "type": "object",
        "required": [
          "model",
          "messages"
        ],
        "properties": {
          "model": {
            "type": "string"
          },
          "messages": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "system": {},
          "thinking": {
            "type": "object",
            "additionalProperties": true
          },
          "tools": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "tool_choice": {
            "type": "object",
            "additionalProperties": true
          },
          "context_management": {
            "type": "object",
            "additionalProperties": true
          },
          "output_config": {
            "type": "object",
            "additionalProperties": true
          }
        },
        "additionalProperties": true
      }
    }
  }
}