Documentation Index

Получите полный индекс документации по адресу: https://api.vega.chat/docs/llms.txt
Используйте этот файл, чтобы узнать о всех доступных страницах перед дальнейшим изучением.

api guides

API Reference

MD версия

Обзор API API ВЕГА

Схемы запросов и ответов API ВЕГА очень похожи на API OpenAI, с небольшими отличиями. На высоком уровне API ВЕГА нормализует схему между моделями и провайдерами, поэтому вам нужно изучить только одну.

API ВЕГА поддерживает два формата запросов: Responses API (POST /api/v1/responses) и Chat Completions API (POST /api/v1/chat/completions). На этой странице сначала показан Responses API. Ниже приведены схемы TypeScript для Chat Completions; схема Responses API находится в Responses API reference.

OpenAPI specification

Полный API API ВЕГА задокументирован с помощью спецификации OpenAPI. Вы можете получить спецификацию в формате YAML или JSON:

Эти спецификации можно использовать с инструментами, такими как Swagger UI, Postman, или любым генератором кода, совместимым с OpenAPI, для исследования API или генерации клиентских библиотек.

Requests

Responses API request format

Запрос Responses API принимает input (строку или массив элементов ввода), необязательные instructions и те же поля маршрутизации, что и у Chat Completions (models, provider, plugins, user). Полная схема запроса находится в Responses API reference и в OpenAPI specification.

json
{ "model": "openai/gpt-5.2", "instructions": "Answer in one sentence.", "input": "What is the meaning of life?", "max_output_tokens": 256 }

Completions request format

Ниже представлена схема запроса Chat Completions в виде TypeScript‑типа. Это будет тело вашего POST‑запроса к эндпоинту /api/v1/chat/completions. Формат запроса Responses API описан выше.

Для полного списка параметров см. Parameters.

typescript
// Definitions of subtypes are below type Request = { // Either "messages" or "prompt" is required messages?: Message[]; prompt?: string; // If "model" is unspecified, uses the user's default model?: string; // See "Supported Models" section // Allows to force the model to produce specific output format. // See "Structured Outputs" section below and models page for which models support it. response_format?: ResponseFormat; stop?: string | string[]; stream?: boolean; // Enable streaming // Plugins to extend model capabilities (PDF parsing, response healing) // See "Plugins" section: openrouter.ai/docs/api-guides/overview plugins?: Plugin[]; // See LLM Parameters (openrouter.ai/docs/api-guides/parameters) max_tokens?: number; // Range: [1, context_length) temperature?: number; // Range: [0, 2] // Tool calling // Will be passed down as-is for providers implementing OpenAI's interface. // For providers with custom interfaces, we transform and map the properties. // Otherwise, we transform the tools into a YAML template. The model responds with an assistant message. // See models supporting tool calling: openrouter.ai/models?supported_parameters=tools tools?: Tool[]; tool_choice?: ToolChoice; // Advanced optional parameters seed?: number; // Integer only top_p?: number; // Range: (0, 1] top_k?: number; // Range: [1, Infinity) Not available for OpenAI models frequency_penalty?: number; // Range: [-2, 2] presence_penalty?: number; // Range: [-2, 2] repetition_penalty?: number; // Range: (0, 2] logit_bias?: { [key: number]: number }; top_logprobs: number; // Integer only min_p?: number; // Range: [0, 1] top_a?: number; // Range: [0, 1] // Reduce latency by providing the model with a predicted output // https://platform.openai.com/docs/api-guides/overview#use-predicted-outputs prediction?: { type: 'content'; content: string }; // OpenRouter-only parameters // See "Model Routing" section: openrouter.ai/docs/api-guides/overview models?: string[]; route?: 'fallback'; // See "Provider Routing" section: openrouter.ai/docs/api-guides/overview provider?: ProviderPreferences; user?: string; // A stable identifier for your end-users. Used to help detect and prevent abuse. // Debug options (streaming only) debug?: { echo_upstream_body?: boolean; // If true, returns the transformed request body sent to the provider }; }; // Subtypes: type TextContent = { type: 'text'; text: string; }; type ImageContentPart = { type: 'image_url'; image_url: { url: string; // URL or base64 encoded image data detail?: string; // Optional, defaults to "auto" }; }; type ContentPart = TextContent | ImageContentPart; type Message = | { role: 'user' | 'assistant' | 'system'; // ContentParts are only for the "user" role: content: string | ContentPart[]; // If "name" is included, it will be prepended like this // for non-OpenAI models: `{name}: {content}` name?: string; } | { role: 'tool'; content: string; tool_call_id: string; name?: string; }; type FunctionDescription = { description?: string; name: string; parameters: object; // JSON Schema object }; type Tool = { type: 'function'; function: FunctionDescription; }; type ToolChoice = | 'none' | 'auto' | { type: 'function'; function: { name: string; }; }; // Response format for structured outputs type ResponseFormat = | { type: 'json_object' } | { type: 'json_schema'; json_schema: { name: string; strict?: boolean; schema: object; // JSON Schema object }; }; // Plugin configuration type Plugin = { id: string; // 'web', 'file-parser', 'response-healing', 'context-compression' enabled?: boolean; // Additional plugin-specific options [key: string]: unknown; };

