Fonksiyon Çağırma
Fonksiyonlarınızı istekte tanımlayın; model, yapılmasını istediği çağrılarla yanıt verir. Kodunuz onları çalıştırır ve sonuçları geri gönderir: API araç çağrılarını döndürür ve bir aracı kendisi çalıştırmaz.
POST https://api.shannon-ai.com/v1/chat/completions
Bu sayfadaki örnekler /v1/chat/completions kullanır. Aynı döngü /v1/responses ve /v1/messages üzerinde de çalışır; bir biçimin bir şeyi farklı yazdığı yerlerde aşağıdaki bölümler üçünü de gösterir.
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 yanıt soruyu yanıtlamaz. Bir çağrı ister:
{
"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}
}
} Sonucu gönderdikten sonra sıradaki yanıt sıradan bir cevaptır: message.content metni içerir ve finish_reason değeri stop olur.
Döngü, adım adım
| Adım | Kim | Ne olur |
|---|---|---|
| 1 | Siz | messages alanını, modelin isteyebileceği fonksiyonların listesi olan tools ile birlikte gönderin. |
| 2 | Model | Yanıt tool_calls ve finish_reason: "tool_calls" taşır. Her çağrı bir fonksiyonu adlandırır ve bağımsız değişkenlerini verir. |
| 3 | Siz | Her çağrının arguments alanını ayrıştırın ve fonksiyonunuzu çalıştırın. |
| 4 | Siz | Assistant mesajını ve her çağrı için bir tool mesajını messages alanına ekleyin, sonra isteği aynı tools ile tekrar gönderin. |
| 5 | Model | Model finish_reason: "stop" ile metin olarak yanıt verir veya daha fazla çağrı ister. Bu durumda 3. adıma dönün. |
Bir istek bir model turudur. API istekler arasında konuşma tutmaz ve tur sayısı belirlemez: messages alanını kodunuz tutar ve ne zaman duracağına o karar verir.
Araçları tanımlama
tools, fonksiyon başına bir girdisi olan bir dizidir. Katalogdaki her model bunu kabul eder; GET /v1/models her kimlik için capabilities.tools: true bildirir.
| Alan | Tür | Açıklama |
|---|---|---|
type | string | Her zaman function. |
function.name | string | Modelin bu fonksiyonu isterken kullandığı ad. Zorunlu. |
function.description | string | Fonksiyonun ne yaptığı, sade bir dille. |
function.parameters | object | En üstte type: "object" bulunan bir JSON Schema olarak bağımsız değişkenler. Aşağıdaki Şema anahtar sözcükleri bölümüne bakın. |
Her uç noktanın bir aracı yazma biçimi kendine özgüdür. Çağırdığınız uç noktaya ait olanı gönderin:
{
"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 bir aracı çağırabileceğini veya çağırmak zorunda olduğunu belirtir. Yalnızca tools ile birlikte okunur.
| Değer | Açıklama | Uygulayan |
|---|---|---|
"auto" | Model metinle yanıt vermeye mi yoksa bir aracı çağırmaya mı karar verir. Varsayılan budur. | Tüm modeller |
"required" | Yanıt en az bir aracı çağırır. | Host edilen açık ağırlıklı modeller |
{"type": "function", "function": {"name": "get_weather"}} | Yanıt bu fonksiyonu çağırır. Ad, tools içindeki fonksiyonlardan biri olmalıdır. Diğer fonksiyonlara yapılan çağrılar yanıta alınmaz. | Host edilen açık ağırlıklı modeller |
Shannon modelleri (shannon-*) her istekte auto gibi kendileri karar verir.
required veya adı verilmiş bir fonksiyonla, tool_calls alanını okumadan önce finish_reason alanını okuyun. Model hiç çağrı üretmezse yanıt, finish_reason: "stop" olan bir metin yanıtıdır.
| Anlamı | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Model karar verir | "auto" | "auto" | {"type": "auto"} |
| En az bir aracı çağır | "required" | "required" | {"type": "any"} |
| Adı verilen bir fonksiyonu çağır | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Uyumluluk için kabul edilenler: tool_choice: "none" ve parallel_tool_calls. Araç çağrısı olmayan bir tur için isteği tools olmadan gönderin.
Yanıttaki araç çağrıları
| Alan | Tür | Açıklama |
|---|---|---|
finish_reason | string | Yanıt en az bir çağrı taşıdığında tool_calls. |
message.tool_calls | array | Çağrı başına bir girdi. Alan yalnızca model bir çağrı istediğinde bulunur. |
tool_calls[].id | string | call_ ve ardından 32 onaltılık karakter. Sonuçla birlikte tool_call_id olarak geri gönderin. |
tool_calls[].type | string | Her zaman function. |
tool_calls[].function.name | string | Çalıştırılacak fonksiyon. |
tool_calls[].function.arguments | string | Bağımsız değişkenler bir JSON dizgesi olarak; hiç yoksa "{}". Kullanmadan önce ayrıştırın. |
message.content | string | null | Yanıt yalnızca çağrı içerdiğinde null. Host edilen açık ağırlıklı modeller çağrıların yanında metin döndürebilir; Shannon modelleri null döndürür. |
Her biçimde aynı çağrı. /v1/responses üzerinde output içinde bir function_call öğesidir ve arguments bir JSON dizgesidir. /v1/messages üzerinde input alanı bir JSON nesnesi olan bir tool_use içerik bloğudur, id değeri toolu_ ile başlar ve stop_reason değeri tool_use olur.
{
"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"}
}
]
} Tek turda birden fazla çağrı
Bir yanıt birden fazla çağrı taşıyabilir. Hepsini çalıştırın ve sonraki istekte her biri kendi tool_call_id değeriyle, çağrı başına bir sonuç gönderin.
Host edilen açık ağırlıklı modeller her ayrı çağrıyı bir kez döndürür: aynı ada ve aynı bağımsız değişkenlere sahip iki çağrı tek çağrı olarak gelir.
Akışlı araç çağrıları
stream: true ile bir çağrı tek parça halinde gelir: parça eksiksiz arguments dizgesini içerir; bu yüzden birleştirilecek parçalar yoktur. index, turun çağrılarını 0'dan başlayarak sayar.
{
"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
}
]
} | Uç nokta | Ne gelir |
|---|---|
/v1/chat/completions | Çağrı başına bir chat.completion.chunk; çağrı delta.tool_calls[0] içinde. Son parça finish_reason: "tool_calls" ve usage taşır. |
/v1/responses | Çağrı başına: response.output_item.added (boş arguments içeren bir function_call öğesi), response.function_call_arguments.delta (tüm dizge), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Çağrı başına: content_block_start (boş input içeren bir tool_use bloğu), input_json_delta.partial_json değeri bağımsız değişkenlerin tüm metni olan bir content_block_delta, content_block_stop. Ardından message_delta, stop_reason: "tool_use" taşır. |
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro ve shannon-coder-1 üzerinde, tools taşıyan akışlı bir istek yanıt metnini turun sonunda tek bir content deltası içinde iletir. Akış
Sonuçları geri gönderme
İkinci istek konuşmayı tekrarlar ve iki şey ekler: çağrıları isteyen assistant turu ve çağrı başına bir sonuç.
{
"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 turunu, aldığınız gibi, sonuçlardan önce geri gönderin. Her sonuç çağrısıyla kimlik üzerinden eşleşir:
/v1/chat/completionsüzerindetool_call_id,/v1/responsesüzerindecall_id,/v1/messagesüzerindetool_use_id. - Sonuç metindir. Bir nesneyi
contentiçin (/v1/responsesüzerindeoutput) JSON dizgesine serileştirin./v1/messagesüzerinde birtool_resultbloğununcontentalanı bir dizge veya metin blokları listesidir. - Assistant turunda
function.arguments, geldiği gibi bir JSON dizgesi olarak kalır. - Konuşma bir araç sonucuyla bitebilir. Yeni bir kullanıcı mesajı gerekmez: model sonuçtan devam eder.
- Fonksiyonunuz başarısız olduğunda başarısızlığı sonuç metni olarak gönderin. Model bunu bildirebilir veya başka bir çağrı isteyebilir.
Şema anahtar sözcükleri
parameters (/v1/messages üzerinde input_schema) bir JSON Schema'dır. Shannon 3 ailesi (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) ve host edilen açık ağırlıklı modeller onu gönderdiğiniz gibi alır.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro ve shannon-coder-1 üç uç noktada da bu alt kümeyi alır:
| İşleniş | Anahtar sözcükler |
|---|---|
| Gönderildiği gibi okunur | Aşağıdaki satırlarda adı geçmeyen her anahtar sözcük; örneğin şemanın her düzeyinde type, properties, required, items, enum, description, minimum, maximum, anyOf ve allOf. |
format | int32, int64, float, double, byte, date, date-time ve enum değerleri için okunur. |
oneOf | anyOf olarak okunur. |
| Bu modellerin aldığı şemanın parçası değil | $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; sayı olduklarında exclusiveMinimum ve exclusiveMaximum; format alanının diğer değerleri. |
Davranış ve sınırlar
- API, en fazla araç sayısı ve en fazla tur sayısı belirlemez.
- Bir istek gövdesi 32 MiB'a kadar olabilir ve sonuçlarıyla birlikte konuşmanın modelin bağlam penceresine sığması gerekir.
- Bir istek
toolstaşıdığındashannon-1.6-lite,shannon-1.6-pro,shannon-2-liteveshannon-2-provarsayılan olarak 0.2temperaturekullanır. Başka bir değer içintemperaturegönderin. - Her tur kendi başına bir istektir: bakiyenizden harcar ve her istek gibi flood korumasına dahil edilir. Limitler ve bakiye
Hatalar
Bir araç çağrısı, 200 durumlu normal bir yanıttır. Bu hatalar isteğin kendisiyle ilgilidir:
| Durum | Tür | Mesaj | Ne zaman |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model, yayımlanmış listedeki bir kimlik değil. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools bir dizi değil veya başka bir alanın JSON türü yanlış. |
413 | invalid_request_error | Failed to buffer the request body: … | İstek gövdesi 32 MiB'dan büyük. Hata code: "request_too_large" taşır. |
Bağımsız değişkenleri model yazar. Herhangi bir dış girdiyi denetlediğiniz gibi, fonksiyonu çalıştırmadan önce bunları şemanıza göre denetleyin.
Kimlik doğrulama, bakiye ve sunucu hataları her istekteki gibidir. Hata yönetimi