Функция шақыру
Функцияларыңызды сұраудан сипаттаңыз, ал модель орындалуын қалайтын шақыруларымен жауап береді. Кодыңыз оларды орындап, нәтижелерді қайта жібереді: API құрал шақыруларын қайтарады, құралдың өзін орындамайды.
POST https://api.shannon-ai.com/v1/chat/completions
Осы беттегі үлгілер /v1/chat/completions қолданады. Сол цикл /v1/responses және /v1/messages бойынша да жұмыс істейді; формат бір нәрсені басқаша жазған жерде төмендегі бөлімдер үшеуін де көрсетеді.
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"]
}
}
}]
}' Бірінші жауап сұраққа жауап бермейді. Ол шақыру сұрайды:
{
"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}
}
} Нәтижені жібергеннен кейін келесі жауап қарапайым жауап болады: message.content мәтінді қамтиды, ал finish_reason мәні stop.
Цикл қадамдап
| Қадам | Кім | Не болады |
|---|---|---|
| 1 | Сіз | messages мен tools тізімін, яғни модель сұрай алатын функцияларды бірге жіберіңіз. |
| 2 | Модель | Жауап tool_calls және finish_reason: "tool_calls" алып жүреді. Әр шақыру функцияны атап, оның аргументтерін береді. |
| 3 | Сіз | Әр шақырудың arguments мәнін парсинг жасап, функцияңызды орындаңыз. |
| 4 | Сіз | messages ішіне assistant хабарламасын және әр шақыруға бір tool хабарламасын қосыңыз, содан кейін сұрауды сол tools мәнімен қайта жіберіңіз. |
| 5 | Модель | Модель finish_reason: "stop" бар мәтінмен жауап береді, немесе көбірек шақыру сұрайды. Ол жағдайда 3-қадамға оралыңыз. |
Бір сұрау — модельдің бір кезеңі. API сұраулар арасында сөйлесуді сақтамайды және раунд санын белгілемейді: messages мәнін кодыңыз ұстайды және қашан тоқтау керегін шешеді.
Құралдарды анықтау
tools — әр функцияға бір жазбасы бар массив. Каталогтың әр моделі оны қабылдайды; GET /v1/models әр id үшін capabilities.tools: true көрсетеді.
| Өріс | Түрі | Сипаттама |
|---|---|---|
type | string | Әрқашан function. |
function.name | string | Модель осы функцияны сұрағанда қолданатын ат. Міндетті. |
function.description | string | Функция не істейтіні, қарапайым тілде. |
function.parameters | object | Жоғарғы деңгейінде type: "object" бар JSON Schema түріндегі аргументтер. Төмендегі Схема кілт сөздері бөлімін қараңыз. |
Әр endpoint-тің құралды жазудың өз түрі бар. Шақыратын endpoint-ке тиесілісін жіберіңіз:
{
"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 модель құралды шақыра алатынын немесе шақыруға тиіс екенін айтады. Ол тек tools бірге оқылады.
| Мәні | Сипаттама | Қолданады |
|---|---|---|
"auto" | Мәтінмен жауап беруді немесе құралды шақыруды модель шешеді. Бұл әдепкі мән. | Барлық модельдер |
"required" | Жауап кемінде бір құралды шақырады. | Hosted open-weight модельдер |
{"type": "function", "function": {"name": "get_weather"}} | Жауап осы функцияны шақырады. Аты tools ішіндегі функциялардың бірі болуы керек. Басқа функцияларға шақырулар жауаптан алынып тасталады. | Hosted open-weight модельдер |
Shannon модельдері (shannon-*) әр сұраста auto сияқты өзі шешеді.
required немесе аталған функция болғанда tool_calls оқымас бұрын finish_reason оқыңыз. Модель шақыру жасамаса, жауап finish_reason: "stop" бар мәтіндік жауап болады.
| Мағынасы | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| Модель шешеді | "auto" | "auto" | {"type": "auto"} |
| Кемінде бір құралды шақыру | "required" | "required" | {"type": "any"} |
| Бір аталған функцияны шақыру | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Үйлесімділік үшін қабылданады: tool_choice: "none" және parallel_tool_calls. Құрал шақыруларсыз кезең үшін сұрауды tools жоқ жіберіңіз.
Жауаптағы құрал шақырулары
| Өріс | Түрі | Сипаттама |
|---|---|---|
finish_reason | string | Жауапта кемінде бір шақыру болғанда tool_calls. |
message.tool_calls | array | Әр шақыруға бір жазба. Өріс тек модель шақыру сұраған кезде болады. |
tool_calls[].id | string | call_ және одан кейін 32 оналтылық таңба. Нәтижемен бірге оны tool_call_id ретінде қайта жіберіңіз. |
tool_calls[].type | string | Әрқашан function. |
tool_calls[].function.name | string | Орындалатын функция. |
tool_calls[].function.arguments | string | Аргументтер JSON жолы ретінде, олар болмаса "{}". Қолданар алдында оны парсинг жасаңыз. |
message.content | string | null | Жауапта тек шақырулар болса, null. Hosted open-weight модельдер шақырулармен қатар мәтін қайтара алады; Shannon модельдері null қайтарады. |
Әр форматтағы сол шақыру. /v1/responses бойынша ол output ішіндегі function_call элементі, arguments JSON жолы түрінде. /v1/messages бойынша ол input мәні JSON нысаны болатын tool_use мазмұн блогы, оның id өрісі toolu_ әрпінен басталады, ал stop_reason мәні 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"}
}
]
} Бір кезеңдегі бірнеше шақыру
Жауап бірнеше шақыру алып жүре алады. Олардың әрқайсысын орындап, келесі сұрауда әр шақыру үшін өз tool_call_id мәні бар бір нәтижеден жіберіңіз.
Hosted open-weight модельдер әр ерекше шақыруды бір рет қайтарады: аты және аргументтері бірдей екі шақыру біреу болып келеді.
Стримделген құрал шақырулары
stream: true болғанда шақыру бір бөлікпен келеді: бөлікте толық arguments жолы бар, сондықтан біріктіретін фрагменттер жоқ. index кезеңдегі шақыруларды 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 | Не келеді |
|---|---|
/v1/chat/completions | Әр шақыруға бір chat.completion.chunk, шақыру delta.tool_calls[0] ішінде. Соңғы бөлікте finish_reason: "tool_calls" және usage бар. |
/v1/responses | Әр шақыруға: response.output_item.added (бос arguments бар function_call элементі), response.function_call_arguments.delta (бүкіл жол), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Әр шақыруға: content_block_start (бос input бар tool_use блогы), input_json_delta.partial_json бүкіл аргумент мәтіні болатын бір content_block_delta, content_block_stop. Содан кейін message_delta stop_reason: "tool_use" алып жүреді. |
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro және shannon-coder-1 бойынша tools алып жүретін стрим сұрау жауап мәтінін кезеңнің соңында бір content дельтасымен жеткізеді. Стриминг
Нәтижелерді қайта жіберу
Екінші сұрау сөйлесуді қайталап, екі нәрсе қосады: шақыруларды сұраған assistant кезеңі және әр шақыруға бір нәтиже.
{
"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 кезеңін нәтижелердің алдында өзіңіз алғандай қайта жіберіңіз. Әр нәтиже өз шақыруымен id арқылы сәйкестендіріледі:
/v1/chat/completionsбойыншаtool_call_id,/v1/responsesбойыншаcall_id,/v1/messagesбойыншаtool_use_id. - Нәтиже — мәтін. Нысанды
contentүшін (/v1/responsesбойыншаoutput) JSON жолына серияландырыңыз./v1/messagesбойыншаtool_resultблогыныңcontentөрісі — жол немесе мәтін блоктарының тізімі. - Assistant кезеңінде
function.argumentsкелгендей JSON жолы болып қалады. - Сөйлесу құрал нәтижесімен аяқталуы мүмкін. Жаңа пайдаланушы хабарламасы қажет емес: модель нәтижеден жалғастырады.
- Функцияңыз сәтсіз аяқталса, ақауды нәтиже мәтіні ретінде жіберіңіз. Сонда модель оны хабарлай алады немесе басқа шақыру сұрай алады.
Схема кілт сөздері
parameters (/v1/messages бойынша input_schema) — JSON Schema. Shannon 3 отбасы (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) және hosted open-weight модельдер оны жібергеніңіздей алады.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro және shannon-coder-1 барлық үш endpoint-те осы ішкі жиынды алады:
| Өңдеу | Кілт сөздер |
|---|---|
| Жіберілгендей оқылады | Төмендегі жолдарда аталмаған әр кілт сөз, мысалы type, properties, required, items, enum, description, minimum, maximum, anyOf және allOf, схеманың әр деңгейінде. |
format | int32, int64, float, double, byte, date, date-time және enum мәндері үшін оқылады. |
oneOf | anyOf ретінде оқылады. |
| Бұл модельдер алатын схемаға кірмейді | $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 және exclusiveMaximum; format өрісінің басқа мәндері. |
Мінез-құлық және шектеулер
- API құралдардың ең көп санын да, раундтардың ең көп санын да белгілемейді.
- Сұрау денесі 32 MiB-қа дейін болуы мүмкін, ал нәтижелерімен бірге сөйлесу модельдің контекст терезесіне сыюы керек.
- Сұрау
toolsалып жүргендеshannon-1.6-lite,shannon-1.6-pro,shannon-2-liteжәнеshannon-2-proәдепкіtemperatureмәнін 0.2 етіп қолданады. Басқа мән орнату үшінtemperatureжіберіңіз. - Әр раунд — жеке сұрау: ол балансыңыздан алады және кез келген басқа сұрау сияқты flood protection есебіне кіреді. Шектеулер және баланс
Қателер
Құрал шақыруы — 200 мәртебесі бар қалыпты жауап. Бұл қателер сұраудың өзіне қатысты:
| Мәртебе | Түрі | Хабарлама | Қашан |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model жарияланған тізімдегі id емес. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools массив емес, немесе басқа өрістің JSON түрі қате. |
413 | invalid_request_error | Failed to buffer the request body: … | Сұрау денесі 32 MiB-тан үлкен. Қатеде code: "request_too_large" бар. |
Аргументтерді модель жазады. Функцияны орындамас бұрын оларды кез келген сыртқы кіріс сияқты схемаңызбен тексеріңіз.
Аутентификация, баланс және сервер қателері әр сұрау үшін бірдей. Қателерді өңдеу