Structured outputs

Параметр response_format позволяет принудительно получать структурированные JSON‑ответы от модели. API ВЕГА поддерживает два режима:

  • { type: 'json_object' }: базовый JSON‑режим — модель вернёт корректный JSON
  • { type: 'json_schema', json_schema: { ... } }: строгий режим схемы — модель вернёт JSON, точно соответствующий вашей схеме

Подробное использование и примеры см. в Structured Outputs. Чтобы найти модели, поддерживающие структурированные выводы, проверьте models page.

Plugins

Плагины API ВЕГА расширяют возможности модели, добавляя такие функции, как веб‑поиск, обработка PDF, исправление ответов и сжатие контекста. Включите плагины, добавив массив plugins в ваш запрос:

json
{ "plugins": [ { "id": "web" }, { "id": "response-healing" } ] }

Доступные плагины: web (поиск в реальном времени), file-parser (обработка PDF), response-healing (автоматический ремонт JSON) и context-compression (сжатие подсказок «middle‑out»). Подробные параметры конфигурации см. в Plugins

Headers

API ВЕГА позволяет указать несколько необязательных заголовков для идентификации вашего приложения и его обнаружения пользователями на нашем сайте.

  • HTTP-Referer: Идентифицирует ваше приложение на api.vega.chat
  • X-OpenRouter-Title: Устанавливает/изменяет заголовок вашего приложения (X-Title также принимается)
  • X-OpenRouter-Categories: Присваивает категории маркетплейса (см. App Attribution)
