Виклик функцій
Опишіть свої функції в запиті, і модель відповість викликами, які хоче зробити. Ваш код виконує їх і надсилає результати назад: API повертає виклики інструментів і сам інструмент не виконує.
POST https://api.shannon-ai.com/v1/chat/completions
Приклади на цій сторінці використовують /v1/chat/completions. Той самий цикл працює на /v1/responses і /v1/messages; де формат пише щось інакше, розділи нижче показують усі три.
import json
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1")
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}]
def get_weather(city, unit="celsius"):
# Your code: ask a weather service here.
return {"city": city, "temperature": 18, "unit": unit, "conditions": "cloudy"}
messages = [{"role": "user", "content": "What is the weather in Paris right now?"}]
answer = None
for _ in range(5): # the API sets no limit on rounds: set your own
response = client.chat.completions.create(
model="Kimi-K3-3BIT-REAP",
messages=messages,
tools=tools,
)
choice = response.choices[0]
if choice.finish_reason != "tool_calls":
answer = choice.message.content
break
messages.append(choice.message) # the assistant turn with its tool_calls
for call in choice.message.tool_calls:
args = json.loads(call.function.arguments) # arguments is a JSON string
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
print(answer) import OpenAI from "openai";
const client = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.shannon-ai.com/v1" });
const tools = [{
type: "function",
function: {
name: "get_weather",
description: "Get the current weather for a city.",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "City name, for example Paris" },
unit: { type: "string", enum: ["celsius", "fahrenheit"] },
},
required: ["city"],
},
},
}];
// Your code: ask a weather service here.
function getWeather({ city, unit = "celsius" }) {
return { city, temperature: 18, unit, conditions: "cloudy" };
}
const messages = [{ role: "user", content: "What is the weather in Paris right now?" }];
let answer = null;
// The API sets no limit on rounds: set your own.
for (let round = 0; round < 5; round++) {
const response = await client.chat.completions.create({
model: "Kimi-K3-3BIT-REAP",
messages,
tools,
});
const choice = response.choices[0];
if (choice.finish_reason !== "tool_calls") {
answer = choice.message.content;
break;
}
messages.push(choice.message); // the assistant turn with its tool_calls
for (const call of choice.message.tool_calls) {
const args = JSON.parse(call.function.arguments); // arguments is a JSON string
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(getWeather(args)),
});
}
}
console.log(answer); # 1. Send the conversation with the tools.
curl https://api.shannon-ai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "Kimi-K3-3BIT-REAP",
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}]
}'
# 2. Run the function yourself, then send the assistant turn and the result.
# Use the id of the call you received.
curl https://api.shannon-ai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "Kimi-K3-3BIT-REAP",
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{"role": "assistant", "content": null, "tool_calls": [{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}
}]},
{"role": "tool", "tool_call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}]
}' Перша відповідь не відповідає на запитання. Вона просить виклик:
{
"id": "chatcmpl-5b0c1d8e7f6a4b3c9d2e1f0a8b7c6d5e",
"object": "chat.completion",
"created": 1791590400,
"model": "Kimi-K3-3BIT-REAP",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"reasoning_content": "The user asks for the current weather in Paris. I should call get_weather.",
"tool_calls": [
{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 312,
"completion_tokens": 58,
"total_tokens": 370,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 31}
}
} Після надсилання результату наступна відповідь — звичайна: message.content містить текст, а finish_reason дорівнює stop.
Цикл крок за кроком
| Крок | Хто | Що відбувається |
|---|---|---|
| 1 | Ви | Надішліть messages разом із tools — списком функцій, які може попросити модель. |
| 2 | Модель | Відповідь містить tool_calls і finish_reason: "tool_calls". Кожен виклик називає функцію та дає її аргументи. |
| 3 | Ви | Розберіть arguments кожного виклику та виконайте свою функцію. |
| 4 | Ви | Додайте до messages повідомлення асистента та по одному повідомленню tool на кожен виклик, потім надішліть запит знову з тими самими tools. |
| 5 | Модель | Модель відповідає текстом із finish_reason: "stop" або просить ще виклики. У такому разі поверніться до кроку 3. |
Один запит — це один хід моделі. API не зберігає розмови між запитами й не встановлює кількості раундів: messages тримає ваш код і вирішує, коли зупинитися.
Визначення інструментів
tools — це масив з одним записом на функцію. Його приймає кожна модель каталогу; GET /v1/models повідомляє capabilities.tools: true для кожного id.
| Поле | Тип | Опис |
|---|---|---|
type | string | Завжди function. |
function.name | string | Назва, яку модель використовує, коли просить цю функцію. Обов'язкове. |
function.description | string | Що робить функція, простою мовою. |
function.parameters | object | Аргументи як JSON Schema з type: "object" на верхньому рівні. Див. нижче Ключові слова схеми. |
Кожен ендпоінт має власний запис інструмента. Надсилайте той, що належить ендпоінту, який ви викликаєте:
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example Paris"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
} {
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example Paris"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
} {
"name": "get_weather",
"description": "Get the current weather for a city.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example Paris"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
} tool_choice
tool_choice вказує, чи може модель, або чи повинна, викликати інструмент. Він читається лише разом із tools.
| Значення | Опис | Застосовують |
|---|---|---|
"auto" | Модель сама вирішує, відповісти текстом чи викликати інструмент. Це значення за замовчуванням. | Усі моделі |
"required" | Відповідь викликає принаймні один інструмент. | Хостовані open-weight моделі |
{"type": "function", "function": {"name": "get_weather"}} | Відповідь викликає цю функцію. Назва має бути однією з функцій у tools. Виклики інших функцій у відповідь не потрапляють. | Хостовані open-weight моделі |
Моделі Shannon (shannon-*) вирішують у кожному запиті самі, як з auto.
З required або названою функцією перед tool_calls прочитайте finish_reason. Якщо модель не сформувала виклику, відповідь — це текст із finish_reason: "stop".
| Значення | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Модель вирішує сама | "auto" | "auto" | {"type": "auto"} |
| Викликати принаймні один інструмент | "required" | "required" | {"type": "any"} |
| Викликати одну названу функцію | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Приймаються для сумісності: tool_choice: "none" і parallel_tool_calls. Для ходу без викликів інструментів надішліть запит без tools.
Виклики інструментів у відповіді
| Поле | Тип | Опис |
|---|---|---|
finish_reason | string | tool_calls, коли відповідь містить принаймні один виклик. |
message.tool_calls | array | Один запис на виклик. Поле є лише тоді, коли модель попросила виклик. |
tool_calls[].id | string | call_, за яким ідуть 32 шістнадцяткові символи. Надішліть його назад як tool_call_id разом з результатом. |
tool_calls[].type | string | Завжди function. |
tool_calls[].function.name | string | Функція, яку потрібно виконати. |
tool_calls[].function.arguments | string | Аргументи як рядок JSON, "{}", якщо їх немає. Розберіть його перед використанням. |
message.content | string | null | null, коли відповідь містить лише виклики. Хостовані open-weight моделі можуть повертати текст поряд із викликами; моделі Shannon повертають null. |
Той самий виклик у кожному форматі. На /v1/responses це елемент function_call у output, з arguments як рядком JSON. На /v1/messages це блок вмісту tool_use, чий input є JSON-об'єктом, його id починається з toolu_, а stop_reason дорівнює tool_use.
{
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
}
} {
"output": [
{
"id": "fc_3d2c1b0a9f8e4d7c6b5a4f3e2d1c0b9a",
"type": "function_call",
"call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}",
"status": "completed"
}
]
} {
"stop_reason": "tool_use",
"content": [
{
"type": "tool_use",
"id": "toolu_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"input": {"city": "Paris"}
}
]
} Кілька викликів в одному ході
Відповідь може містити кілька викликів. Виконайте кожен із них і надішліть по одному результату на виклик, кожен зі своїм tool_call_id, у наступному запиті.
Хостовані open-weight моделі повертають кожен різний виклик один раз: два виклики з однаковою назвою та однаковими аргументами надходять як один.
Виклики інструментів у стрімі
З stream: true виклик надходить цілим: фрагмент містить повний рядок arguments, тож склеювати частини не потрібно. index нумерує виклики ходу з 0.
{
"id": "chatcmpl-5b0c1d8e7f6a4b3c9d2e1f0a8b7c6d5e",
"object": "chat.completion.chunk",
"created": 1791590400,
"model": "Kimi-K3-3BIT-REAP",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"index": 0,
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
"finish_reason": null
}
]
} | Ендпоінт | Що надходить |
|---|---|
/v1/chat/completions | Один chat.completion.chunk на виклик, із викликом у delta.tool_calls[0]. Останній фрагмент має finish_reason: "tool_calls" і usage. |
/v1/responses | На виклик: response.output_item.added (елемент function_call з порожніми arguments), response.function_call_arguments.delta (весь рядок), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | На виклик: content_block_start (блок tool_use з порожнім input), одна content_block_delta, чий input_json_delta.partial_json — це весь текст аргументів, content_block_stop. Потім message_delta містить stop_reason: "tool_use". |
На shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro і shannon-coder-1 запит зі стрімінгом, що містить tools, доставляє текст відповіді в одній дельті content наприкінці ходу. Стримінг
Надсилання результатів назад
Другий запит повторює розмову та додає дві речі: хід асистента, що просив виклики, і по одному результату на виклик.
{
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
}
]
} {
"input": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{
"type": "function_call",
"call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
},
{
"type": "function_call_output",
"call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"output": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
}
]
} {
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{
"role": "assistant",
"content": [
{
"type": "tool_use",
"id": "toolu_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"input": {"city": "Paris"}
}
]
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
}
]
}
]
} - Надішліть хід асистента назад таким, яким ви його отримали, перед результатами. Кожен результат зіставляється зі своїм викликом за id:
tool_call_idна/v1/chat/completions,call_idна/v1/responses,tool_use_idна/v1/messages. - Результат — це текст. Серіалізуйте об'єкт у рядок JSON для
content(outputна/v1/responses). На/v1/messagescontentблокуtool_result— це рядок або список текстових блоків. - У ході асистента
function.argumentsзалишається рядком JSON, точно таким, як надійшов. - Розмова може закінчуватися результатом інструмента. Нове повідомлення користувача не потрібне: модель продовжує з результату.
- Коли ваша функція завершується помилкою, надішліть помилку як текст результату. Модель тоді може повідомити про неї або попросити інший виклик.
Ключові слова схеми
parameters (input_schema на /v1/messages) — це JSON Schema. Сімейство Shannon 3 (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) і хостовані open-weight моделі отримують її такою, як ви її надсилаєте.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro і shannon-coder-1 отримують цю підмножину, на всіх трьох ендпоінтах:
| Обробка | Ключові слова |
|---|---|
| Читається як надіслано | Кожне ключове слово, не назване в рядках нижче, наприклад type, properties, required, items, enum, description, minimum, maximum, anyOf і allOf, на кожному рівні схеми. |
format | Читається для значень int32, int64, float, double, byte, date, date-time і enum. |
oneOf | Читається як anyOf. |
| Не входить у схему, яку отримують ці моделі | $schema, $id, $ref, $defs, $comment, definitions, additionalProperties, unevaluatedProperties, patternProperties, propertyNames, examples, default, title, const, not, if, then, else, contains, minContains, maxContains, dependentRequired, dependentSchemas, dependencies, readOnly, writeOnly, deprecated, contentEncoding, contentMediaType, contentSchema, multipleOf, uniqueItems; exclusiveMinimum і exclusiveMaximum, коли вони є числами; інші значення format. |
Поведінка та ліміти
- API не встановлює максимальної кількості інструментів і максимальної кількості раундів.
- Тіло запиту може бути до 32 MiB, а розмова з результатами має вміщатися у вікно контексту моделі.
- Коли запит містить
tools,shannon-1.6-lite,shannon-1.6-pro,shannon-2-liteіshannon-2-proвикористовуютьtemperatureза замовчуванням 0.2. Надішлітьtemperature, щоб задати інше значення. - Кожен раунд — це окремий запит: він списує з вашого балансу та враховується захистом від флуду, як і будь-який інший запит. Ліміти та баланс
Помилки
Виклик інструмента — це звичайна відповідь зі статусом 200. Ці помилки стосуються самого запиту:
| Статус | Тип | Повідомлення | Коли |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model не є id з опублікованого списку. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools не є масивом, або інше поле має неправильний тип JSON. |
413 | invalid_request_error | Failed to buffer the request body: … | Тіло запиту більше за 32 MiB. Помилка містить code: "request_too_large". |
Аргументи пише модель. Перевіряйте їх за своєю схемою перед виконанням функції, як перевіряли б будь-який зовнішній вхід.
Помилки автентифікації, балансу та сервера такі самі, як для кожного запиту. Обробка помилок