Appearance
Response Healing 插件在非流式请求中自动验证并修复 LLM 返回的格式错误 JSON:可修复缺失括号、尾随逗号、无引号键名、Markdown 代码块包裹、文本前置等常见问题。需配合 response_format(json_schema 或 json_object)使用,在请求的 plugins 数组中加入 { "id": "response-healing" } 即可启用。
OpenRouter Response Healing 插件
Response Healing 插件自动验证并修复 LLM 返回的格式错误 JSON。当模型输出缺少括号、带尾随逗号、被 Markdown 包裹或夹杂文本时,该插件会尝试修复,让你始终拿到可直接解析的有效 JSON。
触发条件
插件在满足以下所有条件时激活:
- 非流式请求(
stream: false或不传stream) - 请求中包含
response_format,类型为json_schema或json_object plugins数组中包含{ "id": "response-healing" }
可修复的问题类型
| 问题类型 | 示例输入 | 修复结果 |
|---|---|---|
| 缺少闭合括号 | {"name": "Alice", "age": 30 | 补全 } |
| Markdown 代码块包裹 | ```json\n{"name": "Bob"}\n``` | 提取纯 JSON |
| 文本前置 + JSON | Here is the result: {"name": "Charlie"} | 提取 JSON 部分 |
| 尾随逗号 | {"name": "David", "age": 35,} | 移除尾随逗号 |
| 无引号键名 | {name: "Eve", age: 40} | 转换为标准 JSON |
完整使用示例
javascript
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-4o',
messages: [
{
role: 'user',
content: '生成一个包含名称、价格和描述的商品信息'
}
],
response_format: {
type: 'json_schema',
json_schema: {
name: 'Product',
schema: {
type: 'object',
properties: {
name: { type: 'string', description: '商品名称' },
price: { type: 'number', description: '价格(USD)' },
description: { type: 'string', description: '商品描述' }
},
required: ['name', 'price']
}
}
},
plugins: [
{ id: 'response-healing' }
]
}),
});
const data = await response.json();
const product = JSON.parse(data.choices[0].message.content);
console.log(product.name, product.price);已知限制
仅支持非流式请求:Response Healing 不适用于流式(stream: true)请求。
无法修复所有 JSON 错误:若响应被 max_tokens 截断导致内容不完整,插件无法修复——截断的 JSON 在结构上无法还原。
常见问题
Q: 同时使用 json_schema 和 Response Healing,哪种更可靠?
A: 两者互补。json_schema 通过约束模型输出格式来预防格式错误;Response Healing 在格式错误已经发生后进行修复。建议同时使用,特别是对输出格式质量参差不齐的模型。
Q: Response Healing 会影响响应内容吗?
A: 不会改变 JSON 的语义内容,只修复语法层面的格式问题(如补全括号、移除多余逗号等)。若修复后仍无法得到有效 JSON,会返回原始响应。
Q: 流式请求有没有类似功能?
A: 目前 Response Healing 仅支持非流式请求。流式场景建议在客户端自行处理 JSON 修复逻辑,或选用对结构化输出支持更好的模型。