跳到主要内容

结构化输出

Knox Chat 支持兼容模型的结构化输出功能,确保响应严格遵循指定的 JSON Schema 格式。当你需要获得一致、格式规范的响应以便应用程序可靠解析时,此功能尤为实用。

概述

结构化输出可以帮助你:

  • 对模型响应强制执行特定的 JSON Schema 验证
  • 获得一致的、类型安全的输出
  • 避免解析错误和虚假字段
  • 简化应用程序中的响应处理

使用结构化输出

要使用结构化输出,请在请求中包含 response_format 参数,将 type 设置为 json_schema,并在 json_schema 对象中定义你的 schema:

{
"messages": [
{ "role": "user", "content": "What's the weather like in London?" }
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "weather",
"strict": true,
"schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City or location name"
},
"temperature": {
"type": "number",
"description": "Temperature in Celsius"
},
"conditions": {
"type": "string",
"description": "Weather conditions description"
}
},
"required": ["location", "temperature", "conditions"],
"additionalProperties": false
}
}
}
}

模型将返回严格遵循你的 schema 的 JSON 对象:

{
"location": "London",
"temperature": 18,
"conditions": "Partly cloudy with light drizzle"
}

模型支持

支持结构化输出的精选模型

你可以在模型页面查看支持结构化输出的模型列表。

  • OpenAI 模型(GPT-5.2 及以上)文档
  • Fireworks 提供的所有模型 文档

要确认你选择的模型是否支持结构化输出:

  1. 模型页面查看该模型支持的参数
  2. 在 provider preferences 中设置 require_parameters: true(参见供应商路由
  3. 在所需参数中包含 response_format 并设置 type: json_schema

最佳实践

  1. 添加描述信息:为 schema 属性提供清晰的描述,以引导模型生成正确的输出。

  2. 使用严格模式:始终设置 strict: true,确保模型严格遵循你的 schema。

示例实现

以下是使用 Fetch API 的完整示例:

const response = await fetch('https://api.knox.chat/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: 'Bearer <KNOXCHAT_API_KEY>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-4',
messages: [
{ role: 'user', content: 'What is the weather like in London?' },
],
response_format: {
type: 'json_schema',
json_schema: {
name: 'weather',
strict: true,
schema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City or location name',
},
temperature: {
type: 'number',
description: 'Temperature in Celsius',
},
conditions: {
type: 'string',
description: 'Weather conditions description',
},
},
required: ['location', 'temperature', 'conditions'],
additionalProperties: false,
},
},
},
}),
});

const data = await response.json();
const weatherInfo = data.choices[0].message.content;

结构化流式输出

流式响应同样支持结构化输出。模型会传输有效的部分 JSON 数据,完成后将构成符合你的 schema 的完整响应。

要启用结构化输出的流式传输,只需在请求中添加 stream: true

{
"stream": true,
"response_format": {
"type": "json_schema",
// ... rest of your schema
}
}

错误处理

使用结构化输出时,你可能会遇到以下情况:

  1. 模型不支持结构化输出:请求将失败并返回不支持该功能的错误信息。
  2. 无效的 schema:如果你的 JSON schema 无效,模型将返回错误。