Volanie funkcií
Popíšte svoje funkcie v requeste a model odpovie volaniami, ktoré chce vykonať. Váš kód ich spustí a pošle výsledky späť: API vracia volania nástrojov a samo žiadny nástroj nespúšťa.
POST https://api.shannon-ai.com/v1/chat/completions
Ukážky na tejto stránke používajú /v1/chat/completions. Rovnaká slučka beží na /v1/responses a /v1/messages; kde formát niečo píše inak, nižšie uvedené sekcie ukazujú všetky tri.
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"]
}
}
}]
}' Prvá odpoveď na otázku neodpovedá. Žiada o volanie:
{
"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}
}
} Po odoslaní výsledku je ďalšia odpoveď bežná odpoveď: message.content obsahuje text a finish_reason je stop.
Slučka krok za krokom
| Krok | Kto | Čo sa stane |
|---|---|---|
| 1 | Vy | Pošlite messages spolu s tools, zoznamom funkcií, o ktoré môže model požiadať. |
| 2 | Model | Odpoveď nesie tool_calls a finish_reason: "tool_calls". Každé volanie uvádza funkciu a jej argumenty. |
| 3 | Vy | Spracujte (parse) arguments každého volania a spustite svoju funkciu. |
| 4 | Vy | Do messages pripojte správu asistenta a jednu správu tool na volanie a potom pošlite request znova s rovnakými tools. |
| 5 | Model | Model odpovie textom s finish_reason: "stop" alebo požiada o ďalšie volania. V takom prípade sa vráťte na krok 3. |
Jeden request je jedno kolo modelu. API medzi requestmi neuchováva konverzáciu a nestanovuje počet kôl: messages drží váš kód a rozhoduje, kedy skončiť.
Definovanie nástrojov
tools je pole s jednou položkou na funkciu. Prijíma ho každý model katalógu; GET /v1/models hlási capabilities.tools: true pre každé id.
| Pole | Typ | Popis |
|---|---|---|
type | string | Vždy function. |
function.name | string | Názov, ktorý model použije, keď o túto funkciu žiada. Povinné. |
function.description | string | Čo funkcia robí, jednoduchým jazykom. |
function.parameters | object | Argumenty ako JSON Schema s type: "object" navrchu. Pozrite Kľúčové slová schémy nižšie. |
Každý endpoint má vlastný zápis nástroja. Pošlite ten, ktorý patrí endpointu, ktorý voláte:
{
"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 hovorí, či model môže, alebo musí zavolať nástroj. Číta sa iba spolu s tools.
| Hodnota | Popis | Uplatňuje |
|---|---|---|
"auto" | Model sám rozhodne, či odpovie textom, alebo zavolá nástroj. Toto je predvolené. | Všetky modely |
"required" | Odpoveď volá aspoň jeden nástroj. | Hostované open-weight modely |
{"type": "function", "function": {"name": "get_weather"}} | Odpoveď volá túto funkciu. Názov musí byť jednou z funkcií v tools. Volania iných funkcií sa z odpovede vynechajú. | Hostované open-weight modely |
Modely Shannon (shannon-*) rozhodujú v každom requeste samy, ako s auto.
S required alebo pomenovanou funkciou čítajte finish_reason skôr než tool_calls. Keď model nevytvorí žiadne volanie, odpoveď je textová s finish_reason: "stop".
| Význam | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Model rozhodne | "auto" | "auto" | {"type": "auto"} |
| Zavolať aspoň jeden nástroj | "required" | "required" | {"type": "any"} |
| Zavolať jednu pomenovanú funkciu | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Prijímané kvôli kompatibilite: tool_choice: "none" a parallel_tool_calls. Pre kolo bez volaní nástrojov pošlite request bez tools.
Volania nástrojov v odpovedi
| Pole | Typ | Popis |
|---|---|---|
finish_reason | string | tool_calls, keď odpoveď nesie aspoň jedno volanie. |
message.tool_calls | array | Jedna položka na volanie. Pole je prítomné iba vtedy, keď model požiadal o volanie. |
tool_calls[].id | string | call_ nasledované 32 hexadecimálnymi znakmi. Pošlite ho späť ako tool_call_id s výsledkom. |
tool_calls[].type | string | Vždy function. |
tool_calls[].function.name | string | Funkcia, ktorú treba spustiť. |
tool_calls[].function.arguments | string | Argumenty ako reťazec JSON, "{}", keď žiadne nie sú. Pred použitím ho spracujte (parse). |
message.content | string | null | null, keď odpoveď obsahuje iba volania. Hostované open-weight modely môžu popri volaniach vrátiť text; modely Shannon vracajú null. |
To isté volanie v každom formáte. Na /v1/responses je to položka function_call v output s arguments ako reťazcom JSON. Na /v1/messages je to blok obsahu tool_use, ktorého input je objekt JSON, jeho id začína toolu_ a stop_reason je 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"}
}
]
} Niekoľko volaní v jednom kole
Odpoveď môže niesť niekoľko volaní. Spustite každé z nich a v ďalšom requeste pošlite jeden výsledok na volanie, každý s vlastným tool_call_id.
Hostované open-weight modely vracajú každé odlišné volanie raz: dve volania s rovnakým názvom a rovnakými argumentmi prídu ako jedno.
Streamované volania nástrojov
S stream: true volanie príde naraz: chunk obsahuje kompletný reťazec arguments, takže nie sú žiadne fragmenty na spájanie. index počíta volania kola od 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
}
]
} | Endpoint | Čo príde |
|---|---|
/v1/chat/completions | Jeden chat.completion.chunk na volanie, s volaním v delta.tool_calls[0]. Posledný chunk má finish_reason: "tool_calls" a usage. |
/v1/responses | Na volanie: response.output_item.added (položka function_call s prázdnymi arguments), response.function_call_arguments.delta (celý reťazec), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Na volanie: content_block_start (blok tool_use s prázdnym input), jedna content_block_delta, ktorej input_json_delta.partial_json je celý text argumentov, content_block_stop. message_delta potom nesie stop_reason: "tool_use". |
Na shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro a shannon-coder-1 streamovaný request, ktorý nesie tools, doručí text odpovede v jednej delte content na konci kola. Streamovanie
Odosielanie výsledkov späť
Druhý request zopakuje konverzáciu a pridá dve veci: kolo asistenta, ktoré žiadalo o volania, a jeden výsledok na volanie.
{
"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\"}"
}
]
}
]
} - Kolo asistenta pošlite späť tak, ako ste ho dostali, pred výsledkami. Každý výsledok sa k svojmu volaniu priradí podľa id:
tool_call_idna/v1/chat/completions,call_idna/v1/responses,tool_use_idna/v1/messages. - Výsledok je text. Objekt serializujte na reťazec JSON pre
content(outputna/v1/responses). Na/v1/messagesjecontentblokutool_resultreťazec alebo zoznam textových blokov. - V kole asistenta zostáva
function.argumentsreťazcom JSON, presne tak, ako prišiel. - Konverzácia môže končiť výsledkom nástroja. Nová správa používateľa nie je potrebná: model pokračuje od výsledku.
- Keď vaša funkcia zlyhá, pošlite zlyhanie ako text výsledku. Model ho potom môže nahlásiť alebo požiadať o ďalšie volanie.
Kľúčové slová schémy
parameters (input_schema na /v1/messages) je JSON Schema. Rodina Shannon 3 (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) a hostované open-weight modely ju dostanú tak, ako ju pošlete.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro a shannon-coder-1 dostanú túto podmnožinu, na všetkých troch endpointoch:
| Zaobchádzanie | Kľúčové slová |
|---|---|
| Číta sa tak, ako bolo poslané | Každé kľúčové slovo, ktoré nie je uvedené v riadkoch nižšie, napríklad type, properties, required, items, enum, description, minimum, maximum, anyOf a allOf, na každej úrovni schémy. |
format | Číta sa pre hodnoty int32, int64, float, double, byte, date, date-time a enum. |
oneOf | Číta sa ako anyOf. |
| Nie je súčasťou schémy, ktorú tieto modely dostanú | $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 a exclusiveMaximum, keď sú to čísla; ostatné hodnoty format. |
Správanie a limity
- API nestanovuje maximálny počet nástrojov ani maximálny počet kôl.
- Telo requestu môže mať až 32 MiB a konverzácia s výsledkami sa musí zmestiť do kontextového okna modelu.
- Keď request nesie
tools,shannon-1.6-lite,shannon-1.6-pro,shannon-2-liteashannon-2-propoužívajú predvolenútemperature0.2. Inú hodnotu nastavíte poslanímtemperature. - Každé kolo je samostatný request: čerpá z vášho zostatku a počíta sa do ochrany pred zahltením ako každý iný request. Limity a zostatok
Chyby
Volanie nástroja je bežná odpoveď so stavom 200. Tieto chyby sa týkajú samotného requestu:
| Stav | Typ | Správa | Kedy |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model nie je id zo zverejneného zoznamu. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools nie je pole alebo iné pole má nesprávny typ JSON. |
413 | invalid_request_error | Failed to buffer the request body: … | Telo requestu je väčšie než 32 MiB. Chyba nesie code: "request_too_large". |
Argumenty píše model. Skontrolujte ich podľa svojej schémy skôr, než funkciu spustíte, tak ako by ste kontrolovali akýkoľvek vonkajší vstup.
Chyby overenia, zostatku a servera sú rovnaké ako pri každom requeste. Spracovanie chýb