安装
uv pip install "googlesearch-python>=1.3.0"
import asyncio
from typing import List
from googlesearch import search
from app.tool.base import BaseTool
class GoogleSearch(BaseTool):
name: str = "google_search"
description: str = """Perform a Google search and return a list of relevant links.
Use this tool when you need to find information on the web, get up-to-date data, or research specific topics.
The tool returns a list of URLs that match the search query.
"""
parameters: dict = {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "(required) The search query to submit to Google.",
},
"num_results": {
"type": "integer",
"description": "(optional) The number of search results to return. Default is 10.",
"default": 10,
},
},
"required": ["query"],
}
def __call__(self, query: str, num_results: int = 10) -> List[str]:
"""
Synchronous Google search (for normal use in scripts).
"""
return list(search(query, num_results=num_results))
async def execute(self, query: str, num_results: int = 10) -> List[str]:
"""
Asynchronous Google search (for async environments).
Runs the search in a thread pool to avoid blocking the event loop.
"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, lambda: self(query, num_results))
GoogleSearch
是一个继承自 BaseTool
的工具类,用于通过 Google 搜索引擎获取与某个关键词相关的链接列表。
支持同步调用(__call__
)
适合在普通脚本中直接使用,比如:
tool = GoogleSearch()
print(tool("Python教程"))
支持异步调用(execute
)
适合在异步环境中使用,比如:
async def main():
tool = GoogleSearch()
result = await tool.execute("Python教程")
print(result)
asyncio.run(main())
query
: 要搜索的关键词(必填)num_results
: 返回的结果数量,默认是 10(可选)