Skip to content

DeepSeek 嵌套 JSON 输出被截断未正常关闭

问题

要求 DeepSeek 输出完整 JSON 且允许截断但必须保持合法格式时,模型在达到 token 限制后直接中断,输出的 JSON 缺少关闭括号,导致解析失败:

json
// 截断后的非法输出示例
{
  "items": [
    {"id": 1, "data": "完整内容"},
    {"id": 2, "data": "被截断的内

解决方案

方案一:启用流式输出 + 手动修复

python
import json

def collect_and_fix_json(stream):
    text = ""
    for chunk in stream:
        delta = chunk.choices[0].delta.content or ""
        text += delta
    
    # 尝试修复截断的 JSON
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        # 简单修复:补全缺失的括号
        depth_curly = text.count('{') - text.count('}')
        depth_square = text.count('[') - text.count(']')
        text += ']' * depth_square + '}' * depth_curly
        return json.loads(text)

方案二:使用 jsonrepair 库

bash
npm install jsonrepair
typescript
import { jsonrepair } from 'jsonrepair';

const rawOutput = await getDeepSeekOutput();
const fixed = jsonrepair(rawOutput);
const parsed = JSON.parse(fixed);

方案三:分批次处理大 JSON

如果 JSON 很大(超过 4K tokens),将任务拆分为多次请求,每次处理 JSON 的一部分,避免截断。

根本原因:DeepSeek 在达到 max_tokens 时强制截断,不会像某些模型一样尝试优雅关闭 JSON 结构。

来源Issue #913 - deepseek-ai/DeepSeek-V3