Spaces:
Runtime error
Runtime error
Feat: 增强 JSON 解析能力,支持 json5 和自动修复
Browse files- 添加 json5 库支持(更宽容的 JSON 解析)
- 新增 _parse_json_with_fallback() 方法(4级降级策略)
- 新增 _repair_json() 方法(修复常见 LLM JSON 错误)
- 更新 _parse_response() 和 _parse_batch_response()
- 改进错误处理,避免返回错误占位符
Files changed (2)
23 unmodified lines242526272829314 unmodified lines34434534634734834920 unmodified lines370371372373374375376377378379380381382383384385386387388389390391345 unmodified lines73773873974074174274374420 unmodified lines76576676776876977077177277377477577677777877978078178223 unmodified linesimport jsonimport loggingfrom datetime import datetimefrom typing import Dict, Any, List, Optionalfrom pathlib import Path314 unmodified lines# 步骤3:解析API响应return self._parse_response(response_text, indicator)def _parse_response(self, response_text: str, indicator: Indicator) -> Dict[str, Any]:"""解析API响应,提取建模产物20 unmodified lineselse:json_str = response_text.strip()# 步骤2:解析JSON字符串(带容错)try:result = json.loads(json_str)except json.JSONDecodeError as je:logger.warning(f"JSON parse failed, attempting repair: {je}")# 尝试修复常见的LLM JSON错误# 方法1:截断到错误��置if hasattr(je, 'pos') and je.pos:json_str = json_str[:je.pos] + '"'try:result = json.loads(json_str)except:# 方法2:使用更宽松的解析result = {"markdown": response_text, "sql": "", "table_structure": []}else:result = {"markdown": response_text, "sql": "", "table_structure": []}# 步骤3:提取字段(处理单指标和批处理两种格式)if "schemes" in result:345 unmodified lineselse:json_str = response_text.strip()# 步骤2:解析JSON字符串result = json.loads(json_str)# 步骤3:提取schemes列表schemes = result.get("schemes", [])20 unmodified lines"table_structure": table_structure})logger.info(f"Parsed {len(formatted_schemes)} schemes from batch response")return formatted_schemesexcept json.JSONDecodeError as e:logger.error(f"Failed to parse batch JSON response: {e}")logger.error(f"Response text (first 500 chars): {response_text[:500]}")# 降级:返回错误占位符return [{"indicator_id": ind_id,"indicator_name": indicator_set.get_indicator(ind_id).indicator_name if indicator_set.get_indicator(ind_id) else ind_id,"markdown": f"# Error\n\nBatch processing failed: {str(e)}","sql": "-- Error: Batch processing failed","table_structure": []} for ind_id in selected_indicators]23 unmodified lines24252627282930314 unmodified lines34534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345420 unmodified lines475476477478479480481482345 unmodified lines82882983083183283383483520 unmodified lines85685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888923 unmodified linesimport jsonimport loggingimport refrom datetime import datetimefrom typing import Dict, Any, List, Optionalfrom pathlib import Path314 unmodified lines# 步骤3:解析API响应return self._parse_response(response_text, indicator)@staticmethoddef _parse_json_with_fallback(json_str: str, response_text: str) -> Dict[str, Any]:"""使用多种策略解析JSON,从LLM输出中提取结构化数据解析策略(按优先级尝试):1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等)2. json.loads() - 标准JSON解析3. 修复常见错误后重试4. 返回原始文本作为markdown降级参数:json_str (str): 提取的JSON字符串response_text (str): 原始响应文本(用于降级)返回:Dict[str, Any]: 解析后的字典,如果所有策略都失败则返回降级结果"""# 策略1:使用 json5 解析(最宽容)try:import json5result = json5.loads(json_str)logger.info("✅ JSON5解析成功")return resultexcept Exception as e:logger.warning(f"⚠️ JSON5解析失败: {e}")# 策略2:标准 json.loads()try:result = json.loads(json_str)logger.info("✅ 标准JSON解析成功")return resultexcept 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解析成功")return resultexcept:logger.warning("⚠️ 修复后仍无法解析JSON")# 策略4:降级 - 返回原始文本作为markdownlogger.error("❌ 所有JSON解析策略均失败,返回原始文本")return {"markdown": response_text,"sql": "","table_structure": []}@staticmethoddef _repair_json(json_str: str, error: json.JSONDecodeError) -> Optional[str]:"""修复LLM输出中常见的JSON错误支持的修复:1. 未终止的字符串 - 在错误位置添加引号2. 尾随逗号 - 移除对象/数组末尾的逗号3. 缺失的逗号 - 在对象/数组元素间添加逗号4. 单引号 - 转换为双引号参数:json_str (str): 包含错误的JSON字符串error (json.JSONDecodeError): 解析错误对象返回:Optional[str]: 修复后的JSON字符串,如果无法修复则返回None"""if not json_str:return Nonerepaired = json_str# 修复1:未终止的字符串if "Unterminated string" in str(error):if hasattr(error, 'pos') and error.pos:# 在错误位置添加引号pos = error.posrepaired = repaired[:pos] + '"'# 尝试平衡括号open_braces = repaired.count('{') - repaired.count('}')open_brackets = repaired.count('[') - repaired.count(']')# 添加缺失的闭合括号if open_brackets > 0:repaired += ']' * open_bracketsif open_braces > 0:repaired += '}' * open_braces# 修复2:尾随逗号if "trailing comma" in str(error).lower():# 移除 } 或 ] 前的逗号repaired = re.sub(r',\s*([}\]])', r'\1', repaired)# 修复3:将单引号转换为双引号(简单情况)# 只处理键名的单引号(不处理字符串值内的单引号)repaired = re.sub(r"([{,]\s*)'([^']*)'\s*:", r'\1"\2":', repaired)return repaired if repaired != json_str else Nonedef _parse_response(self, response_text: str, indicator: Indicator) -> Dict[str, Any]:"""解析API响应,提取建模产物20 unmodified lineselse:json_str = response_text.strip()# 步骤2:使用强大的JSON解析函数(带多种降级策略)result = self._parse_json_with_fallback(json_str, response_text)# 步骤3:提取字段(处理单指标和批处理两种格式)if "schemes" in result:345 unmodified lineselse:json_str = response_text.strip()# 步骤2:使用强大的JSON解析函数(带多种降级策略)result = self._parse_json_with_fallback(json_str, response_text)# 步骤3:提取schemes列表schemes = result.get("schemes", [])20 unmodified lines"table_structure": table_structure})logger.info(f"✅ 从批量响应中解析出 {len(formatted_schemes)} 个方案")return formatted_schemesexcept Exception as e:logger.error(f"❌ 解析批量响应失败: {e}")logger.error(f"响应文本 (前500字符): {response_text[:500]}")# 尝试从原始响应中提取有用信息import re# 尝试1:从 markdown 中提取 SQLsql_match = re.search(r'```sql\n(.*?)\n```', response_text, re.DOTALL)sql = sql_match.group(1).strip() if sql_match else ""# 尝试2:提取指标名称(如果响应中有)indicator_names = []for ind_id in selected_indicators:ind = indicator_set.get_indicator(ind_id)if ind:indicator_names.append(ind.indicator_name)# 降级:返回包含部分信息的方案logger.warning("⚠️ 降级处理:返回包含原始响应的方案")return [{"indicator_id": ind_id,"indicator_name": indicator_set.get_indicator(ind_id).indicator_name if indicator_set.get_indicator(ind_id) else ind_id,"markdown": f"# 指标定义\n\n{response_text[:1000]}...","sql": sql if sql else "-- SQL 解析失败,请查看 markdown","table_structure": []} for ind_id in selected_indicators]
24 unmodified lines25262728293024 unmodified lines# API Call# ============================================================================requests>=2.31.0# ============================================================================# Data Validation (v3.0 New)24 unmodified lines2526272829303124 unmodified lines# API Call# ============================================================================requests>=2.31.0json5>=0.9.0 # Lenient JSON parser for LLM output# ============================================================================# Data Validation (v3.0 New)
agents/modeling_agent.py+132-25
requirements.txt+1