返回到文章

采纳

编辑于 12天前

Python实现GoogleSearch

python

安装

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(可选)

适用场景

  • 需要获取实时数据、网页链接
  • 用于信息检索、内容扩展、生成提示词等场景
  • 可在异步框架(如 FastAPI、LangChain 等)中灵活嵌入