跳到主要内容

结构化输出

OpenRouter 支持兼容模型的结构化输出,确保响应遵循特定的 JSON Schema 格式。当您需要一致、格式良好且能够被应用程序可靠解析的响应时,此功能尤其有用。

概述

结构化输出允许您:

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

使用结构化输出

要使用结构化输出,请在请求中包含 response_format 参数,并将 type 设置为 json_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
}
}
}
}

该模型将使用严格遵循您的模式的 JSON 对象进行响应:

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

模型支持

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

您可以在模型页面找到支持结构化输出的模型列表

  • OpenAI 模型(GPT-4o 及更高版本) 文档
  • 所有 Fireworks 提供的模型 文档

为确保您选择的模型支持结构化输出:

  1. 模型页面查看模型支持的参数
  2. 在您的提供商首选项中设置 require_parameters: true(请参阅提供商路由
  3. 在必需参数中包含 response_format 并设置 type: json_schema

最佳实践

  1. 添加描述:为您的模式属性添加清晰的描述,以指导模型。

  2. 使用严格模式:始终设置 strict: true,以确保模型完全遵循您的模式。

示例实现

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

const response = await fetch('https://openrouter.co/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: 'Bearer <OPENROUTER_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,该部分完成后将形成与您的模式匹配的有效响应。

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

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

错误处理

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

  1. 模型不支持结构化输出:请求将失败,并显示错误,表明不支持
  2. 无效的模式:如果您的 JSON 模式无效,模型将返回错误