Strukturitaj eligoj
Petu la respondon kiel JSON: ajna JSON-objekto, aŭ JSON, kiu sekvas skemon, kiun vi sendas. Uzu ĝin kiam programo, ne homo, legas la respondon.
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"]
}
}
}
}' La JSON estas la teksto de la respondo, en 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}
}
} La reĝimoj de response_format
response_format estas kampo de /v1/chat/completions. Sen ĝi la respondo estas ordinara teksto.
| Reĝimo | Valoro | Kion vi ricevas |
|---|---|---|
| JSON-objekto | {"type": "json_object"} | La respondo estas JSON sen preskribita formo. Diru en la prompt, kiujn ŝlosilojn vi volas. |
| JSON-skemo | {"type": "json_schema", "json_schema": {"name": "…", "schema": {…}}} | La respondo sekvas la skemon, kiun vi sendas: ĝiajn ŝlosilojn, tipojn kaj devigajn kampojn. |
| Strikta | "strict": true | Kampo de json_schema, ne tria reĝimo. Ĝi estas true, krom se vi sendas false. |
| Kampo | Tipo | Defaŭlto | Priskribo | Aplikata de |
|---|---|---|---|---|
type | string | json_object aŭ json_schema. Deviga ene de response_format. text estas akceptata kaj donas ordinaran tekstan respondon. | Ĉiu modelo, kiu akceptas la reĝimon | |
json_schema.schema | object | La JSON Schema, kiun la respondo sekvas. Sendu ĝin kiam ajn type estas json_schema. | Ĉiu modelo, kiu akceptas la reĝimon | |
json_schema.name | string | Etikedo por la skemo, kiel en la formato OpenAI. | Gastigitaj malfermpezaj modeloj | |
json_schema.strict | boolean | true | Ĉu la respondo devas sekvi la skemon precize. La Shannon-modeloj aplikas ĉiun skemon kiel strikta. | Gastigitaj malfermpezaj modeloj |
La reĝimo JSON-objekto ne bezonas skemon. Nomu la ŝlosilojn en la 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"}
} Subteno laŭ modelo
| Modelo | json_object | json_schema |
|---|---|---|
Ĉiu Shannon-modelo (shannon-*) | Jes | Jes |
| Gastigitaj malfermpezaj modeloj, krom tiuj nomitaj sube | Jes | Jes |
Laguna-S-2.1-W4A16-AUTOROUND-REAP | — | — |
inkling-W4A16-AUTOROUND-REAP | Jes | — |
GET /v1/models raportas la samon por id: capabilities.json_schema ĉe ĉiu modelo, kaj capabilities.response_format ĉe la gastigitaj malfermpezaj modeloj. Modeloj kaj prezoj
Subtenataj ŝlosilvortoj de skemo
Kion modelo ricevas el via skemo dependas de la modelo kaj de la endpoint:
| Modeloj | /v1/chat/completions | /v1/responses |
|---|---|---|
| Shannon-modeloj | La subaro de ŝlosilvortoj sube, aplikata kiel strikta. | La skemo tia, kia vi sendas ĝin, aplikata kiel strikta. |
| Gastigitaj malfermpezaj modeloj | La skemo tia, kia vi sendas ĝin. strict estas true, krom se vi sendas ĝin. | La skemo tia, kia vi sendas ĝin. strict estas true, krom se vi sendas ĝin. |
La subaro de ŝlosilvortoj de la Shannon-modeloj ĉe /v1/chat/completions:
| Ŝlosilvorto | Kiel ĝi estas legata |
|---|---|
| Legataj ŝlosilvortoj | type, format, title, description, nullable, enum, items, properties, required, minItems, maxItems, minimum, maximum, minLength, maxLength, pattern, anyOf, default |
$ref | Solvata el $defs aŭ definitions ĉe la supra nivelo de la skemo. Ŝlosilvortoj skribitaj apud la $ref, kiel description, estas konservataj. Referenco sen kongrua difino estas legata kiel {"type": "object"}. |
allOf | La membroj estas kunfanditaj en unu skemon. Kie du membroj agordas la saman ŝlosilvorton, validas la pli posta. |
oneOf | Legata kiel anyOf. |
| Skemoj, kiuj referencas sin mem | Etendataj ĝis 24 niveloj. Pli profunda nivelo estas legata kiel {"type": "object"}. |
| Ekster la subaro | Ĉiu alia ŝlosilvorto, ekzemple additionalProperties, const, multipleOf, uniqueItems, exclusiveMinimum, exclusiveMaximum, patternProperties, prefixItems, minProperties, maxProperties, not kaj if / then / else. Ĉi tiuj ne estas parto de la skemo, kiun la modelo ricevas. |
Ĉe /v1/responses: text.format
/v1/responses literumas la saman peton kiel text.format. La skemo troviĝas rekte en format, apud name kaj strict, ne sub ŝlosilo json_schema. Por la reĝimo JSON-objekto sendu {"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"]
}
}
}
} La JSON estas la text de la parto output_text de la ero message:
{
"output": [
{
"id": "msg_7e1d3c5b9a2f4d6e8c0b1a3f5e7d9c2b",
"type": "message",
"role": "assistant",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
"annotations": []
}
]
}
]
} Subteno laŭ modelo kaj la eraroj estas samaj kiel ĉe /v1/chat/completions. Responses API
Ĉe /v1/messages: ilo kiel la skemo
La formato Messages ne havas kampon por strukturita eligo. Por JSON el la samaj modeloj, vokas /v1/chat/completions aŭ /v1/responses per la sama ŝlosilo.
Por resti ĉe /v1/messages, priskribu la objekton kiel ilon: metu vian skemon en input_schema kaj nomu la ilon en tool_choice. La input de la bloko tool_use tiam estas via objekto, jam analizita. Nomitan tool_choice aplikas la gastigitaj malfermpezaj modeloj.
{
"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"}
}
]
} Kontrolu, ke stop_reason estas tool_use antaŭ ol legi la blokon. Funkci-alvokoj
Kiel la JSON alvenas
- La JSON estas ĉeno. La respondo ne havas analizitan objekton apud ĝi: ruligu vian JSON-analizilon sur
message.content. - Kun
stream: truela JSON alvenas en pecoj dedelta.content. Kunigu ilin kaj analizu unufoje kiam la fluo finiĝis; peco sola ne estas valida JSON. - Gastigita malfermpeza modelo respondas peton
response_formatsen raciuma teksto:reasoning_contentestasnull.
Kontrolu tion, kion vi ricevas
La skemo gvidas kiel la modelo skribas. La API ne komparas la finitan respondon kun via skemo, do via kodo faras la finan kontrolon:
- Analizu ene de traktilo de eraroj, kiel faras la ekzemplo supre.
- Validigu la analizitan objekton per la sama skemo en via propra kodo, ekzemple per biblioteko de JSON Schema, Pydantic aŭ Zod.
- Longa respondo povas finiĝi antaŭ ol la JSON estas kompleta. Ne fluata respondo raportas
finish_reasonnur kielstopaŭtool_calls, do analiza eraro estas la signalo. Demandu denove, aŭ petu pli malgrandan objekton.
Eraroj
| Stato | Tipo | Mesaĝo | Kiam |
|---|---|---|---|
400 | invalid_request_error | <id> does not accept response_format | La modelo akceptas neniun el la du reĝimoj. |
400 | invalid_request_error | <id> does not accept response_format json_schema; use json_object | La modelo akceptas json_object kaj vi sendis json_schema. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | response_format ne havas type, aŭ ne estas JSON-objekto. |
La du respondoj 400 estas senditaj antaŭ ol io estas prenita el via saldo. Erarotraktado