Функц дуудлага
Хүсэлтдээ функцүүдээ тайлбарлавал загвар хийлгэхийг хүссэн дуудлагуудаа хариуд нь өгнө. Таны код тэдгээрийг ажиллуулж үр дүнг буцаан илгээнэ: API tool дуудлага буцаадаг ч tool-ийг өөрөө ажиллуулдаггүй.
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-ийг parse хийж, функцээ ажиллуулна. |
| 4 | Та | Assistant мессеж болон дуудлага бүрт нэг tool мессежийг messages-д нэмж, ижил tools-тэй хүсэлтээ дахин илгээнэ. |
| 5 | Загвар | Загвар finish_reason: "stop"-той текстээр хариулна, эсвэл дахин дуудлага хүснэ. Тэр үед 3-р алхам руу буцна. |
Нэг хүсэлт нь загварын нэг ээлж. API хүсэлтүүдийн хооронд харилцан яриаг хадгалдаггүй, орчмын тоог тогтоодоггүй: messages-ийг таны код барьж, хэзээ зогсохоо шийднэ.
Tool тодорхойлох
tools нь функц бүрт нэг бичлэгтэй массив. Каталогийн бүх загвар үүнийг хүлээн авна; GET /v1/models id бүрт capabilities.tools: true гэж мэдээлнэ.
| Талбар | Төрөл | Тайлбар |
|---|---|---|
type | string | Үргэлж function. |
function.name | string | Загвар энэ функцийг хүсэхдээ хэрэглэх нэр. Заавал. |
function.description | string | Функц юу хийдгийг энгийн хэлээр. |
function.parameters | object | Аргументууд, дээд түвшиндээ type: "object"-тэй JSON Schema хэлбэрээр. Доорх Schema түлхүүр үгс-ийг үзнэ үү. |
Endpoint бүр tool-ийг өөрөөр бичдэг. Дуудаж буй 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 нь загвар tool дуудаж болох уу, эсвэл заавал дуудах уу гэдгийг заана. Зөвхөн tools-тэй хамт уншигдана.
| Утга | Тайлбар | Хэрэгжүүлэгч |
|---|---|---|
"auto" | Загвар текстээр хариулах уу, tool дуудах уу гэдгийг өөрөө шийднэ. Энэ нь үндсэн утга. | Бүх загвар |
"required" | Хариу дор хаяж нэг tool дуудна. | 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"} |
| Дор хаяж нэг tool дуудна | "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. Tool дуудлагагүй ээлжид хүсэлтээ tools-гүй илгээнэ үү.
Хариу доторх tool дуудлага
| Талбар | Төрөл | Тайлбар |
|---|---|---|
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 string хэлбэрээр, байхгүй бол "{}". Ашиглахаасаа өмнө parse хийнэ үү. |
message.content | string | null | Хариу зөвхөн дуудлагаас бүрдэх үед null. Hosted open-weight загварууд дуудлагын хажууд текст буцааж болно; Shannon загварууд null буцаана. |
Ижил дуудлага формат бүрт. /v1/responses дээр энэ нь output-ийн function_call зүйл бөгөөд arguments нь JSON string. /v1/messages дээр энэ нь input нь JSON объект болсон tool_use content block бөгөөд 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 хийсэн tool дуудлага
stream: true-тэй үед дуудлага нэг хэсгээрээ ирнэ: chunk бүрэн arguments string агуулдаг тул залгах хэсэг байхгүй. 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] дотор. Сүүлийн chunk finish_reason: "tool_calls" ба usage агуулна. |
/v1/responses | Дуудлага бүрт: response.output_item.added (хоосон arguments-тэй function_call зүйл), response.function_call_arguments.delta (бүтэн string), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Дуудлага бүрт: content_block_start (хоосон input-тэй tool_use block), бүх аргументийн текстийг 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 агуулсан stream хүсэлт хариултын текстийг ээлжийн төгсгөлд нэг content delta-аар хүргэнэ. Дамжуулалт
Үр дүнг буцаан илгээх
Хоёр дахь хүсэлт харилцан яриаг давтаж, хоёр зүйл нэмнэ: дуудлага хүссэн 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. - Үр дүн бол текст. Объектыг JSON string болгож
content-д (/v1/responsesдээрoutput-д) өгнө./v1/messagesдээрtool_resultblock-ийнcontentнь string эсвэл текст block-уудын жагсаалт. - Assistant ээлжид
function.argumentsирсэн чигээрээ JSON string хэвээр үлдэнэ. - Харилцан яриа tool үр дүнгээр төгсөж болно. Шинэ хэрэглэгчийн мессеж хэрэггүй: загвар үр дүнгээс үргэлжлүүлнэ.
- Таны функц амжилтгүй болбол алдааг үр дүнгийн текст болгон илгээнэ. Тэгвэл загвар үүнийг мэдээлж эсвэл өөр дуудлага хүсэж болно.
Schema түлхүүр үгс
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, schema-ийн түвшин бүрт. |
format | int32, int64, float, double, byte, date, date-time ба enum утгуудад уншигдана. |
oneOf | anyOf гэж уншина. |
| Эдгээр загварт очдог schema-д ордоггүй | $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 нь tool-ийн дээд тоо болон орчмын дээд тоог тогтоодоггүй.
- Хүсэлтийн body 32 MiB хүртэл байж болох бөгөөд үр дүнтэй нь харилцан яриа загварын контекст цонхонд багтах ёстой.
- Хүсэлт
toolsагуулсан үедshannon-1.6-lite,shannon-1.6-pro,shannon-2-lite,shannon-2-proньtemperature-ийн үндсэн утгыг 0.2 болгоно. Өөр утга тогтоохын тулдtemperatureилгээнэ үү. - Орчим бүр нь тусдаа хүсэлт: үлдэгдлээс хасагдаж, бусад хүсэлтийн адил flood protection-д тоологдоно. Хязгаар ба үлдэгдэл
Алдаа
Tool дуудлага нь 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: … | Хүсэлтийн body 32 MiB-ээс том. Алдаа code: "request_too_large" агуулна. |
Аргументуудыг загвар бичнэ. Функцээ ажиллуулахаасаа өмнө гаднаас ирсэн ямар ч оролтыг шалгадаг шиг schema-тайгаа тулган шалгана уу.
Баталгаажуулалт, үлдэгдэл, серверийн алдаа бүх хүсэлтийнхтэй адил. Алдаа боловсруулах