Files
offerpai_python_ai/app/tool/json_helper.py
T
2026-04-23 18:23:44 +08:00

33 lines
1.4 KiB
Python

"""AI 输出 JSON 解析工具
将 LLM 返回的可能带 markdown 代码块、思考标签等包裹的文本解析为 Python 对象。
"""
import re
from json_repair import repair_json
# 匹配 <think>任意内容</think>,用于剥离 DeepSeek R1 等推理模型的思考过程
# re.DOTALL 让 . 匹配换行,re.IGNORECASE 忽略大小写
# .*? 非贪婪匹配,避免跨多个 think 标签
_THINK_RE = re.compile(r"<think>.*?</think>", 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 代码块,容错处理"""
# 1. 去掉 <think>...</think> 思考内容
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)