Извикване на функции
Опишете функциите си в заявката и моделът отговаря с извикванията, които иска да бъдат направени. Вашият код ги изпълнява и връща резултатите: 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 | Вие | Добавете съобщението на асистента и по едно съобщение tool за всяко извикване към messages, после изпратете заявката отново със същите 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 или именувана функция прочетете finish_reason, преди да прочетете tool_calls. Когато моделът не произведе извикване, отговорът е текстов с 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 извикването пристига на едно цяло: chunk-ът съдържа пълния низ 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]. Последният chunk има 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, доставя текста на отговора в една delta на 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". |
Моделът пише аргументите. Проверете ги спрямо вашата схема, преди да изпълните функцията, както бихте проверили всеки външен вход.
Грешките при удостоверяване, баланс и сървър са същите като при всяка заявка. Обработка на грешки