Разделы документации

Документация / API

Чат и текст

Ответы моделей в формате OpenRouter: сообщения, стриминг, инструменты, веб-поиск, разбор PDF.

Текстовые модели →

Как шлюз обрабатывает запрос

  • До отправки модели шлюз резервирует наибольшую возможную стоимость запроса: модель или набор models, вложения, плагины и веб-поиск. Если её нельзя ограничить заранее, запрос отклоняется с кодом 400 и ничего не списывается.
  • Шлюз дописывает в тело учёт расхода, предел вывода (если вы его не задали), provider.max_price и, при веб-поиске, пределы поиска. Остальное тело доходит до модели без изменений.
  • При stream: true последний чанк с usage приходит, только если вы его попросили (stream_options.include_usage или usage.include), и уже после подтверждённого списания — перед data: [DONE].
  • Звук на выходе — через modalities у моделей, которые его поддерживают; картинки на выходе в чате не поддерживаются — для них есть изображения.
  • Полный список отказов — на странице Изменения API.
POST/v1/chat/completions

Create a chat completion

OpenRouter chat completion. The gateway adds usage accounting, an output limit when none is set, provider.max_price and, for server tools, a step limit; everything else in the body reaches the model unchanged. Requests whose cost cannot be bounded in advance are refused with 400 before any charge (see the API changes page). With stream: true the response is a server-sent event stream; the final chunk with usage arrives only when stream_options.include_usage or usage.include is set, after the charge is confirmed.

Ключ: заголовок Authorization: Bearer <ключ>. Как получить ключ →

Тело запроса

application/json

  • max_completion_tokensinteger

    Не меньше 1.

  • max_tokensinteger

    Не меньше 1.

  • messagesarray of objectобязательное
    • contentstring | array of object

      Text or a list of parts.

      • fileobject
        • file_datastring

          base64 data URL; files by URL and file_id are refused.

        • filenamestring
      • image_urlobject
        • detailstring
        • urlstring
      • textstring
      • typestringобязательное

        Значения: text, image_url, file

    • namestring
    • rolestringобязательное

      Значения: system, developer, user, assistant, tool

    • tool_call_idstring
  • modelstringобязательное

    Model id from the catalog, or openrouter/auto with the auto-router plugin and allowed_models.

  • modelsarray of string

    Fallback models; each must be in the catalog.

  • pluginsarray of object

    auto-router, file-parser (cloudflare-ai, mistral-ocr), context-compression, moderation, response-healing.

  • providerobject

    Provider preferences; max_price is capped by the gateway.

  • response_formatobject
  • seedinteger
  • stopstring | array of string

    Stop sequence or sequences.

  • streamboolean
  • stream_optionsobject
    • include_usageboolean
  • temperaturenumber
  • tool_choicestring | object

    none, auto, required, or an object naming a declared tool.

  • toolsarray of object

    Functions, and one web search tool (openrouter:web_search) with engine exa, parallel or perplexity.

  • top_pnumber
  • usageobject
    • includeboolean
  • Остальные поля формата OpenRouter передаются модели без изменений.

Пример запроса

{
  "messages": [
    {
      "content": "Say hello in one word.",
      "role": "user"
    }
  ],
  "model": "openai/gpt-4o-mini"
}

Ответ 200

Completion. With stream: true — text/event-stream of ChatChunk objects ending with data: [DONE].

  • choicesarray of objectобязательное
  • createdinteger
  • idstringобязательное
  • modelstring

    The model that served the request.

  • objectstring
  • usageobject
    • completion_tokensinteger
    • costnumber | null

      Amount actually charged, in roubles with five decimals (thousandths of a kopeck). null while the provider cost is being fetched (pending) or the charge is under review.

    • cost_statusstring

      final — charged by the provider's actual cost; estimated — by our price table; pending — the cost is being fetched, the charge follows; review — an operator decides.

      Значения: final, estimated, pending, review

    • prompt_tokensinteger
    • total_tokensinteger
  • Остальные поля формата OpenRouter передаются модели без изменений.

Пример ответа

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Hello!",
        "role": "assistant"
      }
    }
  ],
  "created": 1760270000,
  "id": "gen-1760270000-abc",
  "model": "openai/gpt-4o-mini",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 2,
    "cost": 0.03124,
    "cost_status": "final",
    "prompt_tokens": 12,
    "total_tokens": 14
  }
}

Ошибки

  • 400The request is invalid or its cost cannot be bounded in advance. Nothing is charged.
  • 401Missing or invalid API key.
  • 402The balance does not cover the reserve of this request.
  • 403The input was flagged by moderation; metadata.reasons lists why.
  • 404The model provider rejected the request (its status is kept: 400, 404, 413 or 422); metadata.provider_message, when present, is the provider's explanation.
  • 413The model provider rejected the request (its status is kept: 400, 404, 413 or 422); metadata.provider_message, when present, is the provider's explanation.
  • 422The model provider rejected the request (its status is kept: 400, 404, 413 or 422); metadata.provider_message, when present, is the provider's explanation.
  • 429Too many requests, or the model provider is busy. Retry-After, when present, says when to retry.
  • 502The model provider failed or returned an error.
  • 503Billing or the model provider is temporarily unavailable.

Формат тела ошибки и что делать — Лимиты и ошибки.