结构化输出
要求以 JSON 形式回答:任意 JSON 对象,或遵循你所发送 schema 的 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 schema | {"type": "json_schema", "json_schema": {"name": "…", "schema": {…}}} | 答案遵循你发送的 schema:它的键、类型和必填字段。 |
| 严格 | "strict": true | json_schema 的一个字段,而不是第三种模式。除非你发送 false,否则它为 true。 |
| 字段 | 类型 | 默认值 | 说明 | 适用模型 |
|---|---|---|---|---|
type | string | json_object 或 json_schema。在 response_format 中必填。text 会被接受,并给出普通文本答案。 | 所有支持该模式的模型 | |
json_schema.schema | object | 答案所遵循的 JSON Schema。只要 type 是 json_schema,就要发送它。 | 所有支持该模式的模型 | |
json_schema.name | string | schema 的标签,与 OpenAI 格式相同。 | 托管开源权重模型 | |
json_schema.strict | boolean | true | 答案是否必须严格遵循 schema。Shannon 模型对每个 schema 都按严格模式应用。 | 托管开源权重模型 |
JSON 对象模式不需要 schema。请在 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-*) | 是 | 是 |
| 托管开源权重模型,下面列出的除外 | 是 | 是 |
Laguna-S-2.1-W4A16-AUTOROUND-REAP | — | — |
inkling-W4A16-AUTOROUND-REAP | 是 | — |
GET /v1/models 对每个 id 也报告同样的信息:所有模型的 capabilities.json_schema,以及托管开源权重模型的 capabilities.response_format。 模型与定价
支持的 schema 关键字
模型能收到你的 schema 的哪些内容,取决于模型和端点:
| 模型 | /v1/chat/completions | /v1/responses |
|---|---|---|
| Shannon 模型 | 下面的关键字子集,按严格模式应用。 | 按你发送的原样使用 schema,按严格模式应用。 |
| 托管开源权重模型 | 按你发送的原样使用 schema。除非你发送,否则 strict 为 true。 | 按你发送的原样使用 schema。除非你发送,否则 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 | 从 schema 顶层的 $defs 或 definitions 解析。写在 $ref 旁边的关键字,例如 description,会被保留。没有对应定义的引用按 {"type": "object"} 处理。 |
allOf | 各成员会合并为一个 schema。两个成员设置了相同的关键字时,以后者为准。 |
oneOf | 按 anyOf 处理。 |
| 引用自身的 schema | 展开到 24 层。更深的层级按 {"type": "object"} 处理。 |
| 子集之外 | 其他所有关键字,例如 additionalProperties、const、multipleOf、uniqueItems、exclusiveMinimum、exclusiveMaximum、patternProperties、prefixItems、minProperties、maxProperties、not 以及 if / then / else。它们不属于模型收到的 schema。 |
在 /v1/responses 上,改用 text.format 字段来表示
/v1/responses 把同样的请求写作 text.format。schema 直接放在 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 是 message 项的 output_text 部分的 text:
{
"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 上:用工具充当 schema
Messages 格式没有结构化输出字段。若要从这些模型得到 JSON,请用同一个密钥调用 /v1/chat/completions 或 /v1/responses。
若要继续使用 /v1/messages,请把对象描述为一个工具:把你的 schema 放在 input_schema 中,并在 tool_choice 中指定该工具的名称。tool_use 块的 input 就是你的对象,且已经解析好。指定名称的 tool_choice 由托管开源权重模型应用。
{
"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 是一个字符串。回复中没有旁边附带的已解析对象:请对
message.content运行你的 JSON 解析器。 - 使用
stream: true时,JSON 以delta.content片段的形式到达。请在流结束后拼接并解析一次;单独的一段不是有效的 JSON。 - 托管开源权重模型回答
response_format请求时不带推理文本:reasoning_content为null。
检查你收到的内容
schema 引导模型如何书写。API 不会将完成的答案与你的 schema 比对,因此最终检查由你的代码完成:
- 在错误处理程序中解析,就像顶部的示例那样。
- 在你自己的代码中用同一个 schema 校验解析后的对象,例如使用 JSON Schema 库、Pydantic 或 Zod。
- 较长的答案可能在 JSON 完整之前就结束。非流式回复的
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 回复会在从你的余额中扣除任何内容之前发出。 错误处理