base_agent/tools/web_search.py

66 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""网络搜索工具"""
# ════════════════════════════════════════════════════════════════
# tools/web_search.py — 网络搜索工具(模拟)
# ════════════════════════════════════════════════════════════════
"""
tools/web_search.py
网络搜索工具Demo 中使用模拟数据,生产环境可替换为真实 API
"""
import time
from tools.base_tool import BaseTool, ToolResult
# 模拟搜索结果数据库
_MOCK_RESULTS: dict[str, list[dict]] = {
"天气": [
{"title": "今日天气预报", "snippet": "晴转多云,气温 15°C ~ 24°C东南风 3 级"},
{"title": "未来 7 天天气", "snippet": "本周整体晴好,周末有小雨"},
],
"python": [
{"title": "Python 官方文档", "snippet": "Python 3.12 新特性:改进的错误提示、更快的启动速度"},
{"title": "Python 教程", "snippet": "从零开始学 Python包含 300+ 实战案例"},
],
}
_DEFAULT_RESULTS = [
{"title": "搜索结果 1", "snippet": "找到相关内容,请查看详情"},
{"title": "搜索结果 2", "snippet": "更多相关信息可通过链接访问"},
]
class WebSearchTool(BaseTool):
name = "web_search"
description = "在互联网上搜索信息,返回相关网页摘要"
parameters = {
"query": {
"type": "string",
"description": "搜索关键词或问题",
},
"max_results": {
"type": "integer",
"description": "返回结果数量,默认 3",
},
}
def execute(self, query: str, max_results: int = 3, **_) -> ToolResult:
time.sleep(0.1) # 模拟网络延迟
# 关键词匹配模拟结果
results = _DEFAULT_RESULTS
for keyword, data in _MOCK_RESULTS.items():
if keyword in query:
results = data
break
results = results[:max_results]
formatted = "\n".join(
f"[{i+1}] {r['title']}\n {r['snippet']}"
for i, r in enumerate(results)
)
return ToolResult(
success=True,
output=f"搜索「{query}」,共 {len(results)} 条结果:\n{formatted}",
metadata={"query": query, "count": len(results)},
)