Вызов инструментов
Полный цикл вызова функции: описание инструмента, получение аргументов, выполнение и передача результата модели.
1. Опишите функцию
Модель выбирает функцию и формирует аргументы. Выполняет её ваше приложение. Ниже функция получения статуса заказа; для реальной системы проверяйте права пользователя и аргументы до выполнения.
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Статус заказа по номеру",
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string"
}
},
"required": [
"order_id"
],
"additionalProperties": false
},
"strict": true
}
}Это форма Chat Completions. В Responses поля name, description, parameters и strict находятся рядом с type, без вложенного function.
2. Полный цикл Chat Completions
import OpenAI from 'openai';
const client = new OpenAI({ apiKey: process.env.ORLIME_API_KEY, baseURL: 'https://gateway.orlime.ru/v1' });
const messages = [{ role: 'user', content: 'Где заказ A-123?' }];
const tools = [{ type: 'function', function: {
name: 'get_order_status',
parameters: { type: 'object', properties: { order_id: { type: 'string' } }, required: ['order_id'] }
} }];
const first = await client.chat.completions.create({
model: 'openai/gpt-6.1-sol', messages, tools, tool_choice: 'required'
});
messages.push(first.choices[0].message);
for (const call of first.choices[0].message.tool_calls ?? []) {
if (call.type !== 'function' || call.function.name !== 'get_order_status') throw new Error('Неизвестная функция');
const args = JSON.parse(call.function.arguments);
// Проверьте args и доступ пользователя к заказу.
const result = { order_id: args.order_id, status: 'В пути' };
messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
}
const second = await client.chat.completions.create({
model: 'openai/gpt-6.1-sol', messages, tools, tool_choice: 'auto'
});
console.log(second.choices[0].message);3. Полный цикл Responses
const input = [{ role: 'user', content: 'Где заказ A-123?' }];
const tools = [{ type: 'function', name: 'get_order_status',
parameters: { type: 'object', properties: { order_id: { type: 'string' } }, required: ['order_id'] }
}];
const first = await client.responses.create({
model: 'openai/gpt-6.1-sol', input, tools, tool_choice: 'required',
include: ['reasoning.encrypted_content'], store: false
});
input.push(...first.output);
for (const call of first.output) {
if (call.type !== 'function_call') continue;
if (call.name !== 'get_order_status') throw new Error('Неизвестная функция');
const args = JSON.parse(call.arguments);
// Выполните разрешённую функцию с проверенными аргументами.
input.push({ type: 'function_call_output', call_id: call.call_id,
output: JSON.stringify({ order_id: args.order_id, status: 'В пути' }) });
}
const second = await client.responses.create({
model: 'openai/gpt-6.1-sol', input, tools, store: false
});
console.log(second.output);Следующий ответ может снова вызвать функцию. В приложении задайте предел числа шагов. Сохраняйте все элементы output, включая reasoning; call_id связывает вызов с результатом и должен передаваться без изменений.
