Для получения чистого Markdown любой страницы добавьте .md к URL страницы.
Для полного индекса документации см. https://api.vega.chat/docs/llms.txt.
Для полного содержания документации см. https://api.vega.chat/docs/llms-full.txt.
Для интеграции AI‑клиентов (Claude Code, Cursor и др.) подключитесь к серверу MCP по адресу https://api.vega.chat/docs/_mcp/server.

Базовое использование

MD версия

Этот API находится в бета-версии и может содержать несовместимые изменения.

Responses API Beta поддерживает как простой ввод строки, так и структурированные массивы сообщений, что упрощает начало работы с базовой генерацией текста.

Простой ввод строки

Самый простой способ использовать API — передать строку в качестве ввода:

typescript
const response = await fetch('https://api.vega.chat/api/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_VEGA_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/o4-mini',
    input: 'What is the meaning of life?',
    max_output_tokens: 9000,
  }),
});

const result = await response.json();
console.log(result);
python
import requests

response = requests.post(
    'https://api.vega.chat/api/v1/responses',
    headers={
        'Authorization': 'Bearer YOUR_VEGA_API_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'openai/o4-mini',
        'input': 'What is the meaning of life?',
        'max_output_tokens': 9000,
    }
)

result = response.json()
print(result)
bash
curl -X POST https://api.vega.chat/api/v1/responses \
  -H "Authorization: Bearer YOUR_VEGA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/o4-mini",
    "input": "What is the meaning of life?",
    "max_output_tokens": 9000
  }'

Структурированный ввод сообщений

Для более сложных диалогов используйте формат массива сообщений:

typescript
const response = await fetch('https://api.vega.chat/api/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_VEGA_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/o4-mini',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'Tell me a joke about programming',
          },
        ],
      },
    ],
    max_output_tokens: 9000,
  }),
});

const result = await response.json();
python
import requests

response = requests.post(
    'https://api.vega.chat/api/v1/responses',
    headers={
        'Authorization': 'Bearer YOUR_VEGA_API_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'openai/o4-mini',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'Tell me a joke about programming',
                    },
                ],
            },
        ],
        'max_output_tokens': 9000,
    }
)

result = response.json()
bash
curl -X POST https://api.vega.chat/api/v1/responses \
  -H "Authorization: Bearer YOUR_VEGA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/o4-mini",
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": [
          {
            "type": "input_text",
            "text": "Tell me a joke about programming"
          }
        ]
      }
    ],
    "max_output_tokens": 9000
  }'

Формат ответа

API возвращает структурированный ответ с сгенерированным содержимым:

json
{
  "id": "resp_1234567890",
  "object": "response",
  "created_at": 1234567890,
  "model": "openai/o4-mini",
  "output": [
    {
      "type": "message",
      "id": "msg_abc123",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The meaning of life is a philosophical question that has been pondered for centuries...",
          "annotations": []
        }
      ]
    }
  ],
  "usage": {
    "input_tokens": 12,
    "output_tokens": 45,
    "total_tokens": 57
  },
  "status": "completed"
}

Потоковые ответы

Включите потоковую передачу для генерации ответов в реальном времени:

typescript
const response = await fetch('https://api.vega.chat/api/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_VEGA_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/o4-mini',
    input: 'Write a short story about AI',
    stream: true,
    max_output_tokens: 9000,
  }),
});

const reader = response.body?.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const chunk = decoder.decode(value);
  const lines = chunk.split('\n');

  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = line.slice(6);
      if (data === '[DONE]') return;

      try {
        const parsed = JSON.parse(data);
        console.log(parsed);
      } catch (e) {
        // Skip invalid JSON
      }
    }
  }
}
python
import requests
import json

response = requests.post(
    'https://api.vega.chat/api/v1/responses',
    headers={
        'Authorization': 'Bearer YOUR_VEGA_API_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'openai/o4-mini',
        'input': 'Write a short story about AI',
        'stream': True,
        'max_output_tokens': 9000,
    },
    stream=True
)

for line in response.iter_lines():
    if line:
        line_str = line.decode('utf-8')
        if line_str.startswith('data: '):
            data = line_str[6:]
            if data == '[DONE]':
                break
            try:
                parsed = json.loads(data)
                print(parsed)
            except json.JSONDecodeError:
                continue

Пример потокового вывода

Потоковый ответ возвращает фрагменты Server-Sent Events (SSE):

