Funksiya çağırışı
Funksiyalarınızı sorğuda təsvir edin, model isə icra edilməsini istədiyi çağırışlarla cavab verir. Kodunuz onları icra edir və nəticələri geri göndərir: API alət çağırışlarını qaytarır, aləti özü icra etmir.
POST https://api.shannon-ai.com/v1/chat/completions
Bu səhifədəki nümunələr /v1/chat/completions istifadə edir. Eyni dövrə /v1/responses və /v1/messages üzərində də işləyir; bir format nəyisə fərqli yazdıqda aşağıdakı bölmələr hər üçünü göstərir.
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"]
}
}
}]
}' İlk cavab suala cavab vermir. O, çağırış istəyir:
{
"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}
}
} Nəticəni göndərdikdən sonra növbəti cavab adi cavabdır: message.content mətni saxlayır və finish_reason stop-dur.
Dövrə addım-addım
| Addım | Kim | Nə baş verir |
|---|---|---|
| 1 | Siz | messages-i modelin istəyə biləcəyi funksiyaların siyahısı olan tools ilə birlikdə göndərin. |
| 2 | Model | Cavab tool_calls və finish_reason: "tool_calls" daşıyır. Hər çağırış funksiyanın adını və arqumentlərini verir. |
| 3 | Siz | Hər çağırışın arguments-ini parse edin və funksiyanızı icra edin. |
| 4 | Siz | Assistant mesajını və hər çağırış üçün bir tool mesajını messages-ə əlavə edin, sonra sorğunu eyni tools ilə yenidən göndərin. |
| 5 | Model | Model finish_reason: "stop" ilə mətnlə cavab verir və ya daha çox çağırış istəyir. Bu halda 3-cü addıma qayıdın. |
Bir sorğu bir model növbəsidir. API sorğular arasında söhbəti saxlamır və raund sayı təyin etmir: messages-i kodunuz saxlayır və nə vaxt dayanacağına o qərar verir.
Alətlərin təyin edilməsi
tools hər funksiya üçün bir element olan massivdir. Kataloqdakı hər model onu qəbul edir; GET /v1/models hər id üçün capabilities.tools: true bildirir.
| Sahə | Tip | Təsvir |
|---|---|---|
type | string | Həmişə function. |
function.name | string | Modelin bu funksiyanı istəyərkən istifadə etdiyi ad. Məcburidir. |
function.description | string | Funksiyanın nə etdiyi, sadə dildə. |
function.parameters | object | Arqumentlər, yuxarı səviyyədə type: "object" olan JSON Schema kimi. Aşağıdakı Sxem açar sözləri bölməsinə baxın. |
Hər endpoint alətin özünəməxsus yazılışına malikdir. Çağırdığınız endpoint-ə aid olanı göndərin:
{
"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 modelin alət çağıra biləcəyini, yoxsa çağırmalı olduğunu bildirir. O yalnız tools ilə birlikdə oxunur.
| Dəyər | Təsvir | Tətbiq edən |
|---|---|---|
"auto" | Model mətnlə cavab verəcəyinə, yoxsa alət çağıracağına özü qərar verir. Standart seçim budur. | Bütün modellər |
"required" | Cavab ən azı bir alət çağırır. | Host edilən açıq çəkili modellər |
{"type": "function", "function": {"name": "get_weather"}} | Cavab bu funksiyanı çağırır. Ad tools içindəki funksiyalardan biri olmalıdır. Digər funksiyalara çağırışlar cavaba daxil edilmir. | Host edilən açıq çəkili modellər |
Shannon modelləri (shannon-*) hər sorğuda auto-da olduğu kimi özü qərar verir.
required və ya adlı funksiya ilə tool_calls-u oxumazdan əvvəl finish_reason-u oxuyun. Model çağırış yaratmadıqda cavab finish_reason: "stop" ilə mətn cavabı olur.
| Mənası | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Model qərar verir | "auto" | "auto" | {"type": "auto"} |
| Ən azı bir alət çağır | "required" | "required" | {"type": "any"} |
| Bir adlı funksiyanı çağır | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Uyğunluq üçün qəbul edilir: tool_choice: "none" və parallel_tool_calls. Alət çağırışı olmayan növbə üçün sorğunu tools olmadan göndərin.
Cavabda alət çağırışları
| Sahə | Tip | Təsvir |
|---|---|---|
finish_reason | string | Cavab ən azı bir çağırış daşıyırsa tool_calls. |
message.tool_calls | array | Hər çağırış üçün bir element. Sahə yalnız model çağırış istəyəndə olur. |
tool_calls[].id | string | call_ və ardınca 32 hexadecimal simvol. Nəticə ilə birlikdə onu tool_call_id kimi geri göndərin. |
tool_calls[].type | string | Həmişə function. |
tool_calls[].function.name | string | İcra ediləcək funksiya. |
tool_calls[].function.arguments | string | Arqumentlər JSON sətri kimi, arqument yoxdursa "{}". İstifadə etməzdən əvvəl onu parse edin. |
message.content | string | null | Cavabda yalnız çağırışlar olduqda null. Host edilən açıq çəkili modellər çağırışlarla yanaşı mətn də qaytara bilər; Shannon modelləri null qaytarır. |
Eyni çağırış hər formatda. /v1/responses-da bu, output-un function_call elementidir və arguments JSON sətridir. /v1/messages-də bu, input-u JSON obyekti olan tool_use məzmun blokudur, onun id-si toolu_ ilə başlayır və stop_reason tool_use-dur.
{
"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"}
}
]
} Bir növbədə bir neçə çağırış
Cavab bir neçə çağırış daşıya bilər. Hamısını icra edin və növbəti sorğuda hər çağırış üçün öz tool_call_id-si ilə bir nəticə göndərin.
Host edilən açıq çəkili modellər hər fərqli çağırışı bir dəfə qaytarır: eyni ad və eyni arqumentlərlə iki çağırış bir çağırış kimi gəlir.
Axınlı alət çağırışları
stream: true ilə çağırış bir parça halında gəlir: chunk tam arguments sətrini saxlayır, ona görə birləşdiriləcək fraqmentlər yoxdur. index növbənin çağırışlarını 0-dan sayır.
{
"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 | Nə gəlir |
|---|---|
/v1/chat/completions | Hər çağırış üçün bir chat.completion.chunk, çağırış delta.tool_calls[0]-dadır. Son chunk-da finish_reason: "tool_calls" və usage olur. |
/v1/responses | Hər çağırış üçün: response.output_item.added (boş arguments-li function_call elementi), response.function_call_arguments.delta (bütün sətir), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Hər çağırış üçün: content_block_start (boş input-lu tool_use bloku), arqumentlərin bütün mətni olan input_json_delta.partial_json-lu bir content_block_delta, content_block_stop. Sonra message_delta stop_reason: "tool_use" daşıyır. |
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro və shannon-coder-1-də tools daşıyan axınlı sorğu cavab mətnini növbənin sonunda bir content delta ilə çatdırır. Axın
Nəticələrin geri göndərilməsi
İkinci sorğu söhbəti təkrarlayır və iki şey əlavə edir: çağırışları istəyən assistant növbəsi və hər çağırış üçün bir nəticə.
{
"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 növbəsini nəticələrdən əvvəl, aldığınız kimi geri göndərin. Hər nəticə id ilə öz çağırışına uyğunlaşdırılır:
/v1/chat/completions-datool_call_id,/v1/responses-dacall_id,/v1/messages-dətool_use_id. - Nəticə mətndir. Obyekti
contentüçün (/v1/responses-daoutput) JSON sətrinə serializasiya edin./v1/messages-dətool_resultblokununcontent-i sətir və ya mətn bloklarının siyahısıdır. - Assistant növbəsində
function.argumentsgəldiyi kimi JSON sətri olaraq qalır. - Söhbət alət nəticəsi ilə bitə bilər. Yeni user mesajı lazım deyil: model nəticədən davam edir.
- Funksiyanız uğursuz olduqda uğursuzluğu nəticə mətni kimi göndərin. Model bunu bildirə və ya başqa çağırış istəyə bilər.
Sxem açar sözləri
parameters (/v1/messages-də input_schema) JSON Schema-dır. Shannon 3 ailəsi (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) və host edilən açıq çəkili modellər onu göndərdiyiniz kimi alır.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro və shannon-coder-1 bu alt çoxluğu üç endpoint-də alır:
| İşlənmə | Açar sözlər |
|---|---|
| Göndərildiyi kimi oxunur | Aşağıdakı sətirlərdə adı çəkilməyən hər açar söz, məsələn type, properties, required, items, enum, description, minimum, maximum, anyOf və allOf, sxemin hər səviyyəsində. |
format | int32, int64, float, double, byte, date, date-time və enum dəyərləri üçün oxunur. |
oneOf | anyOf kimi oxunur. |
| Bu modellərin aldığı sxemin tərkibinə daxil deyil | $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; ədəd olduqda exclusiveMinimum və exclusiveMaximum; format-ın digər dəyərləri. |
Davranış və limitlər
- API alətlərin sayına və raundların sayına maksimum limit qoymur.
- Sorğu gövdəsi 32 MiB-a qədər ola bilər və nəticələrlə birlikdə söhbət modelin kontekst pəncərəsinə sığmalıdır.
- Sorğuda
toolsolduqdashannon-1.6-lite,shannon-1.6-pro,shannon-2-litevəshannon-2-prostandart olaraq 0.2temperatureistifadə edir. Başqa dəyər üçüntemperaturegöndərin. - Hər raund ayrıca sorğudur: balansınızdan çıxılır və digər sorğular kimi flood protection-a daxil olur. Limitlər və balans
Xətalar
Alət çağırışı 200 statuslu normal cavabdır. Bu xətalar sorğunun özünə aiddir:
| Status | Tip | Mesaj | Nə vaxt |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model dərc edilmiş siyahıdakı id deyil. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools massiv deyil və ya başqa sahənin JSON tipi yanlışdır. |
413 | invalid_request_error | Failed to buffer the request body: … | Sorğu gövdəsi 32 MiB-dan böyükdür. Xətada code: "request_too_large" olur. |
Arqumentləri model yazır. Funksiyanı icra etməzdən əvvəl onları hər hansı kənar giriş kimi sxeminizə qarşı yoxlayın.
Doğrulama, balans və server xətaları hər sorğu üçün olduğu kimidir. Xəta idarəetməsi