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 lines3523533543553563553563573573583593603613623613633643653666 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164173754184194204211 unmodified line4234244253834264273854284294304311 unmodified line43343443539343643743843910 unmodified lines4504514524534104114544554564574588 unmodified lines46746846942647047147242943043147347447547647747847948048148243348348448548648748848944049049149244349349449544649649749844949950050150216 unmodified lines5195205214724735225235245255265275285295304765315325335345355365374835385394855405415425435444905455465475489 unmodified lines558559560506561562563564510511565566567568569570571572573574575576577578579580581582583584585586587588589513590591592593351 unmodified lines 解析策略(按优先级尝试): 1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等) 2. 如果json5失败且是截断错误,立即尝试修复并重新用json5解析 3. 尝试直接解析 response_text(可能json_str提取有误) 2. json.loads() - 标准JSON解析 3. 修复常见错误后重试 4. 返回原始文本作为markdown降级 4. json.loads() - 标准JSON解析 5. 修复常见错误后重试 6. 返回原始文本作为markdown降级 参数: json_str (str): 提取的JSON字符串 response_text (str): 原始响应文本(用于降级) response_text (str): 原始响应文本(用于降级和备用解析) 返回: Dict[str, Any]: 解析后的字典,如果所有策略都失败则返回降级结果6 unmodified lines return result except 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_str repaired = ModelingAgent._truncate_and_close_json(json_str) if repaired: try: result = json5.loads(repaired) logger.info("✅ JSON5解析成功(修复json_str后)") return result except Exception as e2: logger.warning(f"⚠️ 修复后JSON5仍无法解析: {e2}") # 也尝试修复整个 response_text repaired_full = ModelingAgent._truncate_and_close_json(response_text) if repaired_full: try: # 尝试从修复后的全文提取JSON if "```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 result except Exception as e3: logger.warning(f"⚠️ 修复后全文JSON5仍无法解析: {e3}") # 策略2:尝试直接解析 response_text(可能之前的json_str提取有误) try: import json5 result = json5.loads(response_text) logger.info("✅ 直接解析response_text成功(JSON5)") return result except: pass # 策略2:标准 json.loads() # 策略3:标准 json.loads() try: result = json.loads(json_str) logger.info("✅ 标准JSON解析成功")1 unmodified line except json.JSONDecodeError as e: logger.warning(f"⚠️ 标准JSON解析失败: {e}") # 策略3:修复常见错误后重试 # 策略4:修复常见错误后重试 repaired = ModelingAgent._repair_json(json_str, e) if repaired: if repaired and repaired != json_str.strip(): try: result = json.loads(repaired) logger.info("✅ 修复后JSON解析成功")1 unmodified line except: logger.warning("⚠️ 修复后仍无法解析JSON") # 策略4:降级 - 返回原始文本作为markdown # 策略5:降级 - 返回原始文本作为markdown logger.error("❌ 所有JSON解析策略均失败,返回原始文本") return { "markdown": response_text,10 unmodified lines 1. 未终止的字符串 - 在错误位置添加引号 2. 意外的输入结束 - 截断到最后一个完整对象 3. 尾随逗号 - 移除对象/数组末尾的逗号 4. 缺失的逗号 - 在字段之间添加缺失的逗号 4. 缺失的括号 - 自动补全 5. 单引号 - 转换为双引号 5. 缺失的括号 - 自动补全 6. 单引号 - 转换为双引号 参数: json_str (str): 包含错误的JSON字符串8 unmodified lines repaired = json_str.strip() # 修复0:如果是 "Unexpected end of input" 或类似截断错误 if error and "Unexpected end of input" in str(error): if error and ("Unexpected end of input" in str(error) or "Unterminated string" in str(error)): logger.warning("⚠️ 检测到JSON输入意外结束,尝试截断修复...") # 策略:找到最后一个完整的对象/数组,截断并关闭 repaired = ModelingAgent._truncate_and_close_json(repaired) if repaired: return repaired 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" # 修复1:未终止的字符串 # 修复2:未终止的字符串 if error and hasattr(error, 'pos') and error.pos: pos = error.pos if pos < len(repaired): # 在错误位置添加引号 repaired = repaired[:pos] + '"' # 修复2:尾随逗号(在 } 或 ] 前) # 修复3:尾随逗号(在 } 或 ] 前) repaired = re.sub(r',\s*([}\]])', r'\1', repaired) # 修复3:缺失的闭合括号 # 修复4:缺失的闭合括号 repaired = ModelingAgent._balance_brackets(repaired) # 修复4:将单引号键名转换为双引号 # 修复5:将单引号键名转换为双引号 repaired = re.sub(r"([{,]\s*)'([^']*)'\s*:", r'\1"\2":', repaired) # 修复5:移除注释(JSON不支持注释,但LLM可能会加) # 修复6:移除注释(JSON不支持注释,但LLM可能会加) repaired = re.sub(r'//[^\n]*', '', repaired) repaired = re.sub(r'/\*.*?\*/', '', repaired, flags=re.DOTALL) 16 unmodified lines if not json_str: return None # 找到最后一个完整的顶级键或对象 # 对于批量处理,我们尝试保留完整的 schemes 数组 # 清理可能的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*\[', json_str) schemes_match = re.search(r'"schemes"\s*:\s*\[', cleaned) if schemes_match: # 找到 schemes 数组的开始位置 array_start = schemes_match.end() # 尝试解析数组中完整的对象 complete_objects = [] pos = array_start while pos < len(json_str): while pos < len(cleaned): # 查找对象的开始 obj_start = json_str.find('{', pos) obj_start = cleaned.find('{', pos) if obj_start == -1: break # 尝试提取这个对象 obj_str = ModelingAgent._extract_complete_object(json_str, obj_start) obj_str = ModelingAgent._extract_complete_object(cleaned, obj_start) if obj_str: try: # 验证这个是完整的JSON对象9 unmodified lines # 重构JSON if complete_objects: schemes_str = ',\n'.join(complete_objects) repaired = json_str[:schemes_match.start()] + '{\n "schemes": [\n' + schemes_str + '\n ]\n}' repaired = cleaned[: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(']')) # 策略2:通用方法 - 从后往前找到最后一个完整的 } 或 ] # 需要正确处理字符串内的括号 last_complete = -1 in_string = False escape_char = False for i, char in enumerate(cleaned): 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 '}': last_complete = i elif char in ']': last_complete = i if last_complete != -1: truncated = json_str[:last_complete + 1] truncated = cleaned[:last_complete + 1] # 平衡括号 repaired = ModelingAgent._balance_brackets(truncated) logger.info("✅ 通用截断修复完成")404 unmodified lines4054064074084094084094104104114124134144154144164174184196 unmodified lines4264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704284714724734741 unmodified line4764774784364794804384814824834841 unmodified line4864874884464894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156164536176186196206216226236246256266277 unmodified lines635636637467468469470471472473474475476477478479480481482483484638639640641642643644645646647648649650651652653654655656657658487659660661662404 unmodified lines 解析策略(按优先级尝试): 1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等) 2. 如果json5失败且是截断错误,立即尝试修复并重新用json5解析 3. 尝试直接解析 response_text(可能json_str提取有误) 2. json.loads() - 标准JSON解析 3. 修复常见错误后重试 4. 返回原始文本作为降级 4. json.loads() - 标准JSON解析 5. 修复常见错误后重试 6. 返回原始文本作为降级 参数: json_str (str): 提取的JSON字符串 response_text (str): 原始响应文本(用于降级) response_text (str): 原始响应文本(用于降级和备用解析) 返回: Dict[str, Any]: 解析后的字典6 unmodified lines return result except 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_str repaired = self._truncate_and_close_json(json_str) if repaired: try: result = json5.loads(repaired) logger.info("✅ JSON5解析成功(修复json_str后)") return result except Exception as e2: logger.warning(f"⚠️ 修复后JSON5仍无法解析: {e2}") # 也尝试修复整个 response_text repaired_full = self._truncate_and_close_json(response_text) if repaired_full: try: # 尝试从修复后的全文提取JSON if "```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 result except Exception as e3: logger.warning(f"⚠️ 修复后全文JSON5仍无法解析: {e3}") # 策略2:尝试直接解析 response_text(可能之前的json_str提取有误) try: import json5 result = json5.loads(response_text) logger.info("✅ 直接解析response_text成功(JSON5)") return result except: pass # 策略2:标准 json.loads() # 策略3:标准 json.loads() try: result = json.loads(json_str) logger.info("✅ 标准JSON解析成功 (RecommendationAgent)")1 unmodified line except json.JSONDecodeError as e: logger.warning(f"⚠️ 标准JSON解析失败: {e}") # 策略3:修复常见错误后重试 # 策略4:修复常见错误后重试 repaired = self._repair_json(json_str, e) if repaired: if repaired and repaired != json_str.strip(): try: result = json.loads(repaired) logger.info("✅ 修复后JSON解析成功 (RecommendationAgent)")1 unmodified line except: logger.warning("⚠️ 修复后仍无法解析JSON") # 策略4:降级 - 尝试从原始文本中提取信息 # 策略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_start while pos < len(cleaned): obj_start = cleaned.find('{', pos) if obj_start == -1: break obj_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: break else: break if 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 = -1 in_string = False escape_char = False for i, char in enumerate(cleaned): 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 '}': last_complete = i elif char in ']': last_complete = i if last_complete != -1: truncated = cleaned[:last_complete + 1] repaired = self._balance_brackets(truncated) logger.info("✅ 通用截断修复完成") return repaired return None def _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 None depth = 0 in_string = False escape_char = False for i in range(start_pos, len(json_str)): char = json_str[i] 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 == '{': depth += 1 elif char == '}': depth -= 1 if depth == 0: return json_str[start_pos:i+1] return None def _repair_json(self, json_str: str, error: json.JSONDecodeError) -> Optional[str]: """ 修复LLM输出中常见的JSON错误 修复LLM输出中常见的JSON错误(增强版) 支持的修复: 1. 未终止的字符串 - 在错误位置添加引号 2. 意外的输入结束 - 截断到最后一个完整对象 3. 尾随逗号 - 移除对象/数组末尾的逗号 4. 缺失的逗号 - 在字段之间添加缺失的逗号 5. 缺失的括号 - 自动补全 参数: json_str (str): 包含错误的JSON字符串7 unmodified lines 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:尾随逗号 # 修复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.pos if pos < len(repaired): repaired = repaired[:pos] + '"' # 修复3:尾随逗号(在 } 或 ] 前) repaired = re.sub(r',\s*([}\]])', r'\1', repaired) # 修复3:缺失的闭合括号 # 修复4:缺失的闭合括号 repaired = self._balance_brackets(repaired) return repaired if repaired != json_str else Noneagents/modeling_agent.py+106-29
agents/recommendation_agent.py+200-28