typescript
fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { Authorization: 'Bearer <OPENROUTER_API_KEY>', 'HTTP-Referer': '<YOUR_SITE_URL>', // Optional. Site URL for rankings on openrouter.ai. 'X-OpenRouter-Title': '<YOUR_SITE_NAME>', // Optional. Site title for rankings on openrouter.ai. 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-5.2', input: 'What is the meaning of life?', }), });
typescript
fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer <OPENROUTER_API_KEY>', 'HTTP-Referer': '<YOUR_SITE_URL>', // Optional. Site URL for rankings on openrouter.ai. 'X-OpenRouter-Title': '<YOUR_SITE_NAME>', // Optional. Site title for rankings on openrouter.ai. 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-5.2', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }), });
python
response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer <OPENROUTER_API_KEY>', 'HTTP-Referer': '<YOUR_SITE_URL>', # Optional. Site URL for rankings on openrouter.ai. 'X-OpenRouter-Title': '<YOUR_SITE_NAME>', # Optional. Site title for rankings on openrouter.ai. 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-5.2', 'input': 'What is the meaning of life?', }, )
go
body := strings.NewReader(`{"model": "openai/gpt-5.2", "input": "What is the meaning of life?"}`) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", body) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("HTTP-Referer", "<YOUR_SITE_URL>") // Optional. Site URL for rankings on openrouter.ai. req.Header.Set("X-OpenRouter-Title", "<YOUR_SITE_NAME>") // Optional. Site title for rankings on openrouter.ai. req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req)
bash
curl -sS https://openrouter.ai/api/v1/responses \ -o response.json \ -w "Status: %{http_code}\n" \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "HTTP-Referer: <YOUR_SITE_URL>" \ -H "X-OpenRouter-Title: <YOUR_SITE_NAME>" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "input": "What is the meaning of life?" }' jq . response.json
text
Status: 200 { "id": "gen-1794947561-lErZowkClrPNycYNs17c", "object": "response", "created_at": 1794947561, "model": "openai/gpt-5.2", "status": "completed", "completed_at": 1794947570, "output": [ { "id": "rs_04c0a1456b3e4c66016afcb9f1f9f887d1be35c915ee85f388", "type": "reasoning", "status": "completed", "summary": [ { "type": "summary_text", "text": "**Crafting meaningful reflections**\n\nI'm thinking about how to approach the topic with a concise and meaningful perspective. It’s important to keep it philosophical, without getting too verbose. I want to present multiple viewpoints and highlight ideas like constructing meaning, well-being, relationships, personal growth, contribution, and curiosity. I also need to emphasize that there’s no single answer and provide actionable reflection prompts for deeper thinking. This way, I can guide the user in exploring the subject more thoughtfully." } ], "encrypted_content": "gAAAAABq_LnxW5uxuX_otngGFsSO5p_FFv06S3YJXOWsaacGZuNGVtn-N4_Z_16z_ahi4VBHLNC7MLGdRkokwsCIeWYlv-4CiTfR5Nf0ko3elo5fRw1d_u981YDpqyHsUVBW7janQNSl70Sb7YG8tpEgejH5xC9jgrbekiclP1t1lg62fA8k6M8bKOrvVfJZw1wLbw1rtWyrVRUibdI-6TBxPoaOv22RuWh3D6881zpvbJac2m89O2oYci3JLvoKChjBZHY7jffAGrbgrA_RM-3F_wjVUN1z84eFn3gP1-yX7QQVLdgMNwySTXnA3VQPEqC9yO-SNrmvOL8y4QJOuGmAOCSx69FXk5LR24bcJd6d-rXruRTgSPC50p8liY_oa71i0PGzJSo-UKrZA1ff5PJStvxXfdAX7Bzik5eusqdA9bps9k3xs3DljTOmAduJMwwuxEAcIvHjb9tQZ4MzbPe99CUpT3SEKgBE6vcCCZjf8iJqcjVVK5Uw8IcShDL77aqMPkWozM9J62DKGo-lwKntYm1KWP4ElwLnpc8USPHP8hGhCZyscsVxBeauREpzl7102BO3Yf19dpzG7hUV8kZ2SL82zYQt3VfuFTeqca7voNdBeML7CGAUWC0uNKXHAb7MFiossXokqsJSwOVrXZvVlDntcyVeDbfHcRwsKwXPDHw3WvhODvw9rhfcHpSfJWQnIy1WRbSRFeInsvEIF3xUCY-FfawJFWVo4w1ttaIWPy4Rj_fY05HRVH1gsh0HVzFrcKVE31Jk2-jkWvUUa63HLkx14wpC4fKK1fBtff8xnGBm8jhQoAfZUwcCi0VDh-UdSsrs174K-dy-XegJAdBNxqJ2_l-l85Dqp1Yo66b9e0INyAkbrLwfR5TSc_zXZQstnRD4nJPhN_3Aep88gOHh1mKmb7wdW0KzR3yOV09j5fCsAg0H_JuJzK1Raxu9fFmUkBoXkIjfv2_M1NFvrT0urogIp5Gt7G7Qsr3NWwfCSrFvjg_ml75TdFuHWlq_9LhIvfY-avHRZihZ5ci-L5ze5MALd5bNQ9wXu6Kg941pTz_gRiHDtvVdRFlEEXJW_VvORanjBfB9enJuDj9zqQwZixKP-cqJXkhqstRFGfu5uySmw6qTLnHLjnqNy7xbcgc4BRkUHxWh3wcFmon061w3EL60mZvathxZTl8kGGovLvWoNh8rZhn5jl4rzGrx5L0KNz4jxBcNWAawC-eqWehhL3UM5I3sQUsRKj5ZNIM7-xWBL7UazjH1URVpjpfNKiHpc3IEyeR54SLwtdnVFH6grOJm3WXi4j6l-KN10_3YGwoCVI0PDCE0TFtuNOcqmeUVOkwGrTK7VlZnLPfTFFr75cG79gGeUi4JXWYben_mp3lRXQT4VqX76U8qXjjDHSKFIerMvwTbQgGxDOkYJLpDQHifqG0WM1sglnffvVZcKZbCmPjjjWW9bNiuH7AztTgjyxORbg0PrduNqnVd6kaGIhvnSocHWXVgOo0_Ve4r3dGBJTu5XnSOEzRBZ0WtoPr58Jd-HDvlrmlnP4y6Nr6xWyib7Nu5UC4lXuel16CLxlBQcZWBk767pk7aJVjdCwwAEooesovtIBSsNb7I9WUXs5VvDzBs8eC39neeKU1kbY2ZHA_PLtihWits73tMXYD3XIcV-x3fBkCnIBvNEWIOLhp3CpVE6B68BsuxtGXiCE268mhiAN5BSdYQDahC7jT7x__3cmI5Cfv9Z9I05Xb4CA3RL4IoITjt92pDeIiFtvPDAZCOP51OctQyXhRgzG6RRpcR0ZEkif4ElGS8MS8riCXxsKpX2VeKfmicur0ZrL6U7gtQC4gE0TOzLGlal9S49yxaq-4ssO9IBMt4Kr7lZ0I4YRTtI5OAkYH2TFTDgXc5_G4zH07XZ2KgZYsY2FQ0uS4a2Z36QlGKpMCwf0dx2c1cm-YMYSl7QaVt9w6dqNijq3gdY54czPO6JhDzFRjWL05fVqQEOj4qMV6YgicrTYPajtmOrQk79C0GrH26SgXb-JB-APf1IHH-_ki8JVf9isgq9F8tVDrTsy9X-0DvUkSp-LFoGHtzKJew4MjgSIat3RcczT0VH_yS8X3XPyUpzVSeX3wAfAZQe2MwuP3s_1siDroGr7g--ekMDAkB4QL7fKb2yl5w_5PZ7FagtrCxFvvfsC86FIEhI_ZWqMMH_cPLzJCd5QM4WtZecxmcJo5PQhF3KzidAspouCPU7CJ454eFW4SvtfoslwbuzIbIbE8TiaIwnRXroSZ5L_MvVOY3gK4IwTu7JBABbDxMAmZRRAjts7FWYrpfbkx1FmmeZh0GsC5bvEMHuHwSBubmriW2a3AShqWvg3-UwYQKzQ45nGVnCarBzsf5axYkHzjn1PH0Xlvl619PPyyD8byn8CLU8SW7TA1JQhRkdv2jRncTvw8jfw5cutKsXtRLgCkBCyZftXbgLE0JugNecApTxRe-q7I79ys=.eyJlbmRwb2ludF9zbHVnIjoib3BlbmFpL2dwdC01LjItMjAyNTEyMTF8b3BlbmFpIn0", "format": "openai-responses-v1" }, { "id": "msg_tmp_sthg0k9a4qs", "type": "message", "role": "assistant", "status": "completed", "content": [ { "type": "output_text", "text": "There isn’t a single, universally agreed “meaning of life.” Different traditions answer it differently, and a lot of modern thought treats meaning as something you *make* rather than something you *find*. Here are a few of the main ways people understand it:\n\n- **Biological/evolutionary:** Life’s “purpose” is to survive and reproduce—meaning is an emergent story we add on top of that.\n- **Religious/spiritual:** Meaning comes from relationship to the divine, fulfilling moral duties, awakening, salvation, or aligning with a sacred order.\n- **Philosophical (existentialist):** The universe doesn’t hand you meaning; you create it through choices, responsibility, and authenticity.\n- **Humanistic/psychological:** Meaning tends to come from **relationships**, **mastery/growth**, **contributing beyond yourself**, and **living by values** (e.g., compassion, honesty, curiosity).\n\nIf you want a practical synthesis many people find satisfying: \n**The meaning of life is to live in a way that’s aligned with your values, deepens connection, reduces needless suffering (yours and others’), and helps you grow—while appreciating the fact that you’re here at all.**\n\nIf you tell me what lens you’re asking from (religious, philosophical, scientific, personal), I can tailor an answer—and if you want, we can turn it into a concrete “meaning statement” for your life based on what you care about.", "annotations": [], "logprobs": [] } ] } ], "error": null, "incomplete_details": null, "access_programs": {

[!NOTE]

Model routing

Если параметр model опущен, используется значение по умолчанию пользователя или плательщика. В противном случае убедитесь, что выбрали значение model из supported models или API, включив префикс организации. API ВЕГА выберет наименее дорогие и лучшие GPU, доступные для обработки запроса, и при необходимости переключится на других провайдеров или GPU, если получит код ошибки 5xx или будет ограничен по скорости.

[!NOTE]

Streaming

Server-Sent Events (SSE) также поддерживаются, позволяя включить потоковую передачу для всех моделей. Просто укажите stream: true в теле запроса. Поток SSE время от времени будет содержать «comment»‑payload, который следует игнорировать (см. ниже).

[!NOTE]

Non-standard parameters

Если выбранная модель не поддерживает определённый параметр запроса (например, logit_bias в моделях, не являющихся OpenAI, или top_k для OpenAI), параметр игнорируется. Остальные параметры передаются в базовый API модели.

Assistant prefill

API ВЕГА поддерживает запрос у модели завершить частичный ответ. Это может быть полезно для направления модели к определённому стилю ответа.

Чтобы воспользоваться этой функцией, просто добавьте сообщение с role: "assistant" в конец массива input (Responses API) или messages (Chat Completions).

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { Authorization: 'Bearer <OPENROUTER_API_KEY>', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-5.2', input: [ { role: 'user', content: 'What is the meaning of life?' }, { role: 'assistant', content: "I'm not sure, but my best guess is" }, ], }), });
typescript
fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer <OPENROUTER_API_KEY>', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-5.2', messages: [ { role: 'user', content: 'What is the meaning of life?' }, { role: 'assistant', content: "I'm not sure, but my best guess is" }, ], }), });
python
response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer <OPENROUTER_API_KEY>', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-5.2', 'input': [ {'role': 'user', 'content': 'What is the meaning of life?'}, {'role': 'assistant', 'content': "I'm not sure, but my best guess is"}, ], }, )
go
body := strings.NewReader(`{ "model": "openai/gpt-5.2", "input": [ {"role": "user", "content": "What is the meaning of life?"}, {"role": "assistant", "content": "I'm not sure, but my best guess is"} ] }`) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", body) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req)
bash
curl -sS https://openrouter.ai/api/v1/responses \ -o response.json \ -w "Status: %{http_code}\n" \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "input": [ { "role": "user", "content": "What is the meaning of life?" }, { "role": "assistant", "content": "I'\''m not sure, but my best guess is" } ] }'

