theme_extractor.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import asyncio
  2. import json
  3. import logging
  4. from typing import List, Dict, Any
  5. from schema_tools.config import SCHEMA_TOOLS_CONFIG
  6. class ThemeExtractor:
  7. """主题提取器"""
  8. def __init__(self, vn, business_context: str):
  9. """
  10. 初始化主题提取器
  11. Args:
  12. vn: vanna实例
  13. business_context: 业务上下文
  14. """
  15. self.vn = vn
  16. self.business_context = business_context
  17. self.logger = logging.getLogger("schema_tools.ThemeExtractor")
  18. self.config = SCHEMA_TOOLS_CONFIG
  19. async def extract_themes(self, md_contents: str) -> List[Dict[str, Any]]:
  20. """
  21. 从MD内容中提取分析主题
  22. Args:
  23. md_contents: 所有MD文件的组合内容
  24. Returns:
  25. 主题列表
  26. """
  27. theme_count = self.config['qs_generation']['theme_count']
  28. prompt = self._build_theme_extraction_prompt(md_contents, theme_count)
  29. try:
  30. # 调用LLM提取主题
  31. response = await self._call_llm(prompt)
  32. # 解析响应
  33. themes = self._parse_theme_response(response)
  34. self.logger.info(f"成功提取 {len(themes)} 个分析主题")
  35. return themes
  36. except Exception as e:
  37. self.logger.error(f"主题提取失败: {e}")
  38. raise
  39. def _build_theme_extraction_prompt(self, md_contents: str, theme_count: int) -> str:
  40. """构建主题提取的prompt"""
  41. prompt = f"""你是一位经验丰富的业务数据分析师,正在分析{self.business_context}的数据库。
  42. 以下是数据库中所有表的详细结构说明:
  43. {md_contents}
  44. 基于对这些表结构的理解,请从业务分析的角度提出 {theme_count} 个数据查询分析主题。
  45. 要求:
  46. 1. 每个主题应该有明确的业务价值和分析目标
  47. 2. 主题之间应该有所区别,覆盖不同的业务领域
  48. 3. 你需要自行决定每个主题应该涉及哪些表
  49. 4. 主题应该体现实际业务场景的数据分析需求
  50. 5. 考虑时间维度、对比分析、排名统计等多种分析角度
  51. 6. 为每个主题提供3-5个关键词,用于快速了解主题内容
  52. 请以JSON格式输出:
  53. ```json
  54. {{
  55. "themes": [
  56. {{
  57. "topic_name": "日营业数据分析",
  58. "description": "基于 bss_business_day_data 表,分析每个服务区和档口每天的营业收入、订单数量、支付方式等",
  59. "related_tables": ["bss_business_day_data", "bss_branch", "bss_service_area"],
  60. "keywords": ["收入", "订单", "支付方式", "日报表"],
  61. "focus_areas": ["收入趋势", "服务区对比", "支付方式分布"]
  62. }}
  63. ]
  64. }}
  65. ```
  66. 请确保:
  67. - topic_name 简洁明了(10字以内)
  68. - description 详细说明分析目标和价值(50字左右)
  69. - related_tables 列出该主题需要用到的表名(数组格式)
  70. - keywords 提供3-5个核心关键词(数组格式)
  71. - focus_areas 列出3-5个具体的分析角度(保留用于生成问题)"""
  72. return prompt
  73. async def _call_llm(self, prompt: str) -> str:
  74. """调用LLM"""
  75. try:
  76. # 使用vanna的chat_with_llm方法
  77. response = await asyncio.to_thread(
  78. self.vn.chat_with_llm,
  79. question=prompt,
  80. system_prompt="你是一个专业的数据分析师,擅长从业务角度设计数据分析主题和查询方案。请严格按照要求的JSON格式输出。"
  81. )
  82. if not response or not response.strip():
  83. raise ValueError("LLM返回空响应")
  84. return response.strip()
  85. except Exception as e:
  86. self.logger.error(f"LLM调用失败: {e}")
  87. raise
  88. def _parse_theme_response(self, response: str) -> List[Dict[str, Any]]:
  89. """解析LLM的主题响应"""
  90. try:
  91. # 提取JSON部分
  92. import re
  93. json_match = re.search(r'```json\s*(.*?)\s*```', response, re.DOTALL)
  94. if json_match:
  95. json_str = json_match.group(1)
  96. else:
  97. # 尝试直接解析
  98. json_str = response
  99. # 解析JSON
  100. data = json.loads(json_str)
  101. themes = data.get('themes', [])
  102. # 验证和标准化主题格式
  103. validated_themes = []
  104. for theme in themes:
  105. # 兼容旧格式(name -> topic_name)
  106. if 'name' in theme and 'topic_name' not in theme:
  107. theme['topic_name'] = theme['name']
  108. # 验证必需字段
  109. required_fields = ['topic_name', 'description', 'related_tables']
  110. if all(key in theme for key in required_fields):
  111. # 确保related_tables是数组
  112. if isinstance(theme['related_tables'], str):
  113. theme['related_tables'] = [theme['related_tables']]
  114. # 确保keywords存在且是数组
  115. if 'keywords' not in theme:
  116. # 从description中提取关键词
  117. theme['keywords'] = self._extract_keywords_from_description(theme['description'])
  118. elif isinstance(theme['keywords'], str):
  119. theme['keywords'] = [theme['keywords']]
  120. # 保留focus_areas用于问题生成(如果没有则使用keywords)
  121. if 'focus_areas' not in theme:
  122. theme['focus_areas'] = theme['keywords'][:3]
  123. validated_themes.append(theme)
  124. else:
  125. self.logger.warning(f"主题格式不完整,跳过: {theme.get('topic_name', 'Unknown')}")
  126. return validated_themes
  127. except json.JSONDecodeError as e:
  128. self.logger.error(f"JSON解析失败: {e}")
  129. self.logger.debug(f"原始响应: {response}")
  130. raise ValueError(f"无法解析LLM响应为JSON格式: {e}")
  131. except Exception as e:
  132. self.logger.error(f"解析主题响应失败: {e}")
  133. raise
  134. def _extract_keywords_from_description(self, description: str) -> List[str]:
  135. """从描述中提取关键词(简单实现)"""
  136. # 定义常见的业务关键词
  137. business_keywords = [
  138. "收入", "营业额", "订单", "支付", "统计", "分析", "趋势", "对比",
  139. "排名", "汇总", "明细", "报表", "月度", "日度", "年度", "服务区",
  140. "档口", "商品", "客流", "车流", "效率", "占比", "增长"
  141. ]
  142. # 从描述中查找出现的关键词
  143. found_keywords = []
  144. for keyword in business_keywords:
  145. if keyword in description:
  146. found_keywords.append(keyword)
  147. # 如果找到的太少,返回默认值
  148. if len(found_keywords) < 3:
  149. found_keywords = ["数据分析", "统计报表", "业务查询"]
  150. return found_keywords[:5] # 最多返回5个