Повик на функции
Опишете ги вашите функции во барањето и моделот одговара со повиците што сака да се направат. Вашиот код ги извршува и ги испраќа резултатите назад: 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 | Вие | Додајте ја пораката на assistant и по една tool порака за секој повик во messages, па повторно испратете го барањето со истите tools. |
| 5 | Модел | Моделот одговара со текст и finish_reason: "stop", или бара уште повици. Во тој случај вратете се на чекор 3. |
Едно барање е еден чекор на моделот. API-то не чува разговор меѓу барањата и не поставува број на кругови: вашиот код ги чува messages и одлучува кога да запре.
Дефинирање алатки
tools е низа со еден запис по функција. Го прифаќа секој модел од каталогот; GET /v1/models пријавува capabilities.tools: true за секој ид.
| Поле | Тип | Опис |
|---|---|---|
type | string | Секогаш function. |
function.name | string | Името што го користи моделот кога ја бара оваа функција. Задолжително. |
function.description | string | Што прави функцијата, со обични зборови. |
function.parameters | object | Аргументите како JSON Schema со type: "object" на врвот. Видете Клучни зборови на schema подолу. |
Секој ендпоинт има свој запис на алатка. Испратете го оној што му припаѓа на ендпоинтот што го повикувате:
{
"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 го испорачува текстот на одговорот во една content delta на крајот на чекорот. Стриминг
Враќање на резултатите
Второто барање го повторува разговорот и додава две работи: чекорот на assistant што ги побарал повиците и по еден резултат за секој повик.
{
"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\"}"
}
]
}
]
} - Испратете го чекорот на assistant назад онака како што го добивте, пред резултатите. Секој резултат се поврзува со својот повик преку ид:
tool_call_idна/v1/chat/completions,call_idна/v1/responses,tool_use_idна/v1/messages. - Резултатот е текст. Серијализирајте го објектот во JSON стринг за
content(outputна/v1/responses). На/v1/messages,contentна блокотtool_resultе стринг или листа од текстуални блокови. - Во чекорот на assistant,
function.argumentsостанува JSON стринг, точно како што пристигнал. - Разговорот може да заврши со резултат од алатка. Не е потребна нова порака од корисникот: моделот продолжува од резултатот.
- Кога вашата функција не успее, испратете ја грешката како текст на резултатот. Моделот потоа може да ја пријави или да побара друг повик.
Клучни зборови на schema
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, на секое ниво на schema. |
format | Се чита за вредностите int32, int64, float, double, byte, date, date-time и enum. |
oneOf | Се чита како anyOf. |
| Не е дел од schema што ја добиваат овие модели | $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за да поставите друга вредност. - Секој круг е посебно барање: се наплатува од вашето салдо и се брои во flood protection како секое друго барање. Ограничувања и салдо
Грешки
Повикот на алатка е нормален одговор со статус 200. Овие грешки се однесуваат на самото барање:
| Статус | Тип | Порака | Кога |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model не е ид од објавената листа. |
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". |
Аргументите ги пишува моделот. Проверете ги според вашата schema пред да ја извршите функцијата, како што би провериле секој надворешен влез.
Грешките при автентикација, салдо и сервер се исти како за секое барање. Ракување со грешки