Files
offerpai_python_ai/app/tool/json_helper.py
T
2026-04-23 17:49:06 +08:00

16 lines
459 B
Python

"""AI 输出 JSON 解析工具
将 LLM 返回的可能带 markdown 代码块包裹的文本解析为 Python 对象。
"""
import re
from json_repair import repair_json
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)
return repair_json(cleaned, return_objects=True)