Инструменты

Дайте модели вызывать функции вашего кода: описания, вызовы и результаты в обоих стилях API.

Опишите функции, которые умеет выполнять ваш код. Модель может ответить вызовом одной из них; вы выполняете её и отправляете результат в следующем запросе.

Chat Completions API

Задайте tools с JSON Schema параметров. tool_choice — auto (по умолчанию), none, required или конкретная функция.

request
{
  "model": "kd-balanced",
  "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
          "type": "object",
          "properties": {"city": {"type": "string"}},
          "required": ["city"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

Вызов приходит в message.tool_calls с finish_reason: "tool_calls". arguments — строка с JSON.

response
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {"id": "call_1", "type": "function",
           "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

Верните сообщение ассистента и по сообщению tool на каждый вызов:

next request
"messages": [
  {"role": "user", "content": "What is the weather in Paris?"},
  {"role": "assistant", "content": null, "tool_calls": [
    {"id": "call_1", "type": "function",
     "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}
  ]},
  {"role": "tool", "tool_call_id": "call_1", "content": "{\"temp_c\": 18, \"sky\": \"clear\"}"}
]

Messages API

Задайте tools с input_schema. tool_choice — {"type": "auto"}, {"type": "any"}, {"type": "none"} или {"type": "tool", "name": "..."}.

request
{
  "model": "kd-balanced",
  "max_tokens": 1024,
  "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
  "tools": [
    {
      "name": "get_weather",
      "description": "Current weather for a city",
      "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    }
  ],
  "tool_choice": {"type": "auto"}
}

Вызов приходит блоком tool_use с stop_reason: "tool_use":

response
{
  "role": "assistant",
  "content": [
    {"type": "tool_use", "id": "tool_1", "name": "get_weather", "input": {"city": "Paris"}}
  ],
  "stop_reason": "tool_use"
}

Верните реплику ассистента, затем реплику пользователя с блоком tool_result на каждый вызов:

next request
"messages": [
  {"role": "user", "content": "What is the weather in Paris?"},
  {"role": "assistant", "content": [
    {"type": "tool_use", "id": "tool_1", "name": "get_weather", "input": {"city": "Paris"}}
  ]},
  {"role": "user", "content": [
    {"type": "tool_result", "tool_use_id": "tool_1", "content": "18 C, clear"}
  ]}
]

Советы

  • Пишите короткие и точные описания: по ним модель выбирает инструмент.
  • Проверяйте аргументы перед выполнением: их пишет модель.
  • Модель может вызвать несколько инструментов в одном ответе. Ответьте на каждый вызов.
  • Описания инструментов считаются входными токенами. В длинных сессиях кэшируйте их (кэш промптов).