Индекс документации

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

Вызов инструментов

MD версия

Вызов функций и интеграция инструментов с Responses API

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

Базовое определение инструмента

Определяйте инструменты, используя формат вызова функций OpenAI:

typescript
const weatherTool = { type: 'function' as const, name: 'get_weather', description: 'Get the current weather in a location', strict: null, parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA', }, unit: { type: 'string', enum: ['celsius', 'fahrenheit'], }, }, required: ['location'], }, }; const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_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 weather in San Francisco?', }, ], }, ], tools: [weatherTool], tool_choice: 'auto', max_output_tokens: 9000, }), }); const result = await response.json(); console.log(result);
python
import requests weather_tool = { 'type': 'function', 'name': 'get_weather', 'description': 'Get the current weather in a location', 'strict': None, 'parameters': { 'type': 'object', 'properties': { 'location': { 'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA', }, 'unit': { 'type': 'string', 'enum': ['celsius', 'fahrenheit'], }, }, 'required': ['location'], }, } response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'What is the weather in San Francisco?', }, ], }, ], 'tools': [weather_tool], 'tool_choice': 'auto', 'max_output_tokens': 9000, } ) result = response.json() print(result)
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer YOUR_OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/o4-mini", "input": [ { "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "What is the weather in San Francisco?" } ] } ], "tools": [ { "type": "function", "name": "get_weather", "description": "Get the current weather in a location", "strict": null, "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } ], "tool_choice": "auto", "max_output_tokens": 9000 }'

Параметры выбора инструмента

Контролируйте, когда и как вызываются инструменты:

Выбор инструментаОписание
autoМодель решает, вызывать ли инструменты
noneМодель не будет вызывать никакие инструменты
{type: 'function', name: 'tool_name'}Принудительный вызов конкретного инструмента

Принудительный вызов конкретного инструмента

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/o4-mini', input: [ { type: 'message', role: 'user', content: [ { type: 'input_text', text: 'Hello, how are you?', }, ], }, ], tools: [weatherTool], tool_choice: { type: 'function', name: 'get_weather' }, max_output_tokens: 9000, }), });
python
import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'Hello, how are you?', }, ], }, ], 'tools': [weather_tool], 'tool_choice': {'type': 'function', 'name': 'get_weather'}, 'max_output_tokens': 9000, } )

Отключить вызов инструментов

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_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 weather in Paris?', }, ], }, ], tools: [weatherTool], tool_choice: 'none', max_output_tokens: 9000, }), });
python
import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'What is the weather in Paris?', }, ], }, { 'type': 'function', 'name': 'get_weather', 'description': 'Get the current weather in a location', 'strict': None, 'parameters': { 'type': 'object', 'properties': { 'location': { 'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA', }, 'unit': { 'type': 'string', 'enum': ['celsius', 'fahrenheit'], }, }, 'required': ['location'], }, }, ], 'tools': [weather_tool], 'tool_choice': 'none', 'max_output_tokens': 9000, } )

Несколько инструментов

Определите несколько инструментов для сложных рабочих процессов:

typescript
const calculatorTool = { type: 'function' as const, name: 'calculate', description: 'Perform mathematical calculations', strict: null, parameters: { type: 'object', properties: { expression: { type: 'string', description: 'The mathematical expression to evaluate', }, }, required: ['expression'], }, }; const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_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 25 * 4?', }, ], }, ], tools: [weatherTool, calculatorTool], tool_choice: 'auto', max_output_tokens: 9000, }), });
python
calculator_tool = { 'type': 'function', 'name': 'calculate', 'description': 'Perform mathematical calculations', 'strict': None, 'parameters': { 'type': 'object', 'properties': { 'expression': { 'type': 'string', 'description': 'The mathematical expression to evaluate', }, }, 'required': ['expression'], }, } response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'What is 25 * 4?', }, ], }, ], 'tools': [weather_tool, calculator_tool], 'tool_choice': 'auto', 'max_output_tokens': 9000, } )

Параллельные вызовы инструментов

API поддерживает параллельное выполнение нескольких инструментов:

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/o4-mini', input: [ { type: 'message', role: 'user', content: [ { type: 'input_text', text: 'Calculate 10*5 and also tell me the weather in Miami', }, ], }, ], tools: [weatherTool, calculatorTool], tool_choice: 'auto', max_output_tokens: 9000, }), }); const result = await response.json(); console.log(result);
python
import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'Calculate 10*5 and also tell me the weather in Miami', }, ], }, ], 'tools': [weather_tool, calculator_tool], 'tool_choice': 'auto', 'max_output_tokens': 9000, } ) result = response.json() print(result)

Ответ вызова инструмента

Когда инструменты вызываются, ответ включает информацию о вызове функции:

json
{ "id": "resp_1234567890", "object": "response", "created_at": 1234567890, "model": "openai/o4-mini", "output": [ { "type": "function_call", "id": "fc_abc123", "call_id": "call_xyz789", "name": "get_weather", "arguments": "{\"location\":\"San Francisco, CA\"}" } ], "usage": { "input_tokens": 45, "output_tokens": 25, "total_tokens": 70 }, "status": "completed" }

