Structured Outputs
从模型返回结构化数据
原文链接:https://openrouter.ai/docs/guides/features/structured-outputs
OpenRouter 支持兼容模型的 structured outputs,确保响应遵循特定的 JSON Schema 格式。当你需要一致的、可类型安全且应用可可靠解析的格式良好响应时,此功能特别有用。
概述
Structured outputs 允许你:
- 对模型响应强制执行特定的 JSON Schema 验证
- 获得一致的、类型安全的输出
- 避免解析错误和 hallucinated 字段
- 简化应用程序中的响应处理
使用 Structured Outputs
要使用 structured outputs,请在请求中包含 response_format 参数,将 type 设置为 json_schema,并包含包含你的 schema 的 json_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"
}
模型支持
Structured outputs 由精选模型支持。
你可以在 models page 找到支持 structured outputs 的模型列表。
- OpenAI 模型(GPT-4o 及更高版本)Docs
- Google Gemini 模型 Docs
- Anthropic 模型(Sonnet 4.5、Opus 4.1+)Docs
- 大多数开源模型
- 所有 Fireworks 提供的模型 Docs
要确保你选择的模型支持 structured outputs:
- 在 models page 检查模型的 supported parameters
- 在 provider preferences 中设置
require_parameters: true(请参阅 Provider Routing) - 在 required parameters 中包含
response_format并设置type: json_schema
最佳实践
- 包含描述:为 schema 属性添加清晰的描述以指导模型
- 使用 strict 模式:始终设置
strict: true以确保模型精确遵循你的 schema
示例实现
以下是使用 Fetch API 的完整示例:
import { OpenRouter } from '@openrouter/sdk';
const openRouter = new OpenRouter({
apiKey: '{{API_KEY_REF}}',
});
const response = await openRouter.chat.send({
model: '{{MODEL}}',
messages: [
{ role: 'user', content: 'What is the weather like in London?' },
],
responseFormat: {
type: 'json_schema',
jsonSchema: {
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,
},
},
},
stream: false,
});
const weatherInfo = response.choices[0].message.content;
带 Structured Outputs 的流式传输
Structured outputs 也支持流式响应。模型将流式传输有效的部分 JSON,当完整时,形成符合你 schema 的有效响应。
要启用带 structured outputs 的流式传输,只需在请求中添加 stream: true:
{
"stream": true,
"response_format": {
"type": "json_schema",
// ... rest of your schema
}
}
错误处理
使用 structured outputs 时,你可能会遇到以下场景:
- 模型不支持 structured outputs:请求将失败并显示错误,指示缺乏支持
- 无效的 schema:如果你的 JSON Schema 无效,模型将返回错误
Response Healing
对于使用 response_format 且 type: "json_schema" 的非流式请求,你可以启用 Response Healing 插件来降低模型返回不完美格式时产生无效 JSON 的风险。在 Response Healing 文档 中了解更多。