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

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

api guides

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

MD версия

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

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

Вызов инструментов с помощью Agent SDK

SDK API ВЕГА agent (@openrouter/agent для TypeScript, openrouter_agent для Python) полностью автоматизирует цикл вызова инструментов. Вы определяете инструмент с типизированной схемой входных данных и функцией execute. SDK отправляет определение инструмента в Responses API, запускает вашу функцию, когда модель её вызывает, возвращает результат модели как function_call_output и предоставляет вам окончательный ответ.

Вы не создаёте элементы function_call и function_call_output вручную и не управляете последующими запросами. Ниже показан ручной протокол на случай, если вам нужен прямой контроль через HTTP.

typescript
import { OpenRouter } from '@openrouter/sdk'; import { callModel, tool } from '@openrouter/agent'; import { z } from 'zod'; const client = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY }); const weatherTool = tool({ name: 'get_weather', description: 'Get the current weather in a location', inputSchema: z.object({ location: z.string().describe('The city and state, e.g. San Francisco, CA'), unit: z.enum(['celsius', 'fahrenheit']).optional(), }), execute: async ({ location, unit }) => ({ location, temperature: unit === 'celsius' ? 22 : 72, unit: unit ?? 'fahrenheit', condition: 'sunny', }), }); const result = callModel(client, { model: 'openai/gpt-4o-mini', input: 'What is the weather like in San Francisco?', tools: [weatherTool] as const, }); // Tools are executed automatically; this is the model's final answer. console.log(await result.getText());
python
import asyncio import os from typing import Literal, Optional from pydantic import BaseModel, Field from openrouter_agent import OpenRouter, call_model, tool class WeatherInput(BaseModel): location: str = Field(description="The city and state, e.g. San Francisco, CA") unit: Optional[Literal["celsius", "fahrenheit"]] = None class WeatherOutput(BaseModel): location: str temperature: int unit: str condition: str def get_weather(params: WeatherInput, ctx) -> WeatherOutput: unit = params.unit or "fahrenheit" return WeatherOutput( location=params.location, temperature=22 if unit == "celsius" else 72, unit=unit, condition="sunny", ) async def main() -> None: client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"]) weather_tool = tool( name="get_weather", description="Get the current weather in a location", input_schema=WeatherInput, output_schema=WeatherOutput, execute=get_weather, ) result = call_model( client, { "model": "openai/gpt-4o", "input": "What is the weather like in San Francisco?", "tools": [weather_tool], }, ) # Tools are executed automatically; this is the model's final answer. print(await result.get_text()) asyncio.run(main())
text
The weather in San Francisco, CA, is currently 72°F and sunny.

Как работает вызов инструментов «под капотом»

Оставшаяся часть этой страницы демонстрирует построение цикла вручную с помощью сырых запросов к Responses API: определение инструментов, чтение элементов function_call и отправка элементов function_call_output обратно модели.

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

Определяйте инструменты, используя формат вызова функций 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 ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: [ { type: 'message', role: 'user' as const, content: [ { type: 'input_text', text: 'What is the weather in San Francisco?', }, ], }, ], tools: [weatherTool] as const, tool_choice: 'auto', max_output_tokens: 9000, }), }); const result = await response.json(); console.log(JSON.stringify(result, null, 2));
python
import os import json 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': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-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(json.dumps(result, indent=2))
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-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 }'
go
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { weatherTool := map[string]any{ "type": "function", "name": "get_weather", "description": "Get the current weather in a location", "strict": nil, "parameters": map[string]any{ "type": "object", "properties": map[string]any{ "location": map[string]any{ "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": map[string]any{ "type": "string", "enum": []string{"celsius", "fahrenheit"}, }, }, "required": []string{"location"}, }, } body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "What is the weather in San Francisco?"}, }, }, }, "tools": []any{weatherTool}, "tool_choice": "auto", "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out bytes.Buffer if err := json.Indent(&out, data, "", " "); err != nil { fmt.Println(string(data)) return } fmt.Println(out.String()) }
text
{ "id": "gen-1794947626-wfrC8WVOyUdKsBEDqJYy", "object": "response", "created_at": 1794947626, "model": "openai/gpt-4o-mini", "status": "completed", "completed_at": 1794947627, "output": [ { "id": "fc_tmp_obdhb66hlx", "type": "function_call", "status": "completed", "call_id": "call_gtKR0Mt9UXdJJQmARAwfQVCg", "name": "get_weather", "arguments": "{\"location\":\"San Francisco, CA\"}" } ], "error": null, "incomplete_details": null, "access_programs": null, "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" ] }

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

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

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

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