Responses

Responses API response format

Ответ Responses API передаёт сгенерированное содержимое в виде элементов массива output: элементы message содержат части output_text, а элементы reasoning, function_call и серверных инструментов (например, openrouter:web_search) появляются как отдельные записи. Счётчики токенов находятся в usage.input_tokens, usage.output_tokens и usage.total_tokens. Полная схема находится в Responses API reference.

json
{ "id": "resp_1234567890", "object": "response", "created_at": 1234567890, "model": "openai/gpt-5.2", "status": "completed", "output": [ { "type": "message", "id": "msg_abc123", "status": "completed", "role": "assistant", "content": [{ "type": "output_text", "text": "The meaning of life is...", "annotations": [] }] } ], "usage": { "input_tokens": 12, "output_tokens": 45, "total_tokens": 57 } }

CompletionsResponse format

API ВЕГА нормализует схему между моделями и провайдерами в соответствии с OpenAI Chat API.

Это означает, что choices всегда массив, даже если модель возвращает только один результат. Каждый элемент будет содержать свойство delta, если запрошен поток, и свойство message в противном случае. Это упрощает использование единого кода для всех моделей.

Схема ответа в виде TypeScript‑типа:

typescript
// Definitions of subtypes are below type Response = { id: string; // Depending on whether you set "stream" to "true" and // whether you passed in "messages" or a "prompt", you // will get a different output shape choices: (NonStreamingChoice | StreamingChoice | NonChatChoice)[]; created: number; // Unix timestamp model: string; object: 'chat.completion' | 'chat.completion.chunk'; system_fingerprint?: string; // Only present if the provider supports it // Usage data is always returned for non-streaming. // When streaming, usage is returned exactly once in the final chunk // before the [DONE] message. Unlike OpenAI's spec, this chunk contains // a non-empty choices array: a choice with a content-free delta that // repeats the finish_reason of the stream. usage?: ResponseUsage; };
typescript
// API ВЕГА always returns detailed usage information. // Token counts are calculated using the model's native tokenizer. type ResponseUsage = { /** Including images, input audio, and tools if any */ prompt_tokens: number; /** The tokens generated */ completion_tokens: number; /** Sum of the above two fields */ total_tokens: number; /** Breakdown of prompt tokens (optional) */ prompt_tokens_details?: { cached_tokens: number; // Tokens cached by the endpoint cache_write_tokens?: number; // Tokens written to cache (models with explicit caching) audio_tokens?: number; // Tokens used for input audio video_tokens?: number; // Tokens used for input video }; /** Breakdown of completion tokens (optional) */ completion_tokens_details?: { reasoning_tokens?: number; // Tokens generated for reasoning audio_tokens?: number; // Tokens generated for audio output image_tokens?: number; // Tokens generated for image output }; /** Cost in credits (optional) */ cost?: number; /** Whether request used Bring Your Own Key */ is_byok?: boolean; /** Detailed cost breakdown (optional) */ cost_details?: { upstream_inference_cost?: number; upstream_inference_prompt_cost: number; upstream_inference_completions_cost: number; /** Metered server-tool execution cost (e.g. shell sandbox time), billed in USD */ server_tool_cost?: number | null; }; /** Server-side tool usage; omitted when no server tool usage is recorded */ server_tool_use_details?: { tool_calls_requested?: number; tool_calls_executed?: number; web_search_requests?: number; }; };
typescript
// Subtypes: type NonChatChoice = { finish_reason: string | null; text: string; error?: ErrorResponse; }; type NonStreamingChoice = { finish_reason: string | null; native_finish_reason: string | null; message: { content: string | null; role: string; tool_calls?: ToolCall[]; }; error?: ErrorResponse; }; type StreamingChoice = { finish_reason: string | null; native_finish_reason: string | null; delta: { content: string | null; role?: string; tool_calls?: ToolCall[]; }; error?: ErrorResponse; }; type ErrorResponse = { code: number; // See "Error Handling" section message: string; metadata?: Record<string, unknown>; // Contains additional error information such as provider details, the raw error message, etc. }; type ToolCall = { id: string; type: 'function'; function: FunctionCall; };

