Funkciju izsaukšana
Aprakstiet savas funkcijas pieprasījumā, un modelis atbild ar izsaukumiem, kurus tas vēlas veikt. Jūsu kods tos palaiž un sūta rezultātus atpakaļ: API atgriež rīku izsaukumus un pats rīku nepalaiž.
POST https://api.shannon-ai.com/v1/chat/completions
Šīs lapas piemēros izmantots /v1/chat/completions. Tas pats cikls darbojas galapunktos /v1/responses un /v1/messages; kur formāti kaut ko raksta citādi, tālāk esošajās sadaļās parādīti visi trīs.
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"]
}
}
}]
}' Pirmā atbilde uz jautājumu neatbild. Tā lūdz izsaukumu:
{
"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}
}
} Pēc rezultāta nosūtīšanas nākamā atbilde ir parasta atbilde: message.content satur tekstu un finish_reason ir stop.
Cikls pa soļiem
| Solis | Kas | Kas notiek |
|---|---|---|
| 1 | Jūs | Nosūtiet messages kopā ar tools — funkciju sarakstu, ko modelis drīkst pieprasīt. |
| 2 | Modelis | Atbildē ir tool_calls un finish_reason: "tool_calls". Katrs izsaukums norāda funkciju un dod tās argumentus. |
| 3 | Jūs | Parsējiet katra izsaukuma arguments un palaidiet savu funkciju. |
| 4 | Jūs | Pievienojiet messages asistenta ziņojumu un vienu tool ziņojumu katram izsaukumam, tad nosūtiet pieprasījumu vēlreiz ar tiem pašiem tools. |
| 5 | Modelis | Modelis atbild ar tekstu un finish_reason: "stop" vai pieprasa vēl izsaukumus. Tādā gadījumā atgriezieties pie 3. soļa. |
Viens pieprasījums ir viens modeļa gājiens. API starp pieprasījumiem nesaglabā sarunu un nenosaka ciklu skaitu: messages glabā jūsu kods un tas izlemj, kad apstāties.
Rīku definēšana
tools ir masīvs ar vienu ierakstu katrai funkcijai. To pieņem katrs katalogā esošais modelis; GET /v1/models katram id norāda capabilities.tools: true.
| Lauks | Tips | Apraksts |
|---|---|---|
type | string | Vienmēr function. |
function.name | string | Nosaukums, ko modelis lieto, kad pieprasa šo funkciju. Obligāts. |
function.description | string | Ko funkcija dara, vienkāršā valodā. |
function.parameters | object | Argumenti kā JSON Schema, augšā ar type: "object". Skatiet zemāk sadaļu Shēmas atslēgvārdi. |
Katram galapunktam ir sava rīka pieraksta forma. Sūtiet to, kas atbilst galapunktam, ko izsaucat:
{
"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 norāda, vai modelis drīkst vai tam jāizsauc rīks. To lasa tikai kopā ar tools.
| Vērtība | Apraksts | Piemēro |
|---|---|---|
"auto" | Modelis pats izlemj, vai atbildēt ar tekstu vai izsaukt rīku. Tas ir noklusējums. | Visi modeļi |
"required" | Atbilde izsauc vismaz vienu rīku. | Hostētie atvērto svaru modeļi |
{"type": "function", "function": {"name": "get_weather"}} | Atbilde izsauc šo funkciju. Nosaukumam jābūt vienam no tools norādītajiem funkciju nosaukumiem. Izsaukumi uz citām funkcijām atbildē netiek iekļauti. | Hostētie atvērto svaru modeļi |
Shannon modeļi (shannon-*) katrā pieprasījumā izlemj paši, tāpat kā ar auto.
Ar required vai nosauktu funkciju pirms tool_calls lasīšanas pārbaudiet finish_reason. Ja modelis neizveido nevienu izsaukumu, atbilde ir teksta atbilde ar finish_reason: "stop".
| Nozīme | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Modelis izlemj | "auto" | "auto" | {"type": "auto"} |
| Izsaukt vismaz vienu rīku | "required" | "required" | {"type": "any"} |
| Izsaukt vienu nosauktu funkciju | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Savietojamības dēļ tiek pieņemti: tool_choice: "none" un parallel_tool_calls. Lai veiktu gājienu bez rīku izsaukumiem, sūtiet pieprasījumu bez tools.
Rīku izsaukumi atbildē
| Lauks | Tips | Apraksts |
|---|---|---|
finish_reason | string | tool_calls, ja atbildē ir vismaz viens izsaukums. |
message.tool_calls | array | Viens ieraksts katram izsaukumam. Lauks ir klāt tikai tad, ja modelis lūdza izsaukumu. |
tool_calls[].id | string | call_, kam seko 32 heksadecimālas rakstzīmes. Sūtiet to atpakaļ kā tool_call_id kopā ar rezultātu. |
tool_calls[].type | string | Vienmēr function. |
tool_calls[].function.name | string | Funkcija, kas jāpalaiž. |
tool_calls[].function.arguments | string | Argumenti kā JSON virkne, "{}", ja to nav. Pirms lietošanas to parsējiet. |
message.content | string | null | null, ja atbildē ir tikai izsaukumi. Hostētie atvērto svaru modeļi līdzās izsaukumiem var atgriezt tekstu; Shannon modeļi atgriež null. |
Tas pats izsaukums katrā formātā. Galapunktā /v1/responses tas ir output elements function_call, ar arguments kā JSON virkni. Galapunktā /v1/messages tas ir satura bloks tool_use, kura input ir JSON objekts, tā id sākas ar toolu_, un stop_reason ir 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"}
}
]
} Vairāki izsaukumi vienā gājienā
Atbildē var būt vairāki izsaukumi. Palaidiet katru no tiem un nākamajā pieprasījumā nosūtiet vienu rezultātu katram izsaukumam, katru ar savu tool_call_id.
Hostētie atvērto svaru modeļi katru atšķirīgo izsaukumu atgriež vienreiz: divi izsaukumi ar vienādu nosaukumu un vienādiem argumentiem ierodas kā viens.
Straumēti rīku izsaukumi
Ar stream: true izsaukums ierodas vienā gabalā: daļā ir pilna arguments virkne, tāpēc nav fragmentu, kas jāsavieno. index skaita gājiena izsaukumus no 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
}
]
} | Galapunkts | Kas ierodas |
|---|---|
/v1/chat/completions | Viens chat.completion.chunk katram izsaukumam, izsaukums ir delta.tool_calls[0]. Pēdējā daļa satur finish_reason: "tool_calls" un usage. |
/v1/responses | Katram izsaukumam: response.output_item.added (elements function_call ar tukšu arguments), response.function_call_arguments.delta (visa virkne), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Katram izsaukumam: content_block_start (bloks tool_use ar tukšu input), viens content_block_delta, kura input_json_delta.partial_json ir viss argumentu teksts, content_block_stop. Pēc tam message_delta satur stop_reason: "tool_use". |
Modeļiem shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro un shannon-coder-1 straumētā pieprasījumā ar tools atbildes teksts tiek piegādāts vienā content delta gājiena beigās. Straumēšana
Rezultātu nosūtīšana atpakaļ
Otrais pieprasījums atkārto sarunu un pievieno divas lietas: asistenta gājienu, kas pieprasīja izsaukumus, un vienu rezultātu katram izsaukumam.
{
"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\"}"
}
]
}
]
} - Nosūtiet asistenta gājienu atpakaļ tādu, kādu saņēmāt, pirms rezultātiem. Katrs rezultāts tiek sasaistīts ar savu izsaukumu pēc id:
tool_call_idgalapunktā/v1/chat/completions,call_idgalapunktā/v1/responses,tool_use_idgalapunktā/v1/messages. - Rezultāts ir teksts. Objektu serializējiet JSON virknē laukam
content(outputgalapunktā/v1/responses). Galapunktā/v1/messagesblokatool_resultlaukscontentir virkne vai teksta bloku saraksts. - Asistenta gājienā
function.argumentspaliek JSON virkne, tieši tāda, kāda tā ieradās. - Saruna var beigties ar rīka rezultātu. Jauns lietotāja ziņojums nav vajadzīgs: modelis turpina no rezultāta.
- Ja jūsu funkcija neizdodas, nosūtiet kļūmi kā rezultāta tekstu. Tad modelis var par to ziņot vai pieprasīt citu izsaukumu.
Shēmas atslēgvārdi
parameters (input_schema galapunktā /v1/messages) ir JSON Schema. Shannon 3 saime (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) un hostētie atvērto svaru modeļi to saņem tādu, kādu jūs nosūtāt.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro un shannon-coder-1 šo apakškopu saņem visos trīs galapunktos:
| Apstrāde | Atslēgvārdi |
|---|---|
| Tiek lasīts, kā nosūtīts | Katrs atslēgvārds, kas nav nosaukts zemāk esošajās rindās, piemēram, type, properties, required, items, enum, description, minimum, maximum, anyOf un allOf, katrā shēmas līmenī. |
format | Tiek lasīts vērtībām int32, int64, float, double, byte, date, date-time un enum. |
oneOf | Tiek lasīts kā anyOf. |
| Nav daļa no shēmas, ko šie modeļi saņem | $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 un exclusiveMaximum, ja tie ir skaitļi; citas format vērtības. |
Uzvedība un ierobežojumi
- API nenosaka ne maksimālo rīku skaitu, ne maksimālo ciklu skaitu.
- Pieprasījuma pamatteksts var būt līdz 32 MiB, un sarunai kopā ar rezultātiem jāietilpst modeļa konteksta logā.
- Ja pieprasījumā ir
tools, modeļishannon-1.6-lite,shannon-1.6-pro,shannon-2-liteunshannon-2-proizmanto noklusējumatemperature0.2. Lai iestatītu citu vērtību, nosūtiettemperature. - Katrs cikls ir atsevišķs pieprasījums: tas tērē jūsu atlikumu un tiek ieskaitīts flood protection tāpat kā jebkurš cits pieprasījums. Ierobežojumi un atlikums
Kļūdas
Rīka izsaukums ir parasta atbilde ar statusu 200. Šīs kļūdas attiecas uz pašu pieprasījumu:
| Statuss | Veids | Ziņojums | Kad |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model nav id no publicētā saraksta. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools nav masīvs, vai citam laukam ir nepareizs JSON tips. |
413 | invalid_request_error | Failed to buffer the request body: … | Pieprasījuma pamatteksts ir lielāks par 32 MiB. Kļūda satur code: "request_too_large". |
Argumentus uzraksta modelis. Pirms funkcijas palaišanas pārbaudiet tos pret savu shēmu, tāpat kā jebkuru ārēju ievadi.
Autentifikācijas, atlikuma un servera kļūdas ir tādas pašas kā jebkuram pieprasījumam. Kļūdu apstrāde