my_advanced_search.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # my_advanced_search.py
  2. import os
  3. from typing import Optional, List, Dict, Any
  4. from hello_agents import ToolRegistry
  5. class MyAdvancedSearchTool:
  6. """
  7. 自定义高级搜索工具类
  8. 展示多源整合和智能选择的设计模式
  9. """
  10. def __init__(self):
  11. self.name = "my_advanced_search"
  12. self.description = "智能搜索工具,支持多个搜索源,自动选择最佳结果"
  13. self.search_sources = []
  14. self._setup_search_sources()
  15. def _setup_search_sources(self):
  16. """设置可用的搜索源"""
  17. # 检查Tavily可用性
  18. if os.getenv("TAVILY_API_KEY"):
  19. try:
  20. from tavily import TavilyClient
  21. self.tavily_client = TavilyClient(api_key=os.getenv("TAVILY_API_KEY"))
  22. self.search_sources.append("tavily")
  23. print("✅ Tavily搜索源已启用")
  24. except ImportError:
  25. print("⚠️ Tavily库未安装")
  26. # 检查SerpApi可用性
  27. if os.getenv("SERPAPI_API_KEY"):
  28. try:
  29. import serpapi
  30. self.search_sources.append("serpapi")
  31. print("✅ SerpApi搜索源已启用")
  32. except ImportError:
  33. print("⚠️ SerpApi库未安装")
  34. if self.search_sources:
  35. print(f"🔧 可用搜索源: {', '.join(self.search_sources)}")
  36. else:
  37. print("⚠️ 没有可用的搜索源,请配置API密钥")
  38. def search(self, query: str) -> str:
  39. """执行智能搜索"""
  40. if not query.strip():
  41. return "❌ 错误:搜索查询不能为空"
  42. # 检查是否有可用的搜索源
  43. if not self.search_sources:
  44. return """❌ 没有可用的搜索源,请配置以下API密钥之一:
  45. 1. Tavily API: 设置环境变量 TAVILY_API_KEY
  46. 获取地址: https://tavily.com/
  47. 2. SerpAPI: 设置环境变量 SERPAPI_API_KEY
  48. 获取地址: https://serpapi.com/
  49. 配置后重新运行程序。"""
  50. print(f"🔍 开始智能搜索: {query}")
  51. # 尝试多个搜索源,返回最佳结果
  52. for source in self.search_sources:
  53. try:
  54. if source == "tavily":
  55. result = self._search_with_tavily(query)
  56. if result and "未找到" not in result:
  57. return f"📊 Tavily AI搜索结果:\n\n{result}"
  58. elif source == "serpapi":
  59. result = self._search_with_serpapi(query)
  60. if result and "未找到" not in result:
  61. return f"🌐 SerpApi Google搜索结果:\n\n{result}"
  62. except Exception as e:
  63. print(f"⚠️ {source} 搜索失败: {e}")
  64. continue
  65. return "❌ 所有搜索源都失败了,请检查网络连接和API密钥配置"
  66. def _search_with_tavily(self, query: str) -> str:
  67. """使用Tavily搜索"""
  68. response = self.tavily_client.search(query=query, max_results=3)
  69. if response.get('answer'):
  70. result = f"💡 AI直接答案:{response['answer']}\n\n"
  71. else:
  72. result = ""
  73. result += "🔗 相关结果:\n"
  74. for i, item in enumerate(response.get('results', [])[:3], 1):
  75. result += f"[{i}] {item.get('title', '')}\n"
  76. result += f" {item.get('content', '')[:150]}...\n\n"
  77. return result
  78. def _search_with_serpapi(self, query: str) -> str:
  79. """使用SerpApi搜索"""
  80. import serpapi
  81. search = serpapi.GoogleSearch({
  82. "q": query,
  83. "api_key": os.getenv("SERPAPI_API_KEY"),
  84. "num": 3
  85. })
  86. results = search.get_dict()
  87. result = "🔗 Google搜索结果:\n"
  88. if "organic_results" in results:
  89. for i, res in enumerate(results["organic_results"][:3], 1):
  90. result += f"[{i}] {res.get('title', '')}\n"
  91. result += f" {res.get('snippet', '')}\n\n"
  92. return result
  93. def create_advanced_search_registry():
  94. """创建包含高级搜索工具的注册表"""
  95. registry = ToolRegistry()
  96. # 创建搜索工具实例
  97. search_tool = MyAdvancedSearchTool()
  98. # 注册搜索工具的方法作为函数
  99. registry.register_function(
  100. name="advanced_search",
  101. description="高级搜索工具,整合Tavily和SerpAPI多个搜索源,提供更全面的搜索结果",
  102. func=search_tool.search
  103. )
  104. return registry