Документация / API
Чат и текст
Ответы моделей в формате OpenRouter: сообщения, стриминг, инструменты, веб-поиск, разбор PDF.
Как шлюз обрабатывает запрос
- До отправки модели шлюз резервирует наибольшую возможную стоимость запроса: модель или набор
models, вложения, плагины и веб-поиск. Если её нельзя ограничить заранее, запрос отклоняется с кодом 400 и ничего не списывается. - Шлюз дописывает в тело учёт расхода, предел вывода (если вы его не задали),
provider.max_priceи, при веб-поиске, пределы поиска. Остальное тело доходит до модели без изменений. - При
stream: trueпоследний чанк сusageприходит, только если вы его попросили (stream_options.include_usageилиusage.include), и уже после подтверждённого списания — передdata: [DONE]. - Звук на выходе — через
modalitiesу моделей, которые его поддерживают; картинки на выходе в чате не поддерживаются — для них есть изображения. - Полный список отказов — на странице Изменения API.
/v1/chat/completionsCreate 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 objectText or a list of parts.
fileobjectfile_datastringbase64 data URL; files by URL and file_id are refused.
filenamestring
image_urlobjectdetailstringurlstring
textstringtypestringобязательноеЗначения:
text,image_url,file
namestringrolestringобязательноеЗначения:
system,developer,user,assistant,tooltool_call_idstring
modelstringобязательноеModel id from the catalog, or openrouter/auto with the auto-router plugin and allowed_models.
modelsarray of stringFallback models; each must be in the catalog.
pluginsarray of objectauto-router, file-parser (cloudflare-ai, mistral-ocr), context-compression, moderation, response-healing.
providerobjectProvider preferences; max_price is capped by the gateway.
response_formatobjectseedintegerstopstring | array of stringStop sequence or sequences.
streambooleanstream_optionsobjectinclude_usageboolean
temperaturenumbertool_choicestring | objectnone, auto, required, or an object naming a declared tool.
toolsarray of objectFunctions, and one web search tool (openrouter:web_search) with engine exa, parallel or perplexity.
top_pnumberusageobjectincludeboolean
- Остальные поля формата 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обязательноеcreatedintegeridstringобязательноеmodelstringThe model that served the request.
objectstringusageobjectcompletion_tokensintegercostnumber | nullAmount 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_statusstringfinal — 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,reviewprompt_tokensintegertotal_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.
Формат тела ошибки и что делать — Лимиты и ошибки.