Ответы инструментов в диалоге

Включайте ответы инструментов в последующие запросы:

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_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 weather in Boston?', }, ], }, { type: 'function_call', id: 'fc_1', call_id: 'call_123', name: 'get_weather', arguments: JSON.stringify({ location: 'Boston, MA' }), }, { type: 'function_call_output', id: 'fc_output_1', call_id: 'call_123', output: JSON.stringify({ temperature: '72°F', condition: 'Sunny' }), }, { type: 'message', role: 'assistant', id: 'msg_abc123', status: 'completed', content: [ { type: 'output_text', text: 'The weather in Boston is currently 72°F and sunny. This looks like perfect weather for a picnic!', annotations: [] } ] }, { type: 'message', role: 'user', content: [ { type: 'input_text', text: 'Is that good weather for a picnic?', }, ], }, ], max_output_tokens: 9000, }), });
python
import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'What is the weather in Boston?', }, ], }, { 'type': 'function_call', 'id': 'fc_1', 'call_id': 'call_123', 'name': 'get_weather', 'arguments': '{"location": "Boston, MA"}', }, { 'type': 'function_call_output', 'id': 'fc_output_1', 'call_id': 'call_123', 'output': '{"temperature": "72°F", "condition": "Sunny"}', }, { 'type': 'message', 'role': 'assistant', 'id': 'msg_abc123', 'status': 'completed', 'content': [ { 'type': 'output_text', 'text': 'The weather in Boston is currently 72°F and sunny. This looks like perfect weather for a picnic!', 'annotations': [] } ] }, { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'Is that good weather for a picnic?', }, ], }, ], 'max_output_tokens': 9000, } )

Необязательное поле

Поле id является необязательным для объектов function_call_output. Требуются только type, call_id и outputcall_id связывает вывод с исходным function_call. Примеры выше включают id для полноты, но вы можете смело опустить его.

Мультимодальные выводы инструмента

function_call_output.output принимает либо строку, либо массив частей входного контента (input_text, input_image, input_file) — ту же структуру, что и содержимое пользовательского сообщения. Используйте форму массива, чтобы вернуть изображения или файлы из инструмента; нетекстовые части передаются только поддерживаемым мультимодальным моделям.

json
{ "type": "function_call_output", "call_id": "call_123", "output": [ { "type": "input_text", "text": "{\"results\":[{\"title\":\"Golden Gate Bridge\"}]}" }, { "type": "input_image", "image_url": "https://example.com/image.jpg" } ] }

Потоковые вызовы инструментов

Отслеживайте вызовы инструментов в реальном времени с помощью потоковой передачи:

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENROUTER_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 weather like in Tokyo, Japan? Please check the weather.', }, ], }, ], tools: [weatherTool], tool_choice: 'auto', 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); if (parsed.type === 'response.output_item.added' && parsed.item?.type === 'function_call') { console.log('Function call:', parsed.item.name); } if (parsed.type === 'response.function_call_arguments.done') { console.log('Arguments:', parsed.arguments); } } catch (e) { // Skip invalid JSON } } } }
python
import requests import json response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': 'Bearer YOUR_OPENROUTER_API_KEY', 'Content-Type': 'application/json', }, json={ 'model': 'openai/o4-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'What is the weather like in Tokyo, Japan? Please check the weather.', }, ], }, ], 'tools': [weather_tool], 'tool_choice': 'auto', '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) if (parsed.get('type') == 'response.output_item.added' and parsed.get('item', {}).get('type') == 'function_call'): print(f"Function call: {parsed['item']['name']}") if parsed.get('type') == 'response.function_call_arguments.done': print(f"Arguments: {parsed.get('arguments', '')}") except json.JSONDecodeError: continue

Проверка инструмента

Убедитесь, что вызовы инструментов имеют правильную структуру:

json
{ "type": "function_call", "id": "fc_abc123", "call_id": "call_xyz789", "name": "get_weather", "arguments": "{\"location\":\"Seattle, WA\"}" }

Обязательные поля:

  • type: всегда "function_call"
  • id: уникальный идентификатор объекта вызова функции
  • name: имя функции, соответствующее определению инструмента
  • arguments: корректная JSON‑строка с параметрами функции
  • call_id: уникальный идентификатор вызова

Лучшие практики

  1. Чёткие описания: предоставляйте подробные описания функций и объяснения параметров
  2. Корректные схемы: используйте валидные JSON Schema для параметров
  3. Обработка ошибок: учитывайте случаи, когда инструменты могут не быть вызваны
  4. Параллельное выполнение: по возможности проектируйте инструменты так, чтобы они могли работать независимо
  5. Поток диалога: включайте ответы инструментов в последующие запросы для сохранения контекста

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

  • Узнайте о интеграции Web Search
  • Исследуйте Reasoning с инструментами
  • Ознакомьтесь с основами Basic Usage