diff --git a/app/tool/json_helper.py b/app/tool/json_helper.py index 1ea07f5..b56e442 100644 --- a/app/tool/json_helper.py +++ b/app/tool/json_helper.py @@ -1,15 +1,32 @@ """AI 输出 JSON 解析工具 -将 LLM 返回的可能带 markdown 代码块包裹的文本解析为 Python 对象。 +将 LLM 返回的可能带 markdown 代码块、思考标签等包裹的文本解析为 Python 对象。 """ import re from json_repair import repair_json +# 匹配 任意内容,用于剥离 DeepSeek R1 等推理模型的思考过程 +# re.DOTALL 让 . 匹配换行,re.IGNORECASE 忽略大小写 +# .*? 非贪婪匹配,避免跨多个 think 标签 +_THINK_RE = re.compile(r".*?", re.DOTALL | re.IGNORECASE) + +# 匹配 ```json ... ``` 代码块,提取中间的 JSON 内容 +# (?:json\w*)? — 可选的语言标记,兼容 json / JSON / jsonc 等,也兼容无标记的裸 ``` +# \s*\n? — 跳过语言标记后的空白和换行 +# (.*?) — 非贪婪捕获代码块内容(第1组) +# \n?\s*``` — 匹配结尾的 ``` +_CODE_BLOCK_RE = re.compile(r"```(?:json\w*)?\s*\n?(.*?)\n?\s*```", re.DOTALL | re.IGNORECASE) + def parse_llm_json(text: str): - """解析 AI 输出的 JSON,自动去除 markdown 代码块包裹,容错处理""" - cleaned = re.sub(r"^```(?:json)?\s*\n?", "", text.strip()) - cleaned = re.sub(r"\n?```\s*$", "", cleaned) + """解析 AI 输出的 JSON,自动去除思考标签、markdown 代码块,容错处理""" + # 1. 去掉 ... 思考内容 + cleaned = _THINK_RE.sub("", text).strip() + # 2. 如果有 ```json ... ``` 代码块,只取代码块里的内容 + match = _CODE_BLOCK_RE.search(cleaned) + if match: + cleaned = match.group(1).strip() + # 3. repair_json 容错解析:修复不规范的 JSON(多余逗号、缺引号等) return repair_json(cleaned, return_objects=True)