WorkAI

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

Обновлено

Вызов функций через WorkAI API: объявление tools, ответ с tool_calls, параллельные вызовы, сообщения role tool и tool_choice. Примеры на cURL, Python и TypeScript.

Модель может попросить вызвать функцию вашего приложения: вы описываете функции в tools, модель возвращает имя функции и аргументы, вы исполняете её у себя и отправляете результат следующим запросом. Сама модель код не исполняет.

Шаг 1. Объявить инструменты

Принимаются только инструменты {"type": "function"}, параметры функции описываются JSON Schema.

cURL

curl https://api.workai.su/v1/chat/completions \
  -H "Authorization: Bearer $WORKAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6.2-sol",
    "messages": [{"role": "user", "content": "Какая погода в Москве и в Казани?"}],
    "tools": [{"type": "function", "function": {
      "name": "get_weather",
      "description": "Текущая погода в городе",
      "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
    }}]
  }'

Python

import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.workai.su/v1", api_key=os.environ["WORKAI_API_KEY"])

tools = [{"type": "function", "function": {
    "name": "get_weather",
    "description": "Текущая погода в городе",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}}]
messages = [{"role": "user", "content": "Какая погода в Москве и в Казани?"}]
response = client.chat.completions.create(model="openai/gpt-6.2-sol", messages=messages, tools=tools)
message = response.choices[0].message

TypeScript

import OpenAI from 'openai'
const client = new OpenAI({ baseURL: 'https://api.workai.su/v1', apiKey: process.env.WORKAI_API_KEY })

const tools: OpenAI.Chat.ChatCompletionTool[] = [{ type: 'function', function: {
  name: 'get_weather',
  description: 'Текущая погода в городе',
  parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
} }]
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [{ role: 'user', content: 'Какая погода в Москве и в Казани?' }]
const response = await client.chat.completions.create({ model: 'openai/gpt-6.2-sol', messages, tools })
const message = response.choices[0].message

Шаг 2. Ответ с tool_calls

Вместо текста модель возвращает tool_calls и finish_reason: "tool_calls". За один ответ вызовов может быть несколько — здесь два параллельных, по одному на город. function.arguments — JSON-строка, её нужно разобрать.

"message": {"role": "assistant", "content": null, "tool_calls": [
  {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Москва\"}"}},
  {"id": "call_2", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Казань\"}"}}
]},
"finish_reason": "tool_calls"

Шаг 3. Вернуть результаты

Добавьте в историю сообщение модели с tool_calls, затем на каждый вызов — сообщение role: "tool" с тем же tool_call_id и результатом строкой в content. Отправьте запрос с теми же tools. Модель ответит текстом с finish_reason: "stop" или снова попросит инструмент — тогда повторите шаг.

Python

messages.append({"role": "assistant", "content": message.content, "tool_calls": [c.model_dump() for c in message.tool_calls]})
for call in message.tool_calls:
    args = json.loads(call.function.arguments)
    result = {"city": args["city"], "temp_c": 3}  # здесь ваша функция
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result, ensure_ascii=False)})
final = client.chat.completions.create(model="openai/gpt-6.2-sol", messages=messages, tools=tools)
print(final.choices[0].message.content)

TypeScript

messages.push({ role: 'assistant', content: message.content, tool_calls: message.tool_calls })
for (const call of message.tool_calls ?? []) {
  if (call.type !== 'function') continue
  const args = JSON.parse(call.function.arguments)
  const result = { city: args.city, temp_c: 3 } // здесь ваша функция
  messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) })
}
const final = await client.chat.completions.create({ model: 'openai/gpt-6.2-sol', messages, tools })
console.log(final.choices[0].message.content)

cURL — второй запрос с полной историей:

curl https://api.workai.su/v1/chat/completions \
  -H "Authorization: Bearer $WORKAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6.2-sol",
    "messages": [
      {"role": "user", "content": "Какая погода в Москве и в Казани?"},
      {"role": "assistant", "content": null, "tool_calls": [
        {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Москва\"}"}},
        {"id": "call_2", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Казань\"}"}}
      ]},
      {"role": "tool", "tool_call_id": "call_1", "content": "{\"city\":\"Москва\",\"temp_c\":3}"},
      {"role": "tool", "tool_call_id": "call_2", "content": "{\"city\":\"Казань\",\"temp_c\":1}"}
    ],
    "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}]
  }'

tool_choice и ограничения

"auto" (по умолчанию) — модель сама решает, звать инструмент или отвечать текстом; "none" — отвечает только текстом, даже если tools переданы. У моделей GPT по акционной цене принимаются только эти два значения: "required", выбор конкретной функции и parallel_tool_calls: false дают 400 unsupported_parameter.

Встроенные инструменты OpenAI (web_search, file_search и другие) и устаревшие functions и function_call — 400, см. Параметры запроса. В потоке (stream: true) аргументы вызова приходят частями в delta.tool_calls — склейте их по index до конца потока.

Что дальше