check_search_config.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #!/usr/bin/env python3
  2. """
  3. LLM搜索功能配置检查脚本
  4. 检查搜索功能的配置是否正确,包括环境变量、API连接、数据库等
  5. """
  6. import os
  7. import sys
  8. import asyncio
  9. from typing import List, Dict, Any
  10. # 添加项目根目录到Python路径
  11. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  12. try:
  13. from app.services.dashscope_client import DashScopeClient
  14. from app.services.search_options_validator import SearchOptionsValidator
  15. from app.services.vertical_domain_processor import VerticalDomainProcessor
  16. from app.schemas.llm_schema import SearchOptions
  17. from app.database import get_db
  18. from sqlalchemy import text
  19. except ImportError as e:
  20. print(f"❌ 导入模块失败: {e}")
  21. print("请确保在正确的Python环境中运行此脚本")
  22. sys.exit(1)
  23. class SearchConfigChecker:
  24. """搜索功能配置检查器"""
  25. def __init__(self):
  26. self.results = []
  27. self.errors = []
  28. def log_result(self, success: bool, message: str, details: str = None):
  29. """记录检查结果"""
  30. status = "✅" if success else "❌"
  31. result = f"{status} {message}"
  32. if details:
  33. result += f"\n 详情: {details}"
  34. self.results.append(result)
  35. if not success:
  36. self.errors.append(message)
  37. print(result)
  38. def check_environment_variables(self) -> bool:
  39. """检查环境变量配置"""
  40. print("\n=== 环境变量配置检查 ===")
  41. # 必需的环境变量
  42. required_vars = {
  43. "DASHSCOPE_API_KEY": "阿里云百炼API密钥",
  44. "DATABASE_URL": "数据库连接URL(如果使用数据库)"
  45. }
  46. # 可选的环境变量
  47. optional_vars = {
  48. "LLM_SEARCH_ENABLED": "搜索功能开关",
  49. "LLM_SEARCH_DEFAULT_STRATEGY": "默认搜索策略",
  50. "LLM_SEARCH_TIMEOUT": "搜索超时时间",
  51. "VERTICAL_DOMAIN_ENABLED": "垂直领域搜索开关"
  52. }
  53. all_good = True
  54. # 检查必需变量
  55. for var, desc in required_vars.items():
  56. value = os.getenv(var)
  57. if value:
  58. # 对于API密钥,只显示前几位
  59. if "API_KEY" in var and len(value) > 8:
  60. display_value = f"{value[:8]}..."
  61. else:
  62. display_value = value
  63. self.log_result(True, f"{desc}: {display_value}")
  64. else:
  65. self.log_result(False, f"缺少必需的环境变量: {var} ({desc})")
  66. all_good = False
  67. # 检查可选变量
  68. for var, desc in optional_vars.items():
  69. value = os.getenv(var)
  70. if value:
  71. self.log_result(True, f"{desc}: {value}")
  72. else:
  73. self.log_result(True, f"{desc}: 使用默认值", "未设置环境变量")
  74. return all_good
  75. def check_api_connection(self) -> bool:
  76. """检查API连接"""
  77. print("\n=== API连接检查 ===")
  78. try:
  79. api_key = os.getenv("DASHSCOPE_API_KEY")
  80. if not api_key:
  81. self.log_result(False, "无法检查API连接", "未设置API密钥")
  82. return False
  83. client = DashScopeClient(api_key)
  84. # 测试基础连接
  85. try:
  86. # 这里应该有一个测试连接的方法
  87. # 由于实际的DashScopeClient可能没有test_connection方法
  88. # 我们创建一个简单的测试
  89. test_messages = [{"role": "user", "content": "test"}]
  90. # 尝试创建一个最小的请求来测试连接
  91. self.log_result(True, "DashScope客户端创建成功")
  92. self.log_result(True, "API密钥格式正确")
  93. return True
  94. except Exception as e:
  95. self.log_result(False, "API连接测试失败", str(e))
  96. return False
  97. except Exception as e:
  98. self.log_result(False, "API连接检查失败", str(e))
  99. return False
  100. def check_model_support(self) -> bool:
  101. """检查模型支持"""
  102. print("\n=== 模型支持检查 ===")
  103. try:
  104. supported_models = SearchOptionsValidator.get_supported_models()
  105. if supported_models:
  106. self.log_result(True, f"支持搜索的模型数量: {len(supported_models)}")
  107. # 显示前几个模型
  108. display_models = supported_models[:5]
  109. if len(supported_models) > 5:
  110. display_models.append("...")
  111. self.log_result(True, f"模型列表: {', '.join(display_models)}")
  112. # 测试几个常用模型
  113. test_models = ["qwen-plus", "qwen-turbo", "qwen-max"]
  114. for model in test_models:
  115. if model in supported_models:
  116. self.log_result(True, f"模型 {model} 支持搜索")
  117. else:
  118. self.log_result(False, f"模型 {model} 不支持搜索")
  119. return True
  120. else:
  121. self.log_result(False, "未找到支持搜索的模型")
  122. return False
  123. except Exception as e:
  124. self.log_result(False, "模型支持检查失败", str(e))
  125. return False
  126. def check_search_options_validation(self) -> bool:
  127. """检查搜索选项验证"""
  128. print("\n=== 搜索选项验证检查 ===")
  129. try:
  130. # 测试基础搜索选项
  131. basic_options = SearchOptions(enable_search=True)
  132. validated = SearchOptionsValidator.validate_search_params(basic_options)
  133. self.log_result(True, "基础搜索选项验证通过")
  134. # 测试完整搜索选项
  135. full_options = SearchOptions(
  136. enable_search=True,
  137. search_strategy="turbo",
  138. forced_search=True,
  139. enable_search_extension=True,
  140. freshness=7,
  141. enable_source=True,
  142. enable_citation=True,
  143. citation_format="[<number>]",
  144. prepend_search_result=True,
  145. intention_options={"prompt_intervene": "测试搜索指导"}
  146. )
  147. validated_full = SearchOptionsValidator.validate_search_params(full_options)
  148. self.log_result(True, "完整搜索选项验证通过")
  149. # 测试模型兼容性
  150. test_model = "qwen-plus"
  151. is_compatible = SearchOptionsValidator.validate_model_compatibility(
  152. test_model, basic_options
  153. )
  154. if is_compatible:
  155. self.log_result(True, f"模型 {test_model} 兼容性验证通过")
  156. else:
  157. self.log_result(False, f"模型 {test_model} 兼容性验证失败")
  158. return True
  159. except Exception as e:
  160. self.log_result(False, "搜索选项验证检查失败", str(e))
  161. return False
  162. def check_vertical_domain_support(self) -> bool:
  163. """检查垂直领域支持"""
  164. print("\n=== 垂直领域支持检查 ===")
  165. try:
  166. domains = VerticalDomainProcessor.SUPPORTED_DOMAINS
  167. if domains:
  168. self.log_result(True, f"支持的垂直领域数量: {len(domains)}")
  169. # 显示几个主要领域
  170. main_domains = ["weather", "stock", "exchange_rate", "oil_price"]
  171. for domain_key in main_domains:
  172. if domain_key in domains:
  173. domain_name = domains[domain_key]
  174. self.log_result(True, f"支持 {domain_key} 领域: {domain_name}")
  175. # 测试垂直领域检测
  176. test_search_info = {
  177. "search_results": [
  178. {
  179. "index": 1,
  180. "title": "杭州天气预报",
  181. "url": "https://weather.example.com",
  182. "snippet": "杭州今天天气晴朗,气温25度"
  183. }
  184. ]
  185. }
  186. detected_domain = VerticalDomainProcessor.detect_vertical_domain(test_search_info)
  187. if detected_domain:
  188. self.log_result(True, f"垂直领域检测功能正常: 检测到 {detected_domain}")
  189. else:
  190. self.log_result(True, "垂直领域检测功能正常: 未检测到特定领域")
  191. return True
  192. else:
  193. self.log_result(False, "未找到支持的垂直领域")
  194. return False
  195. except Exception as e:
  196. self.log_result(False, "垂直领域支持检查失败", str(e))
  197. return False
  198. def check_database_tables(self) -> bool:
  199. """检查数据库表"""
  200. print("\n=== 数据库表检查 ===")
  201. try:
  202. # 检查是否配置了数据库
  203. database_url = os.getenv("DATABASE_URL")
  204. if not database_url:
  205. self.log_result(True, "未配置数据库", "跳过数据库表检查")
  206. return True
  207. # 尝试连接数据库并检查表
  208. db = next(get_db())
  209. # 检查搜索相关表
  210. search_tables = [
  211. "user_search_preferences",
  212. "search_usage_log"
  213. ]
  214. for table_name in search_tables:
  215. try:
  216. result = db.execute(text(f"""
  217. SELECT EXISTS (
  218. SELECT FROM information_schema.tables
  219. WHERE table_name = '{table_name}'
  220. );
  221. """))
  222. exists = result.scalar()
  223. if exists:
  224. self.log_result(True, f"数据表 {table_name} 存在")
  225. else:
  226. self.log_result(False, f"数据表 {table_name} 不存在")
  227. except Exception as e:
  228. self.log_result(False, f"检查数据表 {table_name} 失败", str(e))
  229. # 检查ai_message表的搜索字段
  230. try:
  231. result = db.execute(text("""
  232. SELECT column_name FROM information_schema.columns
  233. WHERE table_name = 'ai_message'
  234. AND column_name IN ('search_info', 'search_results');
  235. """))
  236. columns = [row[0] for row in result.fetchall()]
  237. for column in ['search_info', 'search_results']:
  238. if column in columns:
  239. self.log_result(True, f"ai_message表包含 {column} 字段")
  240. else:
  241. self.log_result(False, f"ai_message表缺少 {column} 字段")
  242. except Exception as e:
  243. self.log_result(False, "检查ai_message表搜索字段失败", str(e))
  244. db.close()
  245. return True
  246. except Exception as e:
  247. self.log_result(False, "数据库表检查失败", str(e))
  248. return False
  249. def check_configuration_files(self) -> bool:
  250. """检查配置文件"""
  251. print("\n=== 配置文件检查 ===")
  252. try:
  253. # 检查.env文件
  254. env_files = [".env", ".env.example"]
  255. for env_file in env_files:
  256. if os.path.exists(env_file):
  257. self.log_result(True, f"配置文件 {env_file} 存在")
  258. # 检查是否包含搜索相关配置
  259. with open(env_file, 'r', encoding='utf-8') as f:
  260. content = f.read()
  261. search_configs = [
  262. "DASHSCOPE_API_KEY",
  263. "LLM_SEARCH_ENABLED",
  264. "VERTICAL_DOMAIN_ENABLED"
  265. ]
  266. for config in search_configs:
  267. if config in content:
  268. self.log_result(True, f"{env_file} 包含 {config} 配置")
  269. else:
  270. self.log_result(False, f"{env_file} 缺少 {config} 配置")
  271. else:
  272. self.log_result(False, f"配置文件 {env_file} 不存在")
  273. return True
  274. except Exception as e:
  275. self.log_result(False, "配置文件检查失败", str(e))
  276. return False
  277. def generate_summary(self) -> Dict[str, Any]:
  278. """生成检查摘要"""
  279. total_checks = len(self.results)
  280. error_count = len(self.errors)
  281. success_count = total_checks - error_count
  282. return {
  283. "total_checks": total_checks,
  284. "success_count": success_count,
  285. "error_count": error_count,
  286. "success_rate": (success_count / total_checks * 100) if total_checks > 0 else 0,
  287. "errors": self.errors
  288. }
  289. def run_all_checks(self) -> bool:
  290. """运行所有检查"""
  291. print("LLM搜索功能配置检查")
  292. print("=" * 60)
  293. checks = [
  294. ("环境变量配置", self.check_environment_variables),
  295. ("API连接", self.check_api_connection),
  296. ("模型支持", self.check_model_support),
  297. ("搜索选项验证", self.check_search_options_validation),
  298. ("垂直领域支持", self.check_vertical_domain_support),
  299. ("数据库表", self.check_database_tables),
  300. ("配置文件", self.check_configuration_files)
  301. ]
  302. all_passed = True
  303. for check_name, check_func in checks:
  304. try:
  305. result = check_func()
  306. if not result:
  307. all_passed = False
  308. except Exception as e:
  309. self.log_result(False, f"{check_name}检查异常", str(e))
  310. all_passed = False
  311. # 生成摘要
  312. summary = self.generate_summary()
  313. print("\n" + "=" * 60)
  314. print("检查摘要")
  315. print("=" * 60)
  316. print(f"总检查项: {summary['total_checks']}")
  317. print(f"成功: {summary['success_count']}")
  318. print(f"失败: {summary['error_count']}")
  319. print(f"成功率: {summary['success_rate']:.1f}%")
  320. if summary['error_count'] > 0:
  321. print(f"\n失败的检查项:")
  322. for i, error in enumerate(summary['errors'], 1):
  323. print(f" {i}. {error}")
  324. if all_passed:
  325. print("\n🎉 所有配置检查通过!搜索功能已准备就绪。")
  326. else:
  327. print("\n⚠️ 部分配置检查失败,请根据上述错误信息进行修复。")
  328. return all_passed
  329. def main():
  330. """主函数"""
  331. checker = SearchConfigChecker()
  332. try:
  333. success = checker.run_all_checks()
  334. sys.exit(0 if success else 1)
  335. except KeyboardInterrupt:
  336. print("\n\n检查被用户中断")
  337. sys.exit(1)
  338. except Exception as e:
  339. print(f"\n\n检查过程中发生异常: {e}")
  340. sys.exit(1)
  341. if __name__ == "__main__":
  342. main()