Volání funkcí
Popište své funkce v požadavku a model odpoví voláními, která chce provést. Váš kód je spustí a pošle výsledky zpět: API vrací volání nástrojů a žádný nástroj samo nespouští.
POST https://api.shannon-ai.com/v1/chat/completions
Ukázky na této stránce používají /v1/chat/completions. Stejná smyčka běží na /v1/responses a /v1/messages; kde formát něco zapisuje jinak, ukazují níže uvedené části všechny tři.
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"]
}
}
}]
}' První odpověď na otázku neodpovídá. Žádá o volání:
{
"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 odeslání výsledku je další odpověď běžná odpověď: message.content obsahuje text a finish_reason je stop.
Smyčka krok za krokem
| Krok | Kdo | Co se stane |
|---|---|---|
| 1 | Vy | Pošlete messages spolu s tools, seznamem funkcí, o které smí model požádat. |
| 2 | Model | Odpověď nese tool_calls a finish_reason: "tool_calls". Každé volání pojmenuje funkci a uvede její argumenty. |
| 3 | Vy | Zpracujte arguments každého volání a spusťte svou funkci. |
| 4 | Vy | Připojte do messages zprávu asistenta a jednu zprávu tool na každé volání, pak pošlete požadavek znovu se stejnými tools. |
| 5 | Model | Model odpoví textem s finish_reason: "stop", nebo požádá o další volání. V tom případě se vraťte ke kroku 3. |
Jeden požadavek je jedno kolo modelu. API mezi požadavky neuchovává konverzaci a nestanoví počet kol: váš kód drží messages a rozhoduje, kdy skončit.
Definování nástrojů
tools je pole s jednou položkou na funkci. Přijímá je každý model katalogu; GET /v1/models hlásí capabilities.tools: true pro každé id.
| Pole | Typ | Popis |
|---|---|---|
type | string | Vždy function. |
function.name | string | Název, který model používá, když o tuto funkci žádá. Povinné. |
function.description | string | Co funkce dělá, srozumitelným jazykem. |
function.parameters | object | Argumenty jako JSON Schema s type: "object" nahoře. Viz Klíčová slova schématu níže. |
Každý endpoint má vlastní zápis nástroje. Pošlete ten, který patří endpointu, který 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 říká, zda smí, nebo musí model zavolat nástroj. Čte se pouze spolu s tools.
| Hodnota | Popis | Uplatňují |
|---|---|---|
"auto" | Model rozhodne, zda odpoví textem, nebo zavolá nástroj. Toto je výchozí hodnota. | Všechny modely |
"required" | Odpověď volá alespoň jeden nástroj. | Hostované modely s otevřenými váhami |
{"type": "function", "function": {"name": "get_weather"}} | Odpověď volá tuto funkci. Název musí být jednou z funkcí v tools. Volání jiných funkcí se z odpovědi vynechají. | Hostované modely s otevřenými váhami |
Modely Shannon (shannon-*) rozhodují v každém požadavku samy, jako při auto.
U required nebo pojmenované funkce čtěte finish_reason dřív než tool_calls. Když model žádné volání nevytvoří, odpověď je textová s finish_reason: "stop".
| Význam | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Model rozhodne | "auto" | "auto" | {"type": "auto"} |
| Zavolat alespoň jeden nástroj | "required" | "required" | {"type": "any"} |
| Zavolat jednu pojmenovanou funkci | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Přijímáno kvůli kompatibilitě: tool_choice: "none" a parallel_tool_calls. Pro kolo bez volání nástrojů pošlete požadavek bez tools.
Volání nástrojů v odpovědi
| Pole | Typ | Popis |
|---|---|---|
finish_reason | string | tool_calls, když odpověď nese alespoň jedno volání. |
message.tool_calls | array | Jedna položka na volání. Pole je přítomno, jen když model požádal o volání. |
tool_calls[].id | string | call_ následované 32 hexadecimálními znaky. Pošlete je zpět jako tool_call_id s výsledkem. |
tool_calls[].type | string | Vždy function. |
tool_calls[].function.name | string | Funkce, která se má spustit. |
tool_calls[].function.arguments | string | Argumenty jako řetězec JSON, "{}", když žádné nejsou. Před použitím jej zpracujte. |
message.content | string | null | null, když odpověď obsahuje pouze volání. Hostované modely s otevřenými váhami mohou vedle volání vrátit text; modely Shannon vrací null. |
Stejné volání v každém formátu. Na /v1/responses je to položka function_call v output, s arguments jako řetězcem JSON. Na /v1/messages je to blok obsahu tool_use, jehož input je objekt JSON, jeho id začíná 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"}
}
]
} Několik volání v jednom kole
Odpověď může nést několik volání. Spusťte každé z nich a v dalším požadavku pošlete jeden výsledek na volání, každý s vlastním tool_call_id.
Hostované modely s otevřenými váhami vrací každé odlišné volání jednou: dvě volání se stejným názvem a stejnými argumenty přijdou jako jedno.
Streamovaná volání nástrojů
S stream: true přijde volání vcelku: chunk obsahuje kompletní řetězec arguments, takže není co spojovat. index počítá volání 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 | Co přichází |
|---|---|
/v1/chat/completions | Jeden chat.completion.chunk na volání, s voláním v delta.tool_calls[0]. Poslední chunk má finish_reason: "tool_calls" a usage. |
/v1/responses | Na volání: response.output_item.added (položka function_call s prázdnými arguments), response.function_call_arguments.delta (celý řetězec), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Na volání: content_block_start (blok tool_use s prázdným input), jedna content_block_delta, jejíž input_json_delta.partial_json je celý text argumentů, content_block_stop. message_delta pak nese stop_reason: "tool_use". |
U shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro a shannon-coder-1 streamovaný požadavek, který nese tools, doručí text odpovědi v jedné deltě content na konci kola. Streamování
Odesílání výsledků zpět
Druhý požadavek opakuje konverzaci a přidává dvě věci: kolo asistenta, které požádalo o volání, a jeden výsledek na volání.
{
"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šlete zpět tak, jak jste je dostali, před výsledky. Každý výsledek se přiřazuje k volání podle id:
tool_call_idna/v1/chat/completions,call_idna/v1/responses,tool_use_idna/v1/messages. - Výsledek je text. Objekt serializujte do řetězce JSON pro
content(outputna/v1/responses). Na/v1/messagesjecontentblokutool_resultřetězec nebo seznam textových bloků. - V kole asistenta zůstává
function.argumentsřetězcem JSON, přesně tak, jak přišlo. - Konverzace může končit výsledkem nástroje. Nová zpráva uživatele není potřeba: model pokračuje od výsledku.
- Když vaše funkce selže, pošlete selhání jako text výsledku. Model to pak může oznámit nebo požádat o další volání.
Klíčová slova schématu
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é modely s otevřenými váhami jej dostanou tak, jak jej pošlete.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro a shannon-coder-1 dostanou tuto podmnožinu, na všech třech endpointech:
| Zacházení | Klíčová slova |
|---|---|
| Čte se tak, jak bylo posláno | Každé klíčové slovo, které není uvedeno v řádcích níže, například type, properties, required, items, enum, description, minimum, maximum, anyOf a allOf, na každé úrovni schématu. |
format | Čte se pro hodnoty int32, int64, float, double, byte, date, date-time a enum. |
oneOf | Čte se jako anyOf. |
| Není součástí schématu, které tyto modely dostanou | $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, když jsou to čísla; ostatní hodnoty format. |
Chování a limity
- API nestanoví žádný nejvyšší počet nástrojů ani nejvyšší počet kol.
- Tělo požadavku může mít až 32 MiB a konverzace s výsledky se musí vejít do kontextového okna modelu.
- Když požadavek nese
tools, používajíshannon-1.6-lite,shannon-1.6-pro,shannon-2-liteashannon-2-provýchozítemperature0.2. Jinou hodnotu nastavíte odeslánímtemperature. - Každé kolo je samostatný požadavek: čerpá z vašeho zůstatku a počítá se do ochrany proti zahlcení jako každý jiný požadavek. Limity a zůstatek
Chyby
Volání nástroje je běžná odpověď se stavem 200. Tyto chyby se týkají samotného požadavku:
| Stav | Typ | Zpráva | Kdy |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model není id ze zveřejněného seznamu. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools není pole, nebo má jiné pole špatný typ JSON. |
413 | invalid_request_error | Failed to buffer the request body: … | Tělo požadavku je větší než 32 MiB. Chyba nese code: "request_too_large". |
Argumenty píše model. Před spuštěním funkce je zkontrolujte podle svého schématu, jako byste kontrolovali jakýkoli vnější vstup.
Chyby ověření, zůstatku a serveru jsou stejné jako u každého požadavku. Zpracování chyb