Spaces:
Runtime error
Runtime error
fix: 增强JSON解析鲁棒性,修复截断/缺失逗号等问题
Browse files- 改进_parse_json_with_fallback:json5失败时立即尝试修复截断的JSON
- 新增支持:直接解析response_text、修复缺失的逗号
- 改进_truncate_and_close_json:更健壮的截断修复逻辑
- 改进_repair_json:处理缺失逗号、未终止字符串等常见LLM输出错误
- 应用到modeling_agent.py和recommendation_agent.py
Files changed (2)
- agents/modeling_agent.py+106-29
- agents/recommendation_agent.py+200-28
351 unmodified lines3523533543553563573583593603613623633646 unmodified lines3713723733743753763773781 unmodified line3803813823833843853863873881 unmodified line39039139239339439539610 unmodified lines4074084094104114124134148 unmodified lines42342442542642742842943043143243343443543643743843944044144244344444544644744844945045145216 unmodified lines4694704714724734744754764774784794804814824834844854864874884894904914924939 unmodified lines503504505506507508509510511512513514515516351 unmodified lines解析策略(按优先级尝试):1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等)2. json.loads() - 标准JSON解析3. 修复常见错误后重试4. 返回原始文本作为markdown降级参数:json_str (str): 提取的JSON字符串response_text (str): 原始响应文本(用于降级)返回:Dict[str, Any]: 解析后的字典,如果所有策略都失败则返回降级结果6 unmodified linesreturn resultexcept Exception as e:logger.warning(f"⚠️ JSON5解析失败: {e}")# 策略2:标准 json.loads()try:result = json.loads(json_str)logger.info("✅ 标准JSON解析成功")1 unmodified lineexcept json.JSONDecodeError as e:logger.warning(f"⚠️ 标准JSON解析失败: {e}")# 策略3:修复常见错误后重试repaired = ModelingAgent._repair_json(json_str, e)if repaired:try:result = json.loads(repaired)logger.info("✅ 修复后JSON解析成功")1 unmodified lineexcept:logger.warning("⚠️ 修复后仍无法解析JSON")# 策略4:降级 - 返回原始文本作为markdownlogger.error("❌ 所有JSON解析策略均失败,返回原始文本")return {"markdown": response_text,10 unmodified lines1. 未终止的字符串 - 在错误位置添加引号2. 意外的输入结束 - 截断到最后一个完整对象3. 尾随逗号 - 移除对象/数组末尾的逗号4. 缺失的括号 - 自动补全5. 单引号 - 转换为双引号参数:json_str (str): 包含错误的JSON字符串8 unmodified linesrepaired = json_str.strip()# 修复0:如果是 "Unexpected end of input" 或类似截断错误if error and "Unexpected end of input" in str(error):logger.warning("⚠️ 检测到JSON输入意外结束,尝试截断修复...")# 策略:找到最后一个完整的对象/数组,截断并关闭repaired = ModelingAgent._truncate_and_close_json(repaired)if repaired:return repaired# 修复1:未终止的字符串if error and hasattr(error, 'pos') and error.pos:pos = error.posif pos < len(repaired):# 在错误位置添加引号repaired = repaired[:pos] + '"'# 修复2:尾随逗号(在 } 或 ] 前)repaired = re.sub(r',\s*([}\]])', r'\1', repaired)# 修复3:缺失的闭合括号repaired = ModelingAgent._balance_brackets(repaired)# 修复4:将单引号键名转换为双引号repaired = re.sub(r"([{,]\s*)'([^']*)'\s*:", r'\1"\2":', repaired)# 修复5:移除注释(JSON不支持注释,但LLM可能会加)repaired = re.sub(r'//[^\n]*', '', repaired)repaired = re.sub(r'/\*.*?\*/', '', repaired, flags=re.DOTALL)16 unmodified linesif not json_str:return None# 找到最后一个完整的顶级键或对象# 对于批量处理,我们尝试保留完整的 schemes 数组# 策略1:尝试找到 "schemes": [ 并提取完整的数组元素schemes_match = re.search(r'"schemes"\s*:\s*\[', json_str)if schemes_match:# 找到 schemes 数组的开始位置array_start = schemes_match.end()# 尝试解析数组中完整的对象complete_objects = []pos = array_startwhile pos < len(json_str):# 查找对象的开始obj_start = json_str.find('{', pos)if obj_start == -1:break# 尝试提取这个对象obj_str = ModelingAgent._extract_complete_object(json_str, obj_start)if obj_str:try:# 验证这个是完整的JSON对象9 unmodified lines# 重构JSONif complete_objects:schemes_str = ',\n'.join(complete_objects)repaired = json_str[:schemes_match.start()] + '{\n "schemes": [\n' + schemes_str + '\n ]\n}'logger.info(f"✅ 截断修复:保留了 {len(complete_objects)} 个完整方案")return repaired# 策略2:通用方法 - 找到最后一个完整的 } 或 ]last_complete = max(json_str.rfind('}'), json_str.rfind(']'))if last_complete != -1:truncated = json_str[:last_complete + 1]# 平衡括号repaired = ModelingAgent._balance_brackets(truncated)logger.info("✅ 通用截断修复完成")351 unmodified lines3523533543553563573583593603613623633643653666 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204211 unmodified line4234244254264274284294304311 unmodified line43343443543643743843910 unmodified lines4504514524534544554564574588 unmodified lines46746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150216 unmodified lines5195205215225235245255265275285295305315325335345355365375385395405415425435445455465475489 unmodified lines558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593351 unmodified lines解析策略(按优先级尝试):1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等)2. 如果json5失败且是截断错误,立即尝试修复并重新用json5解析3. 尝试直接解析 response_text(可能json_str提取有误)4. json.loads() - 标准JSON解析5. 修复常见错误后重试6. 返回原始文本作为markdown降级参数:json_str (str): 提取的JSON字符串response_text (str): 原始响应文本(用于降级和备用解析)返回:Dict[str, Any]: 解析后的字典,如果所有策略都失败则返回降级结果6 unmodified linesreturn resultexcept Exception as e:logger.warning(f"⚠️ JSON5解析失败: {e}")# 关键改进:如果json5失败是因为截断,立即尝试修复if "Unexpected end of input" in str(e) or "Unterminated string" in str(e):logger.warning("⚠️ 检测到JSON截断或未终止字符串,尝试修复...")# 尝试修复 json_strrepaired = ModelingAgent._truncate_and_close_json(json_str)if repaired:try:result = json5.loads(repaired)logger.info("✅ JSON5解析成功(修复json_str后)")return resultexcept Exception as e2:logger.warning(f"⚠️ 修复后JSON5仍无法解析: {e2}")# 也尝试修复整个 response_textrepaired_full = ModelingAgent._truncate_and_close_json(response_text)if repaired_full:try:# 尝试从修复后的全文提取JSONif "```json" in repaired_full:test_json = repaired_full.split("```json")[1].split("```")[0].strip()elif "```" in repaired_full:test_json = repaired_full.split("```")[1].split("```")[0].strip()else:test_json = repaired_full.strip()result = json5.loads(test_json)logger.info("✅ JSON5解析成功(修复response_text后)")return resultexcept Exception as e3:logger.warning(f"⚠️ 修复后全文JSON5仍无法解析: {e3}")# 策略2:尝试直接解析 response_text(可能之前的json_str提取有误)try:import json5result = json5.loads(response_text)logger.info("✅ 直接解析response_text成功(JSON5)")return resultexcept:pass# 策略3:标准 json.loads()try:result = json.loads(json_str)logger.info("✅ 标准JSON解析成功")1 unmodified lineexcept json.JSONDecodeError as e:logger.warning(f"⚠️ 标准JSON解析失败: {e}")# 策略4:修复常见错误后重试repaired = ModelingAgent._repair_json(json_str, e)if repaired and repaired != json_str.strip():try:result = json.loads(repaired)logger.info("✅ 修复后JSON解析成功")1 unmodified lineexcept:logger.warning("⚠️ 修复后仍无法解析JSON")# 策略5:降级 - 返回原始文本作为markdownlogger.error("❌ 所有JSON解析策略均失败,返回原始文本")return {"markdown": response_text,10 unmodified lines1. 未终止的字符串 - 在错误位置添加引号2. 意外的输入结束 - 截断到最后一个完整对象3. 尾随逗号 - 移除对象/数组末尾的逗号4. 缺失的逗号 - 在字段之间添加缺失的逗号5. 缺失的括号 - 自动补全6. 单引号 - 转换为双引号参数:json_str (str): 包含错误的JSON字符串8 unmodified linesrepaired = json_str.strip()# 修复0:如果是 "Unexpected end of input" 或类似截断错误if error and ("Unexpected end of input" in str(error) or "Unterminated string" in str(error)):logger.warning("⚠️ 检测到JSON输入意外结束,尝试截断修复...")# 策略:找到最后一个完整的对象/数组,截断并关闭truncated = ModelingAgent._truncate_and_close_json(repaired)if truncated:return truncated# 修复1:缺失的逗号(在 "value" 后面缺少逗号,如 "value""key" 或 "value"{)# 在引号关闭后如果跟着另一个引号或{,添加逗号repaired = re.sub(r'("\s*)\"\s*"', r'\1", "', repaired) # "value""key" -> "value", "key"repaired = re.sub(r'("\s*)\}\s*"', r'\1}, "', repaired) # "value"}"key" -> "value"}, "key"repaired = re.sub(r'("\s*)\]\s*"', r'\1"], "', repaired) # "value"]"key" -> "value"], "key"# 修复2:未终止的字符串if error and hasattr(error, 'pos') and error.pos:pos = error.posif pos < len(repaired):# 在错误位置添加引号repaired = repaired[:pos] + '"'# 修复3:尾随逗号(在 } 或 ] 前)repaired = re.sub(r',\s*([}\]])', r'\1', repaired)# 修复4:缺失的闭合括号repaired = ModelingAgent._balance_brackets(repaired)# 修复5:将单引号键名转换为双引号repaired = re.sub(r"([{,]\s*)'([^']*)'\s*:", r'\1"\2":', repaired)# 修复6:移除注释(JSON不支持注释,但LLM可能会加)repaired = re.sub(r'//[^\n]*', '', repaired)repaired = re.sub(r'/\*.*?\*/', '', repaired, flags=re.DOTALL)16 unmodified linesif not json_str:return None# 清理可能的markdown代码块标记cleaned = json_str.strip()if cleaned.startswith("```"):cleaned = re.sub(r'^```(json)?\n?', '', cleaned)if cleaned.endswith("```"):cleaned = cleaned.rsplit("```", 1)[0]cleaned = cleaned.strip()# 策略1:尝试找到 "schemes": [ 并提取完整的数组元素schemes_match = re.search(r'"schemes"\s*:\s*\[', cleaned)if schemes_match:# 找到 schemes 数组的开始位置array_start = schemes_match.end()# 尝试解析数组中完整的对象complete_objects = []pos = array_startwhile pos < len(cleaned):# 查找对象的开始obj_start = cleaned.find('{', pos)if obj_start == -1:break# 尝试提取这个对象obj_str = ModelingAgent._extract_complete_object(cleaned, obj_start)if obj_str:try:# 验证这个是完整的JSON对象9 unmodified lines# 重构JSONif complete_objects:schemes_str = ',\n'.join(complete_objects)repaired = cleaned[:schemes_match.start()] + '{\n "schemes": [\n' + schemes_str + '\n ]\n}'logger.info(f"✅ 截断修复:保留了 {len(complete_objects)} 个完整方案")return repaired# 策略2:通用方法 - 从后往前找到最后一个完整的 } 或 ]# 需要正确处理字符串内的括号last_complete = -1in_string = Falseescape_char = Falsefor i, char in enumerate(cleaned):if escape_char:escape_char = Falsecontinueif char == '\\':escape_char = Truecontinueif char == '"' and not in_string:in_string = Truecontinueif in_string:if char == '"':in_string = Falsecontinueif char in '}':last_complete = ielif char in ']':last_complete = iif last_complete != -1:truncated = cleaned[:last_complete + 1]# 平衡括号repaired = ModelingAgent._balance_brackets(truncated)logger.info("✅ 通用截断修复完成")
404 unmodified lines4054064074084094104114124134144154164176 unmodified lines4244254264274284294304311 unmodified line4334344354364374384394404411 unmodified line4434444454464474484494504514524534544554567 unmodified lines464465466467468469470471472473474475476477478479480481482483484485486487488489490404 unmodified lines解析策略(按优先级尝试):1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等)2. json.loads() - 标准JSON解析3. 修复常见错误后重试4. 返回原始文本作为降级参数:json_str (str): 提取的JSON字符串response_text (str): 原始响应文本(用于降级)返回:Dict[str, Any]: 解析后的字典6 unmodified linesreturn resultexcept Exception as e:logger.warning(f"⚠️ JSON5解析失败: {e}")# 策略2:标准 json.loads()try:result = json.loads(json_str)logger.info("✅ 标准JSON解析成功 (RecommendationAgent)")1 unmodified lineexcept 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)")1 unmodified lineexcept: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字符串7 unmodified linesrepaired = 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 repairedif hasattr(error, 'pos') and error.pos:pos = error.posif 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 None404 unmodified lines4054064074084094104114124134144154164174184196 unmodified lines4264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734741 unmodified line4764774784794804814824834841 unmodified line4864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266277 unmodified lines635636637638639640641642643644645646647648649650651652653654655656657658659660661662404 unmodified lines解析策略(按优先级尝试):1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等)2. 如果json5失败且是截断错误,立即尝试修复并重新用json5解析3. 尝试直接解析 response_text(可能json_str提取有误)4. json.loads() - 标准JSON解析5. 修复常见错误后重试6. 返回原始文本作为降级参数:json_str (str): 提取的JSON字符串response_text (str): 原始响应文本(用于降级和备用解析)返回:Dict[str, Any]: 解析后的字典6 unmodified linesreturn resultexcept Exception as e:logger.warning(f"⚠️ JSON5解析失败: {e}")# 关键改进:如果json5失败是因为截断,立即尝试修复if "Unexpected end of input" in str(e) or "Unterminated string" in str(e):logger.warning("⚠️ 检测到JSON截断或未终止字符串,尝试修复...")# 尝试修复 json_strrepaired = self._truncate_and_close_json(json_str)if repaired:try:result = json5.loads(repaired)logger.info("✅ JSON5解析成功(修复json_str后)")return resultexcept Exception as e2:logger.warning(f"⚠️ 修复后JSON5仍无法解析: {e2}")# 也尝试修复整个 response_textrepaired_full = self._truncate_and_close_json(response_text)if repaired_full:try:# 尝试从修复后的全文提取JSONif "```json" in repaired_full:test_json = repaired_full.split("```json")[1].split("```")[0].strip()elif "```" in repaired_full:test_json = repaired_full.split("```")[1].split("```")[0].strip()else:test_json = repaired_full.strip()result = json5.loads(test_json)logger.info("✅ JSON5解析成功(修复response_text后)")return resultexcept Exception as e3:logger.warning(f"⚠️ 修复后全文JSON5仍无法解析: {e3}")# 策略2:尝试直接解析 response_text(可能之前的json_str提取有误)try:import json5result = json5.loads(response_text)logger.info("✅ 直接解析response_text成功(JSON5)")return resultexcept:pass# 策略3:标准 json.loads()try:result = json.loads(json_str)logger.info("✅ 标准JSON解析成功 (RecommendationAgent)")1 unmodified lineexcept json.JSONDecodeError as e:logger.warning(f"⚠️ 标准JSON解析失败: {e}")# 策略4:修复常见错误后重试repaired = self._repair_json(json_str, e)if repaired and repaired != json_str.strip():try:result = json.loads(repaired)logger.info("✅ 修复后JSON解析成功 (RecommendationAgent)")1 unmodified lineexcept:logger.warning("⚠️ 修复后仍无法解析JSON")# 策略5:降级 - 尝试从原始文本中提取信息logger.error("❌ 所有JSON解析策略均失败,返回空结果")logger.error(f"JSON string (first 300 chars): {json_str[:300]}")return {"indicators": []}def _truncate_and_close_json(self, json_str: str) -> Optional[str]:"""截断不完整的JSON并正确关闭所有括号用于处理 "Unexpected end of input" 错误参数:json_str (str): 可能不完整的JSON字符串返回:Optional[str]: 修复后的完整JSON字符串"""if not json_str:return None# 清理可能的markdown代码块标记cleaned = json_str.strip()if cleaned.startswith("```"):cleaned = re.sub(r'^```(json)?\n?', '', cleaned)if cleaned.endswith("```"):cleaned = cleaned.rsplit("```", 1)[0]cleaned = cleaned.strip()# 策略1:尝试找到 "indicators": [ 并提取完整的数组元素indicators_match = re.search(r'"indicators"\s*:\s*\[', cleaned)if indicators_match:array_start = indicators_match.end()complete_objects = []pos = array_startwhile pos < len(cleaned):obj_start = cleaned.find('{', pos)if obj_start == -1:breakobj_str = self._extract_complete_object(cleaned, obj_start)if obj_str:try:obj = json.loads(obj_str)complete_objects.append(obj_str)pos = obj_start + len(obj_str)except:breakelse:breakif complete_objects:indicators_str = ',\n'.join(complete_objects)repaired = cleaned[:indicators_match.start()] + '{\n "indicators": [\n' + indicators_str + '\n ]\n}'logger.info(f"✅ 截断修复:保留了 {len(complete_objects)} 个完整指标")return repaired# 策略2:通用方法 - 从后往前找到最后一个完整的 } 或 ]last_complete = -1in_string = Falseescape_char = Falsefor i, char in enumerate(cleaned):if escape_char:escape_char = Falsecontinueif char == '\\':escape_char = Truecontinueif char == '"' and not in_string:in_string = Truecontinueif in_string:if char == '"':in_string = Falsecontinueif char in '}':last_complete = ielif char in ']':last_complete = iif last_complete != -1:truncated = cleaned[:last_complete + 1]repaired = self._balance_brackets(truncated)logger.info("✅ 通用截断修复完成")return repairedreturn Nonedef _extract_complete_object(self, json_str: str, start_pos: int) -> Optional[str]:"""从指定位置提取一个完整的JSON对象"""if start_pos >= len(json_str) or json_str[start_pos] != '{':return Nonedepth = 0in_string = Falseescape_char = Falsefor i in range(start_pos, len(json_str)):char = json_str[i]if escape_char:escape_char = Falsecontinueif char == '\\':escape_char = Truecontinueif char == '"' and not in_string:in_string = Truecontinueif in_string:if char == '"':in_string = Falsecontinueif char == '{':depth += 1elif char == '}':depth -= 1if depth == 0:return json_str[start_pos:i+1]return Nonedef _repair_json(self, json_str: str, error: json.JSONDecodeError) -> Optional[str]:"""修复LLM输出中常见的JSON错误(增强版)支持的修复:1. 未终止的字符串 - 在错误位置添加引号2. 意外的输入结束 - 截断到最后一个完整对象3. 尾随逗号 - 移除对象/数组末尾的逗号4. 缺失的逗号 - 在字段之间添加缺失的逗号5. 缺失的括号 - 自动补全参数:json_str (str): 包含错误的JSON字符串7 unmodified linesrepaired = json_str# 修复0:如果是 "Unexpected end of input" 或类似截断错误if "Unexpected end of input" in str(error) or "Unterminated string" in str(error):logger.warning("⚠️ 检测到JSON输入意外结束,尝试截断修复...")truncated = self._truncate_and_close_json(repaired)if truncated:return truncated# 修复1:缺失的逗号(在 "value" 后面缺少逗号)repaired = re.sub(r'("\s*)\"\s*"', r'\1", "', repaired)repaired = re.sub(r'("\s*)\}\s*"', r'\1"}, "', repaired)repaired = re.sub(r'("\s*)\]\s*"', r'\1"], "', repaired)# 修复2:未终止的字符串if hasattr(error, 'pos') and error.pos:pos = error.posif pos < len(repaired):repaired = repaired[:pos] + '"'# 修复3:尾随逗号(在 } 或 ] 前)repaired = re.sub(r',\s*([}\]])', r'\1', repaired)# 修复4:缺失的闭合括号repaired = self._balance_brackets(repaired)return repaired if repaired != json_str else None
agents/modeling_agent.py+106-29
agents/recommendation_agent.py+200-28