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

# Ссылка на API

> Обзор API VEGA

Схемы запросов и ответов API VEGA очень похожи на Chat API от OpenAI, с небольшими различиями. На высоком уровне **API VEGA нормализует схему между моделями и провайдерами**, так что вам нужно изучить только одну.

## Спецификация OpenAPI

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

* **YAML**: [https://api.vega.chat/openapi.yaml](https://api.vega.chat/openapi.yaml)
* **JSON**: [https://api.vega.chat/openapi.json](https://api.vega.chat/openapi.json)

Эти спецификации можно использовать с такими инструментами, как [Swagger UI](https://swagger.io/tools/swagger-ui/), [Postman](https://www.postman.com/) или любой генератор кода, совместимый с OpenAPI, чтобы исследовать API или генерировать клиентские библиотеки.

## Запросы

### Формат запроса Completions

Ниже приведена схема запроса в виде TypeScript‑типа. Это будет тело вашего `POST`‑запроса к эндпоинту `/api/v1/chat/completions` (см. [быстрый старт](/docs/quickstart) выше для примера).

Полный список параметров смотрите в разделе [Parameters](/docs/api_reference/parameters).

<CodeGroup>
  ```typescript title="Request Schema" expandable lines theme={null}
  // 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/guides/features/plugins
    plugins?: Plugin[];

    // See LLM Parameters (openrouter.ai/docs/api_reference/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/guides/latency-optimization#use-predicted-outputs
    prediction?: { type: 'content'; content: string };

    // OpenRouter-only parameters
    // See "Model Routing" section: openrouter.ai/docs/guides/features/model-routing
    models?: string[];
    route?: 'fallback';
    // See "Provider Routing" section: openrouter.ai/docs/guides/routing/provider-selection
    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;
  };
  ```
</CodeGroup>

### Структурированные выводы

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

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

Подробное использование и примеры см. в разделе [Structured Outputs](/docs/guides/features/structured-outputs). Чтобы найти модели, поддерживающие структурированные выводы, проверьте [страницу моделей](https://api.vega.chat/models?supported_parameters=structured_outputs).

### Плагины

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

```json lines theme={null}
{
  "plugins": [
    { "id": "web" },
    { "id": "response-healing" }
  ]
}
```

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

### Заголовки

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

* `HTTP-Referer`: Идентифицирует ваше приложение на api.vega.chat
* `X-OpenRouter-Title`: Устанавливает/изменяет заголовок вашего приложения (`X-Title` также принимается)
* `X-OpenRouter-Categories`: Назначает категории маркетплейса (см. [App Attribution](/docs/app-attribution))

<CodeGroup>
  ```typescript title="TypeScript" lines theme={null}
  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?',
        },
      ],
    }),
  });
  ```
</CodeGroup>

<Info>
  **Маршрутизация моделей**

  Если параметр `model` опущен, используется значение по умолчанию пользователя или плательщика.
  В противном случае выберите значение `model` из [поддерживаемых
  моделей](/docs/guides/overview/models) или [API](/docs/api/api-reference/models/list-all-models-and-their-properties), указав префикс организации. API VEGA выберет наиболее дешёвый и быстрый GPU, доступный для выполнения запроса, и при необходимости переключится на других провайдеров или GPU, если получит ответ с кодом 5xx или будет ограничен по частоте запросов.
</Info>

<Info>
  **Потоковая передача**

  [Server-Sent Events
  (SSE)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format)
  поддерживаются, позволяя включить потоковую передачу *для всех моделей*. Просто укажите
  `stream: true` в теле вашего запроса. В SSE‑потоке иногда будет присутствовать полезная нагрузка «comment», которую следует игнорировать (см. ниже).
</Info>

<Info>
  **Нестандартные параметры**

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

### Предзаполнение ассистента

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

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

<CodeGroup>
  ```typescript title="TypeScript" lines theme={null}
  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" },
      ],
    }),
  });
  ```
</CodeGroup>

## Ответы

### Формат CompletionsResponse

 API VEGA нормализует схему между моделями и провайдерами в соответствии с [Chat API от OpenAI](https://platform.openai.com/docs/api-reference/chat).

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

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

```typescript TypeScript lines theme={null}
// 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, with an empty choices array.
  usage?: ResponseUsage;
};
```

```typescript expandable lines theme={null}
// OpenRouter 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;
  };

  /** Server-side tool usage (optional) */
  server_tool_use?: {
    web_search_requests?: number;
  };
};
```

```typescript expandable lines theme={null}
// 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 expandable lines theme={null}
{
  "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
}
```

### Причина завершения

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

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

### Запрос стоимости и статистики

Количество токенов, возвращаемое в ответе API completions, рассчитывается с использованием нативного токенизатора модели. Потребление кредитов и цены модели основаны на этих нативных подсчётах токенов.

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

<CodeGroup>
  ```typescript title="Query Generation Stats" lines theme={null}
  const generation = await fetch(
    'https://openrouter.ai/api/v1/generation?id=$GENERATION_ID',
    { headers },
  );

  const stats = await generation.json();
  ```
</CodeGroup>

Смотрите справочник API [Generation](/docs/api/api-reference/generations/get-request-&-usage-metadata-for-a-generation) для полной структуры ответа.

Обратите внимание, что количество токенов также доступно в поле `usage` тела ответа для неблокирующих (non‑streaming) завершений.