context_helper.py 949 B

12345678910111213141516171819202122232425
  1. def safe_context_param(context_str: str) -> str:
  2. """确保上下文参数可以安全地序列化为JSON"""
  3. if not context_str:
  4. return ""
  5. # 移除ECharts代码块,这些对上下文没有帮助且容易导致格式错误
  6. import re
  7. # 移除 ```echarts 代码块
  8. cleaned = re.sub(r"```echarts[\s\S]*?```", "", context_str)
  9. # 移除其他代码块
  10. cleaned = re.sub(r"```[\s\S]*?```", "", cleaned)
  11. # 清理可能导致JSON解析问题的字符
  12. cleaned = str(cleaned).replace('"', "'").replace("\\", "/").strip()
  13. # 移除多余的空行和空格
  14. cleaned = re.sub(r"\n\s*\n", "\n", cleaned) # 移除连续空行
  15. cleaned = re.sub(r" +", " ", cleaned) # 合并多个空格
  16. # 限制上下文长度,避免过长导致序列化问题
  17. max_length = 2000
  18. if len(cleaned) > max_length:
  19. cleaned = cleaned[:max_length] + "... [上下文已截断]"
  20. return cleaned.strip()