data: {"type":"response.created","response":{"id":"resp_1234567890","object":"response","status":"in_progress"}} data: {"type":"response.output_item.added","response_id":"resp_1234567890","output_index":0,"item":{"type":"message","id":"msg_abc123","role":"assistant","status":"in_progress","content":[]}} data: {"type":"response.content_part.added","response_id":"resp_1234567890","output_index":0,"content_index":0,"part":{"type":"output_text","text":""}} data: {"type":"response.content_part.delta","response_id":"resp_1234567890","output_index":0,"content_index":0,"delta":"Once"} data: {"type":"response.content_part.delta","response_id":"resp_1234567890","output_index":0,"content_index":0,"delta":" upon"} data: {"type":"response.content_part.delta","response_id":"resp_1234567890","output_index":0,"content_index":0,"delta":" a"} data: {"type":"response.content_part.delta","response_id":"resp_1234567890","output_index":0,"content_index":0,"delta":" time"} data: {"type":"response.output_item.done","response_id":"resp_1234567890","output_index":0,"item":{"type":"message","id":"msg_abc123","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Once upon a time, in a world where artificial intelligence had become as common as smartphones..."}]}} data: {"type":"response.done","response":{"id":"resp_1234567890","object":"response","status":"completed","usage":{"input_tokens":12,"output_tokens":45,"total_tokens":57}}} data: [DONE]

Общие параметры

ПараметрТипОписание
modelstringОбязательно. Модель для использования (например, openai/o4-mini)
inputstring or arrayОбязательно. Текст или массив сообщений
streambooleanВключить потоковые ответы (по умолчанию: false)
max_output_tokensintegerМаксимальное количество генерируемых токенов
temperaturenumberТемпература сэмплинга (0-2)
top_pnumberПараметр ядерного сэмплинга (0-1)

Обработка ошибок

Обрабатывайте распространённые ошибки корректно:

typescript
try {
  const response = await fetch('https://api.vega.chat/api/v1/responses', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_VEGA_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'openai/o4-mini',
      input: 'Hello, world!',
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    console.error('API Error:', error.error.message);
    return;
  }

  const result = await response.json();
  console.log(result);
} catch (error) {
  console.error('Network Error:', error);
}
python
import requests

try:
    response = requests.post(
        'https://api.vega.chat/api/v1/responses',
        headers={
            'Authorization': 'Bearer YOUR_VEGA_API_KEY',
            'Content-Type': 'application/json',
        },
        json={
            'model': 'openai/o4-mini',
            'input': 'Hello, world!',
        }
    )

    if response.status_code != 200:
        error = response.json()
        print(f"API Error: {error['error']['message']}")
    else:
        result = response.json()
        print(result)

except requests.RequestException as e:
    print(f"Network Error: {e}")

Многовопросные диалоги

Поскольку Responses API Beta является stateless, вам необходимо включать полную историю диалога в каждый запрос, чтобы сохранять контекст:

typescript
// Первый запрос
const firstResponse = await fetch('https://api.vega.chat/api/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_VEGA_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/o4-mini',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'What is the capital of France?',
          },
        ],
      },
    ],
    max_output_tokens: 9000,
  }),
});

const firstResult = await firstResponse.json();

// Второй запрос — включаем предыдущий диалог
const secondResponse = await fetch('https://api.vega.chat/api/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_VEGA_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/o4-mini',
    input: [
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'What is the capital of France?',
          },
        ],
      },
      {
        type: 'message',
        role: 'assistant',
        id: 'msg_abc123',
        status: 'completed',
        content: [
          {
            type: 'output_text',
            text: 'The capital of France is Paris.',
            annotations: []
          }
        ]
      },
      {
        type: 'message',
        role: 'user',
        content: [
          {
            type: 'input_text',
            text: 'What is the population of that city?',
          },
        ],
      },
    ],
    max_output_tokens: 9000,
  }),
});

const secondResult = await secondResponse.json();
python
import requests

# Первый запрос
first_response = requests.post(
    'https://api.vega.chat/api/v1/responses',
    headers={
        'Authorization': 'Bearer YOUR_VEGA_API_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'openai/o4-mini',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'What is the capital of France?',
                    },
                ],
            },
        ],
        'max_output_tokens': 9000,
    }
)

first_result = first_response.json()

# Второй запрос — включаем предыдущий диалог
second_response = requests.post(
    'https://api.vega.chat/api/v1/responses',
    headers={
        'Authorization': 'Bearer YOUR_VEGA_API_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'model': 'openai/o4-mini',
        'input': [
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'What is the capital of France?',
                    },
                ],
            },
            {
                'type': 'message',
                'role': 'assistant',
                'id': 'msg_abc123',
                'status': 'completed',
                'content': [
                    {
                        'type': 'output_text',
                        'text': 'The capital of France is Paris.',
                        'annotations': []
                    }
                ]
            },
            {
                'type': 'message',
                'role': 'user',
                'content': [
                    {
                        'type': 'input_text',
                        'text': 'What is the population of that city?',
                    },
                ],
            },
        ],
        'max_output_tokens': 9000,
    }
)

second_result = second_response.json()

Поле id и status обязательны для всех сообщений роли assistant, включённых в историю диалога.

Всегда включайте полную историю диалога в каждый запрос. API не сохраняет предыдущие сообщения, поэтому контекст необходимо поддерживать на стороне клиента.

Следующие шаги

  • Узнайте о возможностях Reasoning
  • Исследуйте функциональность Tool Calling
  • Попробуйте интеграцию Web Search