Пример:

json
{ "id": "gen-xxxxxxxxxxxxxx", "choices": [ { "finish_reason": "stop", // Normalized finish_reason "native_finish_reason": "stop", // The raw finish_reason from the provider "message": { // will be "delta" if streaming "role": "assistant", "content": "Hello there!" } } ], "usage": { "prompt_tokens": 10, "completion_tokens": 4, "total_tokens": 14, "prompt_tokens_details": { "cached_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0 }, "cost": 0.00014 }, "model": "openai/gpt-4o" // Could also be "anthropic/claude-sonnet-4.6", etc, depending on the "model" that ends up being used }

Finish reason

API ВЕГА нормализует finish_reason каждой модели до одного из следующих значений: tool_calls, stop, length, content_filter, error.

У некоторых моделей и провайдеров могут быть дополнительные причины завершения. Необработанная строка finish_reason, возвращённая моделью, доступна через свойство native_finish_reason.

Querying cost and stats

Счётчики токенов, возвращаемые в ответе API, рассчитываются с использованием нативного токенизатора модели. Использование кредитов и цены моделей основаны на этих нативных токенах.

Вы также можете использовать возвращённый id для запроса статистики генерации (включая количество токенов и стоимость) после завершения запроса через эндпоинт /api/v1/generation. Это удобно для аудита исторического использования или асинхронного получения статистики.

typescript
const generation = await fetch( `https://openrouter.ai/api/v1/generation?id=${generationId}`, { headers }, ); const stats = await generation.json();
python
generation = requests.get( 'https://openrouter.ai/api/v1/generation', params={'id': generation_id}, headers=headers, ) stats = generation.json()
go
req, _ := http.NewRequest("GET", "https://openrouter.ai/api/v1/generation?id="+generationId, nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } var stats map[string]any json.NewDecoder(resp.Body).Decode(&stats)
bash
curl -sS -G https://openrouter.ai/api/v1/generation \ --data-urlencode "id=$GENERATION_ID" \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -o stats.json jq . stats.json

См. полную форму ответа в Generation API reference.

Обратите внимание, что счётчики токенов также доступны в поле usage тела ответа для запросов без потоковой передачи.