|
|
@@ -203,29 +203,46 @@ SERPAPI_API_KEY="YOUR_SERPAPI_API_KEY"
|
|
|
我们的第一个工具是 `search` 函数,它的作用是接收一个查询字符串,然后返回搜索结果。
|
|
|
|
|
|
```python
|
|
|
-from ddgs import DDGS
|
|
|
+from serpapi import SerpApiClient
|
|
|
|
|
|
def search(query: str) -> str:
|
|
|
"""
|
|
|
- 一个网页搜索引擎工具。
|
|
|
- 它使用 DuckDuckGo 来搜索并返回排名前3的结果摘要。
|
|
|
+ 一个基于SerpApi的实战网页搜索引擎工具。
|
|
|
+ 它会智能地解析搜索结果,优先返回直接答案或知识图谱信息。
|
|
|
"""
|
|
|
- print(f"🔍 正在执行真实网页搜索: {query}")
|
|
|
+ print(f"🔍 正在执行 [SerpApi] 网页搜索: {query}")
|
|
|
try:
|
|
|
- # 使用 with 上下文管理器确保资源被正确处理
|
|
|
- with DDGS() as ddgs:
|
|
|
- # max_results 控制返回结果的数量
|
|
|
- results = [r for r in ddgs.text(query, max_results=3)]
|
|
|
+ api_key = os.getenv("SERPAPI_API_KEY")
|
|
|
+ if not api_key:
|
|
|
+ return "错误:SERPAPI_API_KEY 未在 .env 文件中配置。"
|
|
|
+
|
|
|
+ params = {
|
|
|
+ "engine": "google",
|
|
|
+ "q": query,
|
|
|
+ "api_key": api_key,
|
|
|
+ "gl": "cn", # 国家代码
|
|
|
+ "hl": "zh-cn", # 语言代码
|
|
|
+ }
|
|
|
|
|
|
- if not results:
|
|
|
- return f"对不起,没有找到关于 '{query}' 的信息。"
|
|
|
+ client = SerpApiClient(params)
|
|
|
+ results = client.get_dict()
|
|
|
|
|
|
- # 将结果格式化为对LLM友好的字符串
|
|
|
- result_strings = []
|
|
|
- for i, result in enumerate(results):
|
|
|
- result_strings.append(f"[{i+1}] {result['title']}\n{result['body']}")
|
|
|
+ # 智能解析:优先寻找最直接的答案
|
|
|
+ if "answer_box_list" in results:
|
|
|
+ return "\n".join(results["answer_box_list"])
|
|
|
+ if "answer_box" in results and "answer" in results["answer_box"]:
|
|
|
+ return results["answer_box"]["answer"]
|
|
|
+ if "knowledge_graph" in results and "description" in results["knowledge_graph"]:
|
|
|
+ return results["knowledge_graph"]["description"]
|
|
|
+ if "organic_results" in results and results["organic_results"]:
|
|
|
+ # 如果没有直接答案,则返回前三个有机结果的摘要
|
|
|
+ snippets = [
|
|
|
+ f"[{i+1}] {res.get('title', '')}\n{res.get('snippet', '')}"
|
|
|
+ for i, res in enumerate(results["organic_results"][:3])
|
|
|
+ ]
|
|
|
+ return "\n\n".join(snippets)
|
|
|
|
|
|
- return "\n\n".join(result_strings)
|
|
|
+ return f"对不起,没有找到关于 '{query}' 的信息。"
|
|
|
|
|
|
except Exception as e:
|
|
|
return f"搜索时发生错误: {e}"
|