You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在google-generativeai包中为Gemini模型启用联网搜索功能?

为Gemini模型添加联网搜索功能的实现方法

Gemini模型的联网搜索需要通过工具调用机制实现,你需要先实现搜索逻辑,将其注册为模型可调用的工具,再处理模型的工具调用请求并返回搜索结果,最终由模型生成整合后的响应。

步骤1:准备搜索服务(以Google Custom Search API为例)

你需要先申请Google Custom Search API密钥和搜索引擎ID:

  • API密钥:在Google Cloud控制台创建
  • 搜索引擎ID:在Google Custom Search控制台创建

安装依赖库:

pip install google-generativeai google-api-python-client

步骤2:实现搜索函数并定义工具

from google.generativeai import configure, GenerativeModel, Tool
from googleapiclient.discovery import build

# 配置Gemini API密钥
configure(api_key="你的Gemini API密钥")

# 配置Google Custom Search服务
SEARCH_API_KEY = "你的Custom Search API密钥"
SEARCH_ENGINE_ID = "你的搜索引擎ID"
search_service = build("customsearch", "v1", developerKey=SEARCH_API_KEY)

# 定义搜索函数
def web_search(query: str) -> str:
    """执行联网搜索并返回结果摘要"""
    result = search_service.cse().list(q=query, cx=SEARCH_ENGINE_ID, num=3).execute()
    items = result.get("items", [])
    if not items:
        return "未找到相关搜索结果"
    # 整理搜索结果为字符串
    search_results = []
    for idx, item in enumerate(items, 1):
        search_results.append(f"{idx}. 标题: {item['title']}\n链接: {item['link']}\n摘要: {item.get('snippet', '无摘要')}\n")
    return "\n".join(search_results)

# 将搜索函数注册为Gemini可调用的工具
search_tool = Tool(
    function_declaration={
        "name": "web_search",
        "description": "当需要获取实时信息、最新数据或网络上的公开内容时调用此工具,输入为搜索关键词",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "要搜索的关键词或问题"
                }
            },
            "required": ["query"]
        }
    },
    function=web_search
)

步骤3:调用模型并处理工具调用

# 初始化支持工具调用的Gemini模型
model = GenerativeModel(
    model_name="models/gemini-2.0-flash",
    tools=[search_tool]
)

# 发起请求并处理工具调用
chat = model.start_chat(history=[])
response = chat.send_message("2024年最新的Python版本是什么?")

# 检查模型是否需要调用工具
while response.candidates[0].content.parts[0].function_call:
    # 获取工具调用请求
    func_call = response.candidates[0].content.parts[0].function_call
    # 执行搜索函数
    search_result = web_search(func_call.args["query"])
    # 将搜索结果返回给模型
    response = chat.send_message(
        content=[{
            "function_response": {
                "name": "web_search",
                "response": {"result": search_result}
            }
        }]
    )

# 输出最终响应
print(response.text)

关键说明

  • 必须使用支持工具调用的Gemini模型(如gemini-2.0-flash、gemini-1.5-pro等)
  • 工具调用是多轮过程:模型先判断是否需要搜索,返回调用请求;你执行搜索后将结果返回,模型再生成最终回答
  • 除了Google Custom Search,你也可以替换为其他搜索服务(如SerpAPI、Bing Search API等),只需修改web_search函数的实现

内容的提问来源于stack exchange,提问作者soapergem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 21:59:57