Spaces:
Runtime error
Runtime error
Fix: 修复 RecommendationAgent JSON解析失败问题
Browse files- 添加 import re
- 新增 _parse_json_with_fallback() 方法(4级降级策略)
- 新增 _repair_json() 方法(修复常见JSON错误)
- 新增 _balance_brackets() 方法(自动补全括号)
- 更新 _parse_response() 使用强大的JSON解析
- 增强错误处理和日志记录
修复内容:
1. 处理 'Unterminated string' 错误
2. 处理 'Unexpected end of input' 错误
3. 使用 json5 作为首选解析器(更宽容)
4. 解析失败时返回详细错误信息便于调试
21 unmodified lines22232425262728338 unmodified lines36736836936937037037137237337414 unmodified lines38939039139139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954021 unmodified lines
import jsonimport loggingimport refrom typing import Dict, Any, List, Optionalfrom pathlib import Pathimport sys338 unmodified lines else: json_str = response_text.strip() # 解析JSON result = json.loads(json_str) # 使用强大的JSON解析(带多种降级策略) result = self._parse_json_with_fallback(json_str, response_text) # 提取指标列表并转换为 Indicator 对象 indicators_list = result.get("indicators", [])14 unmodified lines "recommendation_type": "ai_generated" } except json.JSONDecodeError as e: except Exception as e: # JSON解析失败,记录错误并返回空结果 logger.error(f"Failed to parse JSON from response: {e}") logger.error(f"Response text (first 500 chars): {response_text[:500]}") return { "indicators": [], "total_count": 0, "recommendation_type": "ai_generated" } def _parse_json_with_fallback(self, json_str: str, response_text: str) -> Dict[str, Any]: """ 使用多种策略解析JSON(复用 ModelingAgent 的逻辑) 解析策略(按优先级尝试): 1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等) 2. json.loads() - 标准JSON解析 3. 修复常见错误后重试 4. 返回原始文本作为降级 参数: json_str (str): 提取的JSON字符串 response_text (str): 原始响应文本(用于降级) 返回: Dict[str, Any]: 解析后的字典 """ # 策略1:使用 json5 解析(最宽容) try: import json5 result = json5.loads(json_str) logger.info("✅ JSON5解析成功 (RecommendationAgent)") return result except Exception as e: logger.warning(f"⚠️ JSON5解析失败: {e}") # 策略2:标准 json.loads() try: result = json.loads(json_str) logger.info("✅ 标准JSON解析成功 (RecommendationAgent)") return result except json.JSONDecodeError as e: logger.warning(f"⚠️ 标准JSON解析失败: {e}") # 策略3:修复常见错误后重试 repaired = self._repair_json(json_str, e) if repaired: try: result = json.loads(repaired) logger.info("✅ 修复后JSON解析成功 (RecommendationAgent)") return result except: logger.warning("⚠️ 修复后仍无法解析JSON") # 策略4:降级 - 尝试从原始文本中提取信息 logger.error("❌ 所有JSON解析策略均失败,返回空结果") logger.error(f"JSON string (first 300 chars): {json_str[:300]}") return {"indicators": []} def _repair_json(self, json_str: str, error: json.JSONDecodeError) -> Optional[str]: """ 修复LLM输出中常见的JSON错误 参数: json_str (str): 包含错误的JSON字符串 error (json.JSONDecodeError): 解析错误对象 返回: Optional[str]: 修复后的JSON字符串,如果无法修复则返回None """ if not json_str: return None repaired = json_str # 修复1:未终止的字符串 if "Unterminated string" in str(error) or "Unexpected end of input" in str(error): # 对于 "Unexpected end of input",尝试截断到最后一个完整对象 if "Unexpected end of input" in str(error): # 找到最后一个完整的 } 或 ] last_complete = max(repaired.rfind('}'), repaired.rfind(']')) if last_complete != -1: repaired = repaired[:last_complete + 1] # 平衡括号 repaired = self._balance_brackets(repaired) return repaired if hasattr(error, 'pos') and error.pos: pos = error.pos if pos < len(repaired): repaired = repaired[:pos] + '"' # 修复2:尾随逗号 repaired = re.sub(r',\s*([}\]])', r'\1', repaired) # 修复3:缺失的闭合括号 repaired = self._balance_brackets(repaired) return repaired if repaired != json_str else None @staticmethod def _balance_brackets(json_str: str) -> str: """ 平衡JSON字符串中的括号 """ if not json_str: return json_str stack = [] in_string = False escape_char = False for char in json_str: if escape_char: escape_char = False continue if char == '\\': escape_char = True continue if char == '"' and not in_string: in_string = True continue if in_string: if char == '"': in_string = False continue if char in '{[': stack.append(char) elif char in '}]': if stack: stack.pop() # 添加缺失的闭合括号 while stack: opening = stack.pop() if opening == '{': json_str += '}' elif opening == '[': json_str += ']' return json_str def recommend_indicator_set(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """ 推荐指标集的便捷方法agents/recommendation_agent.py+141-3