typescript
const response = await fetch('https://openrouter.ai/api/v1/responses', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-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, }), }); const result = await response.json(); console.log(JSON.stringify(result, null, 2));
python
import json import os import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-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, } ) result = response.json() print(json.dumps(result, indent=2))
go
body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "Hello, how are you?"}, }, }, }, "tools": []any{weatherTool}, "tool_choice": map[string]any{"type": "function", "name": "get_weather"}, "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out bytes.Buffer if err := json.Indent(&out, data, "", " "); err != nil { fmt.Println(string(data)) return } fmt.Println(out.String())
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "input": [ { "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "Hello, how are you?" } ] } ], "tools": [ { "type": "function", "name": "get_weather", "description": "Get the current weather in a location", "parameters": { "type": "object", "properties": { "location": { "type": "string" } }, "required": ["location"] } } ], "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 ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: [ { type: 'message', role: 'user' as const, content: [ { type: 'input_text', text: 'What is the weather in Paris?', }, ], }, ], tools: [weatherTool] as const, tool_choice: 'none', max_output_tokens: 9000, }), });
python
import json import os import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-mini', 'input': [ { 'type': 'message', 'role': 'user', 'content': [ { 'type': 'input_text', 'text': 'What is the weather in Paris?', }, ], }, ], 'tools': [weather_tool], 'tool_choice': 'none', 'max_output_tokens': 9000, } ) result = response.json() print(json.dumps(result, indent=2))
go
body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "What is the weather in Paris?"}, }, }, }, "tools": []any{weatherTool}, "tool_choice": "none", "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close()
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "input": [ { "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "What is the weather in Paris?" } ] } ], "tools": [ { "type": "function", "name": "get_weather", "description": "Get the current weather in a location", "parameters": { "type": "object", "properties": { "location": { "type": "string" } }, "required": ["location"] } } ], "tool_choice": "none", "max_output_tokens": 9000 }'

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

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

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 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 ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: [ { type: 'message', role: 'user' as const, content: [ { type: 'input_text', text: 'What is 25 * 4?', }, ], }, ], tools: [weatherTool, calculatorTool], tool_choice: 'auto', max_output_tokens: 9000, }), }); const result = await response.json(); console.log(JSON.stringify(result, null, 2));
python
import json import os 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'], }, } 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': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-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, } ) result = response.json() print(json.dumps(result, indent=2))
go
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { weatherTool := map[string]any{ "type": "function", "name": "get_weather", "description": "Get the current weather in a location", "strict": nil, "parameters": map[string]any{ "type": "object", "properties": map[string]any{ "location": map[string]any{ "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": map[string]any{ "type": "string", "enum": []string{"celsius", "fahrenheit"}, }, }, "required": []string{"location"}, }, } calculatorTool := map[string]any{ "type": "function", "name": "calculate", "description": "Perform mathematical calculations", "strict": nil, "parameters": map[string]any{ "type": "object", "properties": map[string]any{ "expression": map[string]any{ "type": "string", "description": "The mathematical expression to evaluate", }, }, "required": []string{"expression"}, }, } body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "What is 25 * 4?"}, }, }, }, "tools": []any{weatherTool, calculatorTool}, "tool_choice": "auto", "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out bytes.Buffer if err := json.Indent(&out, data, "", " "); err != nil { fmt.Println(string(data)) return } fmt.Println(out.String()) }
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "input": [ { "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "What is 25 * 4?" } ] } ], "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"] } }, { "type": "function", "name": "calculate", "description": "Perform mathematical calculations", "strict": null, "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "The mathematical expression to evaluate" } }, "required": ["expression"] } } ], "tool_choice": "auto", "max_output_tokens": 9000 }'
text
{ "id": "gen-1794947916-JqitACgZxVM6a051leDL", "object": "response", "created_at": 1794947916, "model": "openai/gpt-4o-mini", "status": "completed", "completed_at": 1794947916, "output": [ { "id": "fc_tmp_84h9i390srq", "type": "function_call", "status": "completed", "call_id": "call_njcjjHkGCOfs99rVDKYW3Xs9", "name": "calculate", "arguments": "{\"expression\":\"25 * 4\"}" } ], "error": null, "incomplete_details": null, "access_programs": null, "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" ] }

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

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

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 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 ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: [ { type: 'message', role: 'user' as const, 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(JSON.stringify(result, null, 2));
python
import os import json 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'], }, } 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': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-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(json.dumps(result, indent=2))
go
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { weatherTool := map[string]any{ "type": "function", "name": "get_weather", "description": "Get the current weather in a location", "strict": nil, "parameters": map[string]any{ "type": "object", "properties": map[string]any{ "location": map[string]any{ "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": map[string]any{ "type": "string", "enum": []string{"celsius", "fahrenheit"}, }, }, "required": []string{"location"}, }, } calculatorTool := map[string]any{ "type": "function", "name": "calculate", "description": "Perform mathematical calculations", "strict": nil, "parameters": map[string]any{ "type": "object", "properties": map[string]any{ "expression": map[string]any{ "type": "string", "description": "The mathematical expression to evaluate", }, }, "required": []string{"expression"}, }, } body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "Calculate 10*5 and also tell me the weather in Miami"}, }, }, }, "tools": []any{weatherTool, calculatorTool}, "tool_choice": "auto", "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out bytes.Buffer if err := json.Indent(&out, data, "", " "); err != nil { fmt.Println(string(data)) return } fmt.Println(out.String()) }
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "input": [ { "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "Calculate 10*5 and also tell me the weather in Miami" } ] } ], "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"] } }, { "type": "function", "name": "calculate", "description": "Perform mathematical calculations", "strict": null, "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "The mathematical expression to evaluate" } }, "required": ["expression"] } } ], "tool_choice": "auto", "max_output_tokens": 9000 }'
text
{ "id": "gen-1794948028-pOJsgjWbBhVMri9oSatO", "object": "response", "created_at": 1794948028, "model": "openai/gpt-4o-mini", "status": "completed", "completed_at": 1794948030, "output": [ { "id": "fc_tmp_4bzk69qn9xw", "type": "function_call", "status": "completed", "call_id": "call_ls7QxqPyMXCm0EGZyUTsvqpd", "name": "calculate", "arguments": "{\"expression\": \"10*5\"}" }, { "id": "fc_tmp_wv729ikcrq", "type": "function_call", "status": "completed", "call_id": "call_tyhKhpubo7N6m4YVBvg0g8Kg", "name": "get_weather", "arguments": "{\"location\": \"Miami, FL\"}" } ], "error": null, "incomplete_details": null, "access_programs": null, "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"

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

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

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 ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: [ { type: 'message', role: 'user' as const, 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' as const, content: [ { type: 'input_text', text: 'Is that good weather for a picnic?', }, ], }, ], max_output_tokens: 9000, }), }); const result = await response.json(); console.log(JSON.stringify(result, null, 2));
python
import os import json import requests response = requests.post( 'https://openrouter.ai/api/v1/responses', headers={ 'Authorization': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-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, } ) result = response.json() print(json.dumps(result, indent=2))
go
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "What is the weather in Boston?"}, }, }, map[string]any{ "type": "function_call", "id": "fc_1", "call_id": "call_123", "name": "get_weather", "arguments": `{"location":"Boston, MA"}`, }, map[string]any{ "type": "function_call_output", "id": "fc_output_1", "call_id": "call_123", "output": `{"temperature":"72°F","condition":"Sunny"}`, }, map[string]any{ "type": "message", "role": "assistant", "id": "msg_abc123", "status": "completed", "content": []any{ map[string]any{ "type": "output_text", "text": "The weather in Boston is currently 72°F and sunny. This looks like perfect weather for a picnic!", "annotations": []any{}, }, }, }, map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "Is that good weather for a picnic?"}, }, }, }, "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() data, _ := io.ReadAll(resp.Body) var out bytes.Buffer if err := json.Indent(&out, data, "", " "); err != nil { fmt.Println(string(data)) return } fmt.Println(out.String()) }
bash
curl -X POST https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-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 }'
text
{ "id": "gen-1794948128-fwzhtqjBeTidFyD55QW5", "object": "response", "created_at": 1794948128, "model": "openai/gpt-4o-mini", "status": "completed", "completed_at": 1794948130, "output": [ { "id": "msg_tmp_opeouv3gaa", "type": "message", "role": "assistant", "status": "completed", "content": [ { "type": "output_text", "text": "Yes, 72°F and sunny is typically considered great weather for a picnic! It's warm but not too hot, and the sunshine makes for a pleasant outdoor experience. Just be sure to bring some sunscreen and stay hydrated!", "annotations": [], "logprobs": [] } ] } ], "error": null, "incomplete_details": null, "access_programs": null, "tools": [], "tool_choice": "auto", "parallel_tool_calls": true, "max_output_tokens": 9000, "temperature": 1, "top_p": 1, "presence_penalty": 0, "frequency_penalty": 0, "top_logprobs": 0, "max_tool_calls": null, "metadata": {}, "background": false, "previous_response_id": null, "service_tier": "default",

[!NOTE]

Optional Field

The id field is optional for function_call_output objects. Only type, call_id, and output are required — call_id is what pairs the output with its originating function_call. The examples above include id for completeness, but you can safely omit it.

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

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 weatherTool = { type: 'function' as const, name: 'get_weather', description: 'Get the current weather in a given 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 ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o-mini', input: [ { type: 'message', role: 'user' as const, content: [ { type: 'input_text', text: 'What is the weather like in Tokyo, Japan? Please check the weather.', }, ], }, ], tools: [weatherTool] as const, tool_choice: 'auto', stream: true, max_output_tokens: 9000, }), }); const reader = response.body!.getReader(); const decoder = new TextDecoder(); let buffer = ''; stream: while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() ?? ''; for (const line of lines) { if (line.startsWith('data: ')) { const data = line.slice(6); if (data === '[DONE]') break stream; 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); } if (parsed.type === 'response.output_text.delta') { process.stdout.write(parsed.delta); } if (parsed.type === 'response.completed') { console.log('\nResponse completed with status:', parsed.response?.status); } } catch (e) { // Skip invalid JSON } } } }
python
import os import requests import json weather_tool = { 'type': 'function', 'name': 'get_weather', 'description': 'Get the current weather in a given 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': f'Bearer {os.environ["OPENROUTER_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'model': 'openai/gpt-4o-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(decode_unicode=True): if line: line_str = line if isinstance(line, str) else 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', '')}") if parsed.get('type') == 'response.output_text.delta': print(parsed.get('delta', ''), end='', flush=True) if parsed.get('type') == 'response.completed': print(f"\nResponse completed with status: {parsed.get('response', {}).get('status')}") except json.JSONDecodeError: continue
go
package main import ( "bufio" "bytes" "encoding/json" "fmt" "net/http" "os" "strings" ) func main() { weatherTool := map[string]any{ "type": "function", "name": "get_weather", "description": "Get the current weather in a given location", "strict": nil, "parameters": map[string]any{ "type": "object", "properties": map[string]any{ "location": map[string]any{ "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": map[string]any{ "type": "string", "enum": []string{"celsius", "fahrenheit"}, }, }, "required": []string{"location"}, }, } body, _ := json.Marshal(map[string]any{ "model": "openai/gpt-4o-mini", "input": []any{ map[string]any{ "type": "message", "role": "user", "content": []any{ map[string]any{"type": "input_text", "text": "What is the weather like in Tokyo, Japan? Please check the weather."}, }, }, }, "tools": []any{weatherTool}, "tool_choice": "auto", "stream": true, "max_output_tokens": 9000, }) req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() scanner := bufio.NewScanner(resp.Body) scanner.Buffer(make([]byte, 1024*1024), 1024*1024) for scanner.Scan() { line := scanner.Text() if !strings.HasPrefix(line, "data: ") { continue } data := strings.TrimPrefix(line, "data: ") if data == "[DONE]" { break } var parsed struct { Type string `json:"type"` Delta string `json:"delta"` Arguments string `json:"arguments"` Item *struct { Type string `json:"type"` Name string `json:"name"` } `json:"item"` Response *struct { Status string `json:"status"` } `json:"response"` } if err := json.Unmarshal([]byte(data), &parsed); err != nil { continue // Skip invalid JSON } switch parsed.Type { case "response.output_item.added": if parsed.Item != nil && parsed.Item.Type == "function_call" { fmt.Println("Function call:", parsed.Item.Name) } case "response.function_call_arguments.done": fmt.Println("Arguments:", parsed.Arguments) case "response.output_text.delta": fmt.Print(parsed.Delta) case "response.completed": status := "" if parsed.Response != nil { status = parsed.Response.Status } fmt.Println("\nResponse completed with status:", status) } } }
bash
curl -sN https://openrouter.ai/api/v1/responses \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-4o-mini", "input": [ { "type": "message", "role": "user", "content": [ { "type": "input_text", "text": "What is the weather like in Tokyo, Japan? Please check the weather." } ] } ], "tools": [ { "type": "function", "name": "get_weather", "description": "Get the current weather in a given 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", "stream": true, "max_output_tokens": 9000 }' | sed -n 's/^data: //p' | jq -rjR --unbuffered 'fromjson? | if .type == "response.output_item.added" and .item.type == "function_call" then "Function call: \(.item.name)\n" elif .type == "response.function_call_arguments.done" then "Arguments: \(.arguments)\n" elif .type == "response.output_text.delta" then .delta elif .type == "response.completed" then "\nResponse completed with status: \(.response.status)\n" else empty end'
text
Function call: get_weather Arguments: {"location":"Tokyo, Japan"} Response completed with status: completed

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

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

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

[!NOTE]
Опциональное поле
Поле id является необязательным для объектов function_call_output. Требуются только type, call_id и output — call_id связывает вывод с соответствующим function_call. Примеры выше включают id для полноты, но вы можете безопасно опустить его.