Spaces:
Runtime error
Runtime error
File size: 27,807 Bytes
ce06eb4 650cb4f ce06eb4 650cb4f ce06eb4 650cb4f ce06eb4 650cb4f ce06eb4 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 1419496 d3f2aa9 1419496 d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f d3f2aa9 650cb4f ce06eb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 | """
数据指标建模助手 v3.1 - 推荐Agent模块
本模块实现了RecommendationAgent类,根据业务领域和分析目的推荐或生成相关指标。
主要功能:
1. 根据业务领域和分析目的,从向量库中推荐相似的指标
2. 将推荐结果组织成指标列表
3. 当向量库不可用或结果为空时,使用AI生成推荐指标
4. 支持模拟模式和真实API模式
更新日志 (v3.1):
- 输入:business_domain(业务领域)和 analysis_purpose(分析目的)
- 输出:指标列表(Indicator 对象列表)
- 移除对 IndicatorSet 的依赖
- 新增基于业务领域和分析目的的推荐逻辑
作者: 数据指标建模助手团队
版本: v3.1
日期: 2024
"""
import json
import logging
import re
from typing import Dict, Any, List, Optional
from pathlib import Path
import sys
# 将项目根目录添加到Python路径
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))
# 导入所需的模块和类
from .base_agent import BaseAgent # 基础Agent类
from rag.vector_store import VectorStore # 向量存储(用于RAG)
from utils.api_client import DeepSeekClient # DeepSeek API客户端
from config.prompts import get_recommendation_agent_prompt # 提示词模板
from config.settings import ( # 配置参数
DEEPSEEK_API_KEY,
)
from models.indicator import Indicator # 指标数据模型
logger = logging.getLogger(__name__)
class RecommendationAgent(BaseAgent):
"""
推荐Agent,根据业务领域和分析目的推荐或生成指标
本Agent是数据指标建模助手的核心组件之一,主要职责是基于用户的业务领域和分析目的,
推荐相关的指标,避免重复建设,提高指标复用率。
更新说明 (v3.1):
- 输入参数:
* business_domain (str): 业务领域(如:电商、金融、公共资源交易等)
* analysis_purpose (str): 分析目的(用户想要解决的业务问题)
* similar_indicators (str, 可选): 历史指标库中相似的指标(来自RequirementAgent)
* top_k (int, 可选): 推荐数量上限(默认8)
- 输出结果:
* indicators (List[Indicator]): 推荐的指标列表
* total_count (int): 推荐指标总数
* recommendation_type (str): 推荐类型("rag" 或 "ai_generated")
属性:
api_key (str): DeepSeek API密钥
vector_store (VectorStore): 向量存储实例(可选)
api_client (DeepSeekClient): API客户端实例
"""
def __init__(
self,
vector_store: Optional[VectorStore] = None,
api_key: Optional[str] = None
):
"""
初始化推荐Agent
构造方法,设置Agent的运行参数并初始化所需的组件。
向量库是可选的,如果未提供,将使用AI生成作为降级方案。
参数:
vector_store (Optional[VectorStore]): 向量存储实例
- 用于相似度搜索(RAG)
- 如果为None,RAG将不可用(将使用AI生成降级)
api_key (Optional[str]): DeepSeek API密钥
- 在向量库不可用時使用
返回:
无
示例:
>>> # 使用向量库
>>> vector_store = VectorStore()
>>> agent = RecommendationAgent(vector_store=vector_store)
>>> # 不使用向量库(使用AI生成降级)
>>> agent = RecommendationAgent(vector_store=None)
"""
# 调用父类构造方法,设置Agent名称
super().__init__(name="RecommendationAgent")
# 使用提供的参数或回退到配置文件中的设置
self.api_key = api_key or DEEPSEEK_API_KEY
# 向量库(可选)
# 如果未提供,RAG功能将不可用,系统会自动降级到AI生成
self.vector_store = vector_store
# 初始化API客户端
self.api_client = None
if self.api_key:
self.api_client = DeepSeekClient(api_key=self.api_key)
else:
logger.warning("No API key provided. Some features may be unavailable.")
logger.info(f"RecommendationAgent initialized (vector_store={'available' if vector_store else 'unavailable'})")
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""
根据业务领域和分析目的生成推荐指标
这是Agent的主入口方法,协调整个推荐流程:
1. 验证输入数据的有效性
2. 根据运行模式选择执行路径
3. 返回指标列表
参数:
input_data (Dict[str, Any]): 输入数据字典,包含:
- business_domain (str): 业务领域(必需)
- analysis_purpose (str): 分析目的(必需)
- similar_indicators (str, 可选): 相似的指标(来自RAG)
- top_k (int, 可选): 推荐数量上限(默认8)
返回:
Dict[str, Any]: 包含执行结果的字典:
- status (str): "success" 或 "error"
- data (dict, 当status="success"时): 包含:
* indicators (List[Indicator]): 推荐的指标列表
* total_count (int): 推荐指标总数
* recommendation_type (str): 推荐类型("rag" 或 "ai_generated")
- error (str, 当status="error"时): 错误描述
示例:
>>> result = agent.run({
... "business_domain": "电商",
... "analysis_purpose": "分析用户购买行为",
... "top_k": 8
... })
>>> if result["status"] == "success":
... indicators = result["data"]["indicators"]
... for ind in indicators:
... print(f"指标: {ind.indicator_name}")
"""
try:
# 步骤1:验证输入数据
if not self._validate_input(input_data):
return {
"status": "error",
"error": "Invalid input: 'business_domain' and 'analysis_purpose' are required"
}
# 步骤2:提取输入参数
business_domain = input_data.get("business_domain")
analysis_purpose = input_data.get("analysis_purpose")
similar_indicators = input_data.get("similar_indicators", "")
top_k = input_data.get("top_k", 8)
logger.info(f"Generating recommendations for business_domain: {business_domain}, analysis_purpose: {analysis_purpose[:50]}...")
# 调用真实模式:使用向量库和/或API
result = self._real_run(business_domain, analysis_purpose, similar_indicators, top_k)
return {
"status": "success",
"data": result
}
except Exception as e:
logger.error(f"Error in RecommendationAgent.run: {e}")
return {
"status": "error",
"error": str(e)
}
def _validate_input(self, input_data: Dict[str, Any]) -> bool:
"""
验证输入数据的有效性
检查输入字典是否包含必需的字段(business_domain 和 analysis_purpose)。
参数:
input_data (Dict[str, Any]): 需要验证的输入数据
返回:
bool:
- True: 输入数据有效
- False: 输入数据无效
"""
if not input_data:
return False
business_domain = input_data.get("business_domain")
analysis_purpose = input_data.get("analysis_purpose")
if not business_domain or not analysis_purpose:
return False
return True
def _real_run(
self,
business_domain: str,
analysis_purpose: str,
similar_indicators: str,
top_k: int
) -> Dict[str, Any]:
"""
真实执行:使用向量库和/或API生成推荐指标
在真实模式下,优先使用向量库(RAG)进行相似度搜索。
如果向量库不可用或搜索结果为空,自动降级到AI生成。
参数:
business_domain (str): 业务领域
analysis_purpose (str): 分析目的
similar_indicators (str): 相似的指标(来自RequirementAgent)
top_k (int): 推荐数量上限
返回:
Dict[str, Any]: 包含推荐指标的字典
降级策略:
1. 优先使用向量库(RAG)
2. 如果向量库不可用或结果为空,使用AI生成
3. 如果AI生成失败,将抛出异常
"""
# 尝试使用RAG(向量库)进行推荐
if self.vector_store and self.vector_store.is_ready():
logger.info("Using RAG (VectorStore) for recommendations")
# 步骤1:构建搜索查询字符串
search_query = f"{business_domain} {analysis_purpose}"
# 步骤2:在向量库中搜索相似的指标
search_results = self.vector_store.search(search_query, k=top_k)
# 步骤3:将搜索结果转换为 Indicator 对象
indicators = self._convert_to_indicators(search_results)
# 步骤4:检查是否有有效的推荐结果
if len(indicators) > 0:
# 有推荐结果,直接返回
return {
"indicators": indicators,
"total_count": len(indicators),
"recommendation_type": "rag"
}
else:
# 无推荐结果,记录日志并降级
logger.info("RAG found no results. Falling back to AI generation.")
# 降级方案:使用AI生成推荐
logger.info("Using AI generation for recommendations")
return self._ai_generate_recommendations(business_domain, analysis_purpose, similar_indicators)
def _convert_to_indicators(self, search_results: List[tuple]) -> List[Indicator]:
"""
将向量库搜索结果转换为 Indicator 对象列表
参数:
search_results (List[tuple]): 向量库搜索结果
每个元素是一个元组:(指标字典, 相似度评分)
返回:
List[Indicator]: Indicator 对象列表
"""
indicators = []
for item in search_results:
try:
# 搜索结果格式:(dict, score) 或 dict
if isinstance(item, tuple):
indicator_dict, score = item
else:
indicator_dict = item
score = 1.0 # 默认相似度
# 将字典转换为 Indicator 对象
indicator = Indicator.from_dict(indicator_dict)
indicators.append(indicator)
except Exception as e:
logger.warning(f"Failed to convert indicator: {e}")
continue
return indicators
def _ai_generate_recommendations(
self,
business_domain: str,
analysis_purpose: str,
similar_indicators: str
) -> Dict[str, Any]:
"""
使用AI生成推荐指标(当RAG不可用时)
当向量库不可用或搜索结果为空时,调用DeepSeek API生成推荐指标。
这是一个降级方案,确保系统在没有向量库时仍能提供推荐。
参数:
business_domain (str): 业务领域
analysis_purpose (str): 分析目的
similar_indicators (str): 相似的指标(来自RequirementAgent)
返回:
Dict[str, Any]: AI生成的推荐结果
降级策略:
1. 尝试调用API生成推荐
2. 如果失败,降级到模拟模式
"""
logger.info("Generating recommendations using AI")
# 构建提示词(prompt)
prompt = get_recommendation_agent_prompt(
business_domain=business_domain,
analysis_purpose=analysis_purpose,
similar_indicators=similar_indicators if similar_indicators else "(无相似指标,请生成新的推荐指标)"
)
# 调用API
try:
response_text = self.api_client.call(
system_message="你是一个数据指标推荐专家,擅长根据业务领域和分析目的推荐相关指标。",
prompt=prompt
)
# 解析API响应
return self._parse_response(response_text)
except Exception as e:
# API调用失败,重新抛出异常
raise # Re-raise exception, no fallback
def _parse_response(self, response_text: str) -> Dict[str, Any]:
"""
解析API响应,提取推荐指标
API返回的是文本格式,可能包含JSON代码块。
此方法负责从响应中提取JSON,并转换为 Indicator 对象列表。
参数:
response_text (str): API返回的原始文本
返回:
Dict[str, Any]: 解析后的推荐结果
如果解析失败,返回空的推荐结果
"""
try:
# 从响应文本中提取JSON字符串
if "```json" in response_text:
json_str = response_text.split("```json")[1].split("```")[0].strip()
elif "```" in response_text:
json_str = response_text.split("```")[1].split("```")[0].strip()
else:
json_str = response_text.strip()
# 使用强大的JSON解析(带多种降级策略)
result = self._parse_json_with_fallback(json_str, response_text)
# 提取指标列表并转换为 Indicator 对象
indicators_list = result.get("indicators", [])
indicators = []
for ind_dict in indicators_list:
try:
indicator = Indicator.from_dict(ind_dict)
indicators.append(indicator)
except Exception as e:
logger.warning(f"Failed to convert indicator from AI response: {e}")
continue
# 返回标准格式
return {
"indicators": indicators,
"total_count": len(indicators),
"recommendation_type": "ai_generated"
}
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. 如果json5失败且是截断错误,立即尝试修复并重新用json5解析
3. 尝试直接解析 response_text(可能json_str提取有误)
4. json.loads() - 标准JSON解析
5. 修复常见错误后重试
6. 返回原始文本作为降级
参数:
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}")
# 关键改进:如果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
# 策略3:标准 json.loads()
try:
result = json.loads(json_str)
logger.info("✅ 标准JSON解析成功 (RecommendationAgent)")
return result
except 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)")
return result
except:
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_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
# 重构JSON - 从零构建,避免不完整的前缀
if complete_objects:
indicators_str = ',\n'.join(complete_objects)
repaired = '{\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错误(增强版)
支持的修复:
1. 未终止的字符串 - 在错误位置添加引号
2. 意外的输入结束 - 截断到最后一个完整对象
3. 尾随逗号 - 移除对象/数组末尾的逗号
4. 缺失的逗号 - 在字段之间添加缺失的逗号
5. 缺失的括号 - 自动补全
参数:
json_str (str): 包含错误的JSON字符串
error (json.JSONDecodeError): 解析错误对象
返回:
Optional[str]: 修复后的JSON字符串,如果无法修复则返回None
"""
if not json_str:
return None
repaired = 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.pos
if 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
@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]:
"""
推荐指标集的便捷方法
这是run()方法的别名,提供更直观的方法名。
参数:
input_data (Dict[str, Any]): 与run()方法相同的输入
返回:
Dict[str, Any]: 与run()方法相同的输出
注意:
此方法的存在是为了提供更语义化的API
"""
return self.run(input_data)
|