async def get_insight(self, prompt, required_feature=None): # 筛选出支持所需特征的提供商 candidates = [p for p in self.providers if (not required_feature or p['features'].get(required_feature))]
for p in candidates: result = await self._call_provider(p, prompt) if result: return result, p['name'] return None, None 当用户在前端选择“联网搜索”时,系统自动跳过DeepSeek,优先调用 Moonshot 如果Moonshot超时,就降级到Gemma(此时联网功能丢失,但是至少能给出基础解读)。 --- ➢2 防御性JSON解析的三层护甲 大模型返回JSON的稳定性堪比“抽盲盒” 我设计了三层解析护甲,这确保了即使AI返回了“半成品垃圾”,前端依然能展示有效信息 第一层:标准JSON解析 python 蟒 try: return json.loads(response) except json.JSONDecodeError: pass 第二层:清洗Markdown代码块标记 这是最常见的污染形式——AI会把JSON包裹在 ```` ```json ... ``` ```` 中 python 蟒 cleaned = response.strip() if cleaned.startswith('json'): cleaned = cleaned[7:] if cleaned.endswith(''): cleaned = cleaned[:-3] cleaned = cleaned.strip()
try: return json.loads(cleaned) except: pass 第三层:正则暴力提取 如果前两层都失败,说明 AI 返回的可能是纯文本或格式完全损坏的JSON。 此时我用正则直接提取关键字段: python 蟒 import re