Documentation Index
Получите полный индекс документации по адресу: https://api.vega.chat/docs/llms.txt
Используйте этот файл, чтобы узнать о всех доступных страницах перед дальнейшим изучением.
Обзор 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.
{
"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.
type Request = {
messages?: Message[];
prompt?: string;
model?: string;
response_format?: ResponseFormat;
stop?: string | string[];
stream?: boolean;
plugins?: Plugin[];
max_tokens?: number;
temperature?: number;
tools?: Tool[];
tool_choice?: ToolChoice;
seed?: number;
top_p?: number;
top_k?: number;
frequency_penalty?: number;
presence_penalty?: number;
repetition_penalty?: number;
logit_bias?: { [key: number]: number };
top_logprobs: number;
min_p?: number;
top_a?: number;
prediction?: { type: 'content'; content: string };
models?: string[];
route?: 'fallback';
provider?: ProviderPreferences;
user?: string;
debug?: {
echo_upstream_body?: boolean;
};
};
type TextContent = {
type: 'text';
text: string;
};
type ImageContentPart = {
type: 'image_url';
image_url: {
url: string;
detail?: string;
};
};
type ContentPart = TextContent | ImageContentPart;
type Message =
| {
role: 'user' | 'assistant' | 'system';
content: string | ContentPart[];
name?: string;
}
| {
role: 'tool';
content: string;
tool_call_id: string;
name?: string;
};
type FunctionDescription = {
description?: string;
name: string;
parameters: object;
};
type Tool = {
type: 'function';
function: FunctionDescription;
};
type ToolChoice =
| 'none'
| 'auto'
| {
type: 'function';
function: {
name: string;
};
};
type ResponseFormat =
| { type: 'json_object' }
| {
type: 'json_schema';
json_schema: {
name: string;
strict?: boolean;
schema: object;
};
};
type Plugin = {
id: string;
enabled?: boolean;
[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 в ваш запрос:
{
"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)
fetch('https://openrouter.ai/api/v1/responses', {
method: 'POST',
headers: {
Authorization: 'Bearer <OPENROUTER_API_KEY>',
'HTTP-Referer': '<YOUR_SITE_URL>',
'X-OpenRouter-Title': '<YOUR_SITE_NAME>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-5.2',
input: 'What is the meaning of life?',
}),
});
fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: 'Bearer <OPENROUTER_API_KEY>',
'HTTP-Referer': '<YOUR_SITE_URL>',
'X-OpenRouter-Title': '<YOUR_SITE_NAME>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-5.2',
messages: [
{
role: 'user',
content: 'What is the meaning of life?',
},
],
}),
});
response = requests.post(
'https://openrouter.ai/api/v1/responses',
headers={
'Authorization': 'Bearer <OPENROUTER_API_KEY>',
'HTTP-Referer': '<YOUR_SITE_URL>',
'X-OpenRouter-Title': '<YOUR_SITE_NAME>',
'Content-Type': 'application/json',
},
json={
'model': 'openai/gpt-5.2',
'input': 'What is the meaning of life?',
},
)
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>")
req.Header.Set("X-OpenRouter-Title", "<YOUR_SITE_NAME>")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
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
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-jkWvUUa63HLkx14wpC4fKK1fBtff8xnGBm8jhQoAfZUw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07XZ2KgZYsY2FQ0uS4a2Z36QlGKpMCwf0dx2c1cm-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).
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" },
],
}),
});
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" },
],
}),
});
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"},
],
},
)
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)
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.
{
"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‑типа:
type Response = {
id: string;
choices: (NonStreamingChoice | StreamingChoice | NonChatChoice)[];
created: number;
model: string;
object: 'chat.completion' | 'chat.completion.chunk';
system_fingerprint?: string;
usage?: ResponseUsage;
};
type ResponseUsage = {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
prompt_tokens_details?: {
cached_tokens: number;
cache_write_tokens?: number;
audio_tokens?: number;
video_tokens?: number;
};
completion_tokens_details?: {
reasoning_tokens?: number;
audio_tokens?: number;
image_tokens?: number;
};
cost?: number;
is_byok?: boolean;
cost_details?: {
upstream_inference_cost?: number;
upstream_inference_prompt_cost: number;
upstream_inference_completions_cost: number;
server_tool_cost?: number | null;
};
server_tool_use_details?: {
tool_calls_requested?: number;
tool_calls_executed?: number;
web_search_requests?: number;
};
};
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;
message: string;
metadata?: Record<string, unknown>;
};
type ToolCall = {
id: string;
type: 'function';
function: FunctionCall;
};
Пример:
{
"id": "gen-xxxxxxxxxxxxxx",
"choices": [
{
"finish_reason": "stop",
"native_finish_reason": "stop",
"message": {
"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"
}
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. Это удобно для аудита исторического использования или асинхронного получения статистики.
const generation = await fetch(
`https://openrouter.ai/api/v1/generation?id=${generationId}`,
{ headers },
);
const stats = await generation.json();
generation = requests.get(
'https://openrouter.ai/api/v1/generation',
params={'id': generation_id},
headers=headers,
)
stats = generation.json()
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)
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 тела ответа для запросов без потоковой передачи.