Функция чакыруу
Функцияларыңызды сурамда сүрөттөңүз, модель өзү каалаган чалууларды жооп катары берет. Коддуңуз аларды аткарып, натыйжаларды кайра жөнөтөт: 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 ичине ассистент билдирүүсүн жана ар бир чалуу үчүн бир 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 | Аргументтер JSON Schema түрүндө, жогорку деңгээлде type: "object" менен. Төмөндөгү Схеманын ачкыч сөздөрү бөлүмүн караңыз. |
Ар бир 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" | Жооп жок дегенде бир куралды чакырат. | Хостингдеги ачык салмактуу моделдер |
{"type": "function", "function": {"name": "get_weather"}} | Жооп ушул функцияны чакырат. Ат tools ичиндеги функциялардын бири болушу керек. Башка функцияларга чалуулар жоопко киргизилбейт. | Хостингдеги ачык салмактуу моделдер |
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. Хостингдеги ачык салмактуу моделдер чалуулардын жанында текст кайтара алат; Shannon моделдери null кайтарат. |
Ошол эле чалуу ар бир форматта. /v1/responses боюнча ал output'тун function_call элементи, arguments JSON сап түрүндө. /v1/messages боюнча ал tool_use мазмун блогу, анын input'у JSON объекти, 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 менен бирден натыйжа жөнөтүңүз.
Хостингдеги ачык салмактуу моделдер ар бир айырмаланган чалууну бир гана жолу кайтарат: аты жана аргументтери бирдей эки чалуу бир катары келет.
Стримдеги курал чалуулары
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 блогу), бир content_block_delta, анын input_json_delta.partial_json аргументтердин бүт тексти, 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 дельтасында берет. Стриминг
Натыйжаларды кайра жөнөтүү
Экинчи сурам сүйлөшүүнү кайталайт жана экөөнү кошот: чалууларды сураган ассистент кадамын жана ар бир чалуу үчүн бир натыйжаны.
{
"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\"}"
}
]
}
]
} - Ассистент кадамын натыйжалардан мурун, алганыңыздай кайра жөнөтүңүз. Ар бир натыйжа чалуусуна 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'и сап же текст блокторунун тизмеси. - Ассистент кадамында
function.argumentsкелгендей эле JSON сап бойдон калат. - Сүйлөшүү курал натыйжасы менен аяктаса болот. Жаңы колдонуучу билдирүүсү керек эмес: модель натыйжадан улантат.
- Функцияңыз ишке ашпаса, катаны натыйжа тексти катары жөнөтүңүз. Модель аны билдире алат же башка чалууну сурай алат.
Схеманын ачкыч сөздөрү
parameters (/v1/messages боюнча input_schema) — JSON Schema. Shannon 3 үй-бүлөсү (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) жана хостингдеги ачык салмактуу моделдер аны жөнөткөнүңүздөй алат.
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стандарттууtemperature0.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" бар. |
Аргументтерди модель жазат. Функцияны аткарардан мурун аларды схемаңызга каршы текшериңиз, башка тышкы киргизүүнү текшергендей.
Аутентификация, баланс жана сервер каталары ар бир сурамдагыдай эле. Ката иштетүү