Skip to content

OpenRouter 支持通过 response_format.json_schema 强制模型返回符合指定 JSON Schema 的响应,消除字段幻觉和格式不一致问题。本页说明如何配置 schema、启用 strict 模式、查找支持结构化输出的模型,以及流式传输和错误处理的注意事项。

OpenRouter 结构化输出

结构化输出让模型的响应严格遵守你定义的 JSON Schema,避免字段幻觉和解析错误,特别适合需要可靠数据提取的场景。

基本用法

在请求中添加 response_format 参数:

json
{
  "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:

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

TypeScript SDK 示例

typescript
import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({ apiKey: '<OPENROUTER_API_KEY>' });

const response = await openRouter.chat.send({
  model: 'openai/gpt-4o',
  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' },
        },
        required: ['location', 'temperature', 'conditions'],
        additionalProperties: false,
      },
    },
  },
  stream: false,
});

const weatherInfo = JSON.parse(response.choices[0].message.content);
console.log(weatherInfo.temperature); // 18

支持的模型

提供商模型
OpenAIGPT-4o 及以上版本
GoogleGemini 系列
AnthropicSonnet 4.5、Opus 4.1+
开源模型大多数支持
Fireworks全部模型

通过 模型页面 筛选支持 structured_outputs 的模型。

最佳实践

添加字段描述:为 schema 中的每个属性添加 description,帮助模型理解预期内容,减少字段误用。

启用 strict 模式:始终设置 strict: true,确保模型严格遵循 schema,不会添加额外字段。

结合 require_parameters:使用 provider.require_parameters: true 确保只路由到真正支持结构化输出的提供商。

流式传输支持

结构化输出与流式传输兼容。流式模式下,模型会逐步流出有效的 JSON 片段,完整接收后可解析为符合 schema 的对象:

json
{
  "stream": true,
  "response_format": {
    "type": "json_schema",
    // ... 同上
  }
}

Response Healing 容错

对于非流式请求,如果模型生成了不完美的 JSON 格式,可以启用 Response Healing 插件自动修复:

json
{
  "plugins": [{ "id": "response-healing" }],
  "response_format": { "type": "json_schema", "json_schema": { ... } }
}

错误处理

场景结果
模型不支持结构化输出请求失败,返回错误
schema 定义无效模型返回格式错误信息
模型无法满足 schema可能返回错误或不完整 JSON

常见问题

Q: response_format.type: "json_object"json_schema 有什么区别?

A: json_object 只保证返回有效 JSON,但字段内容由模型自由发挥;json_schema 会严格约束字段名、类型和必填项,适合需要固定格式的场景。

Q: 能用结构化输出提取文档中的数据吗?

A: 是主要使用场景之一。定义好数据结构的 schema,在消息中提供文档内容,模型会按 schema 提取并填充字段。

Q: 结构化输出和工具调用有什么区别?

A: 用途不同。结构化输出用于控制模型最终回复的格式;工具调用用于让模型请求执行外部操作。如果只是想要结构化数据,用 response_format 更直接。