Баромадҳои сохторӣ
Ҷавобро ҳамчун JSON талаб кунед: объекти ихтиёрии JSON, ё JSON, ки схемаеро, ки мефиристед, риоя мекунад. Онро вақте истифода баред, ки барнома, на одам, ҷавобро мехонад.
POST https://api.shannon-ai.com/v1/chat/completions
import json
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1")
response = client.chat.completions.create(
model="Kimi-K3-3BIT-REAP",
messages=[
{"role": "user", "content": "Extract the person: John Doe, 30 years old, engineer."}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"occupation": {"type": "string"},
},
"required": ["name", "age", "occupation"],
},
},
},
)
# The JSON arrives as text in message.content: parse it, then check it.
try:
person = json.loads(response.choices[0].message.content)
except json.JSONDecodeError:
person = None # ask again, or report the failure
print(person) import OpenAI from "openai";
const client = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.shannon-ai.com/v1" });
const response = await client.chat.completions.create({
model: "Kimi-K3-3BIT-REAP",
messages: [
{ role: "user", content: "Extract the person: John Doe, 30 years old, engineer." },
],
response_format: {
type: "json_schema",
json_schema: {
name: "person",
strict: true,
schema: {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
occupation: { type: "string" },
},
required: ["name", "age", "occupation"],
},
},
},
});
// The JSON arrives as text in message.content: parse it, then check it.
let person = null;
try {
person = JSON.parse(response.choices[0].message.content);
} catch {
// ask again, or report the failure
}
console.log(person); 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": "Extract the person: John Doe, 30 years old, engineer."}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"occupation": {"type": "string"}
},
"required": ["name", "age", "occupation"]
}
}
}
}' JSON матни ҷавоб аст, дар choices[0].message.content:
{
"id": "chatcmpl-0c4e7a1b9d2f4e6a8b3c5d7e9f1a2b3c",
"object": "chat.completion",
"created": 1791590400,
"model": "Kimi-K3-3BIT-REAP",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
"reasoning_content": null
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 96,
"completion_tokens": 19,
"total_tokens": 115,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 0}
}
} Ҳолатҳои response_format
response_format майдони /v1/chat/completions аст. Бе он ҷавоб матни одӣ аст.
| Ҳолат | Қимат | Чӣ мегиред |
|---|---|---|
| Объекти JSON | {"type": "json_object"} | Ҷавоб JSON бе шакли муқарраршуда аст. Дар prompt гӯед, ки кадом калидҳоро мехоҳед. |
| Схемаи JSON | {"type": "json_schema", "json_schema": {"name": "…", "schema": {…}}} | Ҷавоб схемаеро, ки мефиристед, риоя мекунад: калидҳо, навъҳо ва майдонҳои ҳатмии он. |
| Strict | "strict": true | Майдони json_schema, на ҳолати сеюм. Он true аст, магар ин ки false фиристед. |
| Майдон | Навъ | Пешфарз | Тавсиф | Татбиқ мекунад |
|---|---|---|---|---|
type | string | json_object ё json_schema. Дар дохили response_format ҳатмӣ аст. text қабул карда мешавад ва ҷавоби матнии одӣ медиҳад. | Ҳар модели ин ҳолатро қабулкунанда | |
json_schema.schema | object | JSON Schema, ки ҷавоб онро риоя мекунад. Онро ҳар вақте ки type json_schema аст, фиристед. | Ҳар модели ин ҳолатро қабулкунанда | |
json_schema.name | string | Тамға барои схема, мисли формати OpenAI. | Моделҳои open-weight-и хостшуда | |
json_schema.strict | boolean | true | Оё ҷавоб бояд схемаро дақиқан риоя кунад. Моделҳои Shannon ҳар схемаро ҳамчун strict татбиқ мекунанд. | Моделҳои open-weight-и хостшуда |
Ҳолати объекти JSON схемаро талаб намекунад. Калидҳоро дар prompt ном баред:
{
"model": "shannon-3",
"messages": [
{
"role": "user",
"content": "Name the capital of France. Answer as JSON with the keys city and country."
}
],
"response_format": {"type": "json_object"}
} Дастгирӣ барои ҳар модел
| Модел | json_object | json_schema |
|---|---|---|
Ҳар модели Shannon (shannon-*) | Ҳа | Ҳа |
| Моделҳои open-weight-и хостшуда, ба истиснои онҳое, ки дар зер ном бурда шудаанд | Ҳа | Ҳа |
Laguna-S-2.1-W4A16-AUTOROUND-REAP | — | — |
inkling-W4A16-AUTOROUND-REAP | Ҳа | — |
GET /v1/models ҳамин чизро барои ҳар id хабар медиҳад: capabilities.json_schema дар ҳар модел ва capabilities.response_format дар моделҳои open-weight-и хостшуда. Моделҳо ва нархҳо
Калидвожаҳои дастгиришавандаи схема
Модел аз схемаи шумо чиро мегирад, аз модел ва аз endpoint вобаста аст:
| Моделҳо | /v1/chat/completions | /v1/responses |
|---|---|---|
| Моделҳои Shannon | Зермаҷмӯи калидвожаҳои зерин, ки ҳамчун strict татбиқ мешавад. | Схема ҳамон тавр, ки мефиристед, ҳамчун strict татбиқ мешавад. |
| Моделҳои open-weight-и хостшуда | Схема ҳамон тавр, ки мефиристед. strict true аст, магар ин ки онро фиристед. | Схема ҳамон тавр, ки мефиристед. strict true аст, магар ин ки онро фиристед. |
Зермаҷмӯи калидвожаҳои моделҳои Shannon дар /v1/chat/completions:
| Калидвожа | Чӣ гуна хонда мешавад |
|---|---|
| Калидвожаҳои хондашаванда | type, format, title, description, nullable, enum, items, properties, required, minItems, maxItems, minimum, maximum, minLength, maxLength, pattern, anyOf, default |
$ref | Аз $defs ё definitions дар сатҳи болоии схема ҳал карда мешавад. Калидвожаҳое, ки дар паҳлӯи $ref навишта шудаанд, масалан description, нигоҳ дошта мешаванд. Ишора бе таърифи мувофиқ ҳамчун {"type": "object"} хонда мешавад. |
allOf | Аъзоҳо ба як схема муттаҳид карда мешаванд. Ҷое ки ду аъзо як калидвожаро муқаррар мекунанд, охирин ҳисоб мешавад. |
oneOf | Ҳамчун anyOf хонда мешавад. |
| Схемаҳое, ки ба худашон ишора мекунанд | То 24 сатҳ густариш дода мешавад. Сатҳи амиқтар ҳамчун {"type": "object"} хонда мешавад. |
| Берун аз зермаҷмӯъ | Ҳар калидвожаи дигар, масалан additionalProperties, const, multipleOf, uniqueItems, exclusiveMinimum, exclusiveMaximum, patternProperties, prefixItems, minProperties, maxProperties, not ва if / then / else. Онҳо қисми схемае нестанд, ки модел мегирад. |
Дар /v1/responses: майдони text.format
/v1/responses ҳамин дархостро ҳамчун text.format менависад. Схема бевосита дар format, дар паҳлӯи name ва strict меистад, на дар зери калиди json_schema. Барои ҳолати объекти JSON {"format": {"type": "json_object"}}-ро фиристед.
{
"model": "Kimi-K3-3BIT-REAP",
"input": "Extract the person: John Doe, 30 years old, engineer.",
"text": {
"format": {
"type": "json_schema",
"name": "person",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"occupation": {"type": "string"}
},
"required": ["name", "age", "occupation"]
}
}
}
} JSON text-и қисми output_text-и ҷузъи message аст:
{
"output": [
{
"id": "msg_7e1d3c5b9a2f4d6e8c0b1a3f5e7d9c2b",
"type": "message",
"role": "assistant",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
"annotations": []
}
]
}
]
} Дастгирӣ барои ҳар модел ва хатогиҳо мисли /v1/chat/completions мебошанд. Responses API
Дар /v1/messages: абзор ҳамчун схема
Формати Messages майдони баромади сохторӣ надорад. Барои JSON аз ҳамин моделҳо /v1/chat/completions ё /v1/responses-ро бо ҳамин калид даъват кунед.
Барои дар /v1/messages мондан, объектро ҳамчун абзор тавсиф кунед: схемаи худро ба input_schema гузоред ва абзорро дар tool_choice ном баред. Он гоҳ input-и блоки tool_use объекти шумо аст, аллакай парсшуда. tool_choice-и номбаршударо моделҳои open-weight-и хостшуда татбиқ мекунанд.
{
"model": "Kimi-K3-3BIT-REAP",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Extract the person: John Doe, 30 years old, engineer."
}
],
"tools": [
{
"name": "record_person",
"description": "Record the extracted person.",
"input_schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"occupation": {"type": "string"}
},
"required": ["name", "age", "occupation"]
}
}
],
"tool_choice": {"type": "tool", "name": "record_person"}
} {
"stop_reason": "tool_use",
"content": [
{
"type": "tool_use",
"id": "toolu_4b8d2f6a1c3e4a5b9d7f0e2c4a6b8d1f",
"name": "record_person",
"input": {"name": "John Doe", "age": 30, "occupation": "engineer"}
}
]
} Пеш аз хондани блок санҷед, ки stop_reason tool_use аст. Даъвати функсия
JSON чӣ гуна меояд
- JSON сатр аст. Дар паҳлӯи ҷавоб объекти парсшуда нест: парсери JSON-и худро ба
message.contentтатбиқ кунед. - Бо
stream: trueJSON дар порчаҳоиdelta.contentмеояд. Онҳоро якҷоя кунед ва пас аз анҷоми ҷараён як бор парс кунед; порчаи ҷудогона JSON-и дуруст нест. - Модели open-weight-и хостшуда ба дархости
response_formatбе матни reasoning ҷавоб медиҳад:reasoning_contentnullаст.
Он чиро мегиред, санҷед
Схема тарзи навиштани моделро роҳнамоӣ мекунад. API ҷавоби тамомшударо бо схемаи шумо муқоиса намекунад, бинобар ин санҷиши ниҳоиро рамзи шумо анҷом медиҳад:
- Дар дохили идоракунандаи хатогӣ парс кунед, мисли намунаи боло.
- Объекти парсшударо бо ҳамон схема дар рамзи худатон тасдиқ кунед, масалан бо китобхонаи JSON Schema, Pydantic ё Zod.
- Ҷавоби дароз метавонад пеш аз пурра шудани JSON ба охир расад. Ҷавоби бе streaming
finish_reason-ро танҳо ҳамчунstopёtool_callsхабар медиҳад, бинобар ин хатои парс нишона аст. Дубора пурсед, ё объекти хурдтарро талаб кунед.
Хатогиҳо
| Ҳолат | Навъ | Паём | Кай |
|---|---|---|---|
400 | invalid_request_error | <id> does not accept response_format | Модел ҳеҷ як ҳолатро қабул намекунад. |
400 | invalid_request_error | <id> does not accept response_format json_schema; use json_object | Модел json_object-ро қабул мекунад ва шумо json_schema фиристодед. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | response_format type надорад, ё объекти JSON нест. |
Ду ҷавоби 400 пеш аз он фиристода мешаванд, ки аз баланси шумо чизе гирифта шавад. Идораи хатогиҳо