Gemini API:深度研究智能体

本文深入解析 Gemini API 的 Deep Research Agent,涵盖其异步交互模型、协作规划、可视化、流式传输、工具配置及多模态输入等核心能力。通过代码示例与配置详解,帮助开发者掌握构建自主研究系统的工程实践,并针对常见错误与生产环境优化提供实用建议。

技术背景

传统搜索与问答难以满足复杂研究需求,如市场分析、文献综述等,需要多步骤规划、信息综合与引用生成。Deep Research Agent 基于 Gemini 模型,自主执行搜索、阅读、代码执行等任务,单次可查阅超 100 个来源,生成带引用的报告。其通过 Interactions API 异步运行,适合耗时较长的研究任务,但无法通过 generate_content 访问,且需注意异步轮询与状态管理。

核心原理

Deep Research Agent 采用规划-执行-综合的自主循环:接收用户输入后,模型规划研究步骤,调用工具(如 Google 搜索、URL 上下文、代码执行)收集信息,分析并综合生成报告。协作规划模式允许用户审查和迭代计划,确保研究方向正确。可视化功能自动生成图表,流式传输提供实时进度。工具配置可限制或扩展代理能力,MCP 服务器与文件搜索支持私有数据集成。

架构分析

系统基于 Interactions API,支持异步任务(background=True)与流式传输(stream=True)。核心组件包括:代理(agent)定义研究行为,agent_config 控制规划、可视化等参数,工具列表(tools)决定数据源,previous_interaction_id 实现多轮对话。轮询机制通过 client.interactions.get 获取状态,流式事件(interaction.start, content.delta, interaction.complete)驱动实时更新。设计上强调异步解耦,便于长时间任务管理。

完整实战教程

##### 版权所有 2026 Google LLC.

# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Gemini API:深度研究智能体

<a class="tfo-notebook-buttons" target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_Deep_Research.ipynb">

</a>

Deep Research Agent 能够自主规划、执行并综合多步骤研究任务,生成详细且带有引用的报告。它由 Gemini 驱动,能够驾驭复杂的信息环境——搜索网页、阅读页面、执行代码以及分析文档——在几分钟内生成全面的报告。

Deep Research 非常适合市场分析、竞争情报、文献综述和技术深度研究,这些场景需要的不只是简单答案。它可以在单个任务中查阅超过 100 个来源。

Deep Research 仅通过 Interactions API 提供,无法通过 generate_content 访问。研究任务在后台异步运行,因为完成可能需要几分钟时间。

文档 是开始了解 Deep Research Agent 的好地方。

设置

设置你的 API 密钥

要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab Secret 中。如果你还没有 API 密钥,或者不确定如何创建 Colab Secret,请参阅 身份验证。

image(有关示例,请参阅](../quickstarts/Authentication.ipynb)。

from google.colab import userdata

GEMINI_API_KEY=userdata.get('GEMINI_API_KEY')

安装并初始化 SDK

%pip install -U -q "google-genai>=2.9.0"
import time
import base64
from google import genai
from IPython.display import display, Image, Markdown

client = genai.Client(api_key=GEMINI_API_KEY)

选择深度研究代理

提供两个版本的深度研究代理:

AGENT = "deep-research-preview-04-2026" # @param ["deep-research-preview-04-2026","deep-research-max-preview-04-2026"] {"allow-input":true, isTemplate: true}

接下来,创建辅助函数来轮询结果并显示输出:

# @title Helper functions (just run this cell)

def wait_for_result(interaction, poll_interval=10):
    """Poll until a background interaction completes or fails."""
    print(f"Research started: {interaction.id}")
    while True:
        result = client.interactions.get(interaction.id)
        if result.status == "completed":
            return result
        elif result.status == "failed":
            print(f"Research failed: {result.error}")
            return result
        print(f"  Status: {result.status}", flush=True)
        time.sleep(poll_interval)


def display_outputs(result):
    """Display text and image outputs from a completed interaction."""
    for step in result.steps:
        if step.type == "model_output" and step.content:
            for content in step.content:
                if content.type == "text":
                    display(Markdown(content.text))
                elif content.type == "image" and content.data:
                    image_bytes = base64.b64decode(content.data)
                    display(Image(data=image_bytes))

运行你的第一个深度研究任务

使用 background=True 启动一个研究任务,并轮询获取结果。深度研究是异步的——由于代理需要规划、搜索、阅读和综合信息,任务可能需要几分钟时间。

interaction = client.interactions.create(
    input="Research the history of Google TPUs and their impact on AI development.",
    agent=AGENT,
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)

协作规划

协作规划允许你在智能体开始工作之前审查和完善研究计划。启用后,智能体会返回一个提议的计划,而不是立即执行。你可以通过多轮交互来迭代该计划。

步骤 1:请求计划

在 agent_config 中设置 collaborative_planning=True。智能体会返回一个研究计划,而不是完整的报告。

plan_interaction = client.interactions.create(
    agent=AGENT,
    input="Research Google TPUs vs competitor AI accelerator hardware.",
    agent_config={
        "type": "deep-research",
        "collaborative_planning": True,
    },
    background=True,
)

result = wait_for_result(plan_interaction)
display_outputs(result)

第二步:优化计划(可选)

使用 previous_interaction_id 继续对话并迭代计划。保持 collaborative_planning=True 以停留在规划模式。你可以根据需要重复此步骤多次。

refined_plan = client.interactions.create(
    agent=AGENT,
    input="Add a section comparing power efficiency and total cost of ownership.",
    agent_config={
        "type": "deep-research",
        "collaborative_planning": True,
    },
    previous_interaction_id=plan_interaction.id,
    background=True,
)

result = wait_for_result(refined_plan)
display_outputs(result)

步骤 3:批准并执行

设置 collaborative_planning=False 以批准计划并开始完整研究。代理将执行计划并返回最终报告。

重要提示: 您必须在最后一轮明确设置 collaborative_planning=False。仅发送“继续”而不切换该标志不会触发报告生成。
final_report = client.interactions.create(
    agent=AGENT,
    input="Plan looks good!",
    agent_config={
        "type": "deep-research",
        "collaborative_planning": False,
    },
    previous_interaction_id=refined_plan.id,
    background=True,
)

result = wait_for_result(final_report)
display_outputs(result)

内置图表与信息图

在 agent_config 中设置 visualization="auto" 以启用代理生成的图表、图形和信息图。为获得最佳效果,请在查询中明确要求可视化内容——例如,“包含显示趋势的图表”或“生成比较市场份额的图形”。

interaction = client.interactions.create(
    agent=AGENT,
    input="Analyze global semiconductor market trends from 2020 to 2025. Include charts showing market share changes between the top vendors.",
    agent_config={
        "type": "deep-research",
        "visualization": "auto",
    },
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)
提示: 设置 visualization="auto" 可启用该功能,但代理仅在提示请求时生成可视化内容。请明确说明您想要的图表或图形。

实时流式传输

实时流式传输研究进度,而不是等待最终结果。设置 stream=True 并配合 background=True。启用 thinking_summaries="auto" 以查看代理工作时的中间推理步骤。

流事件类型

| 事件类型 | 增量类型 | 描述 |

| :--- | :--- | :--- |

| interaction.start | — | 提供交互 ID |

| content.delta | thought_summary | 中间推理步骤 |

| content.delta | text | 最终文本输出的一部分 |

| content.delta | image | 生成的图像(base64 编码) |

| interaction.complete | — | 研究已完成 |

stream = client.interactions.create(
    input="Research AI chip market trends. Include charts comparing major vendors.",
    agent=AGENT,
    background=True,
    stream=True,
    agent_config={
        "type": "deep-research",
        "thinking_summaries": "auto",
        "visualization": "auto",
    },
)

interaction_id = None
last_event_id = None
is_complete = False

def process_stream(stream):
    global interaction_id, last_event_id, is_complete
    for chunk in stream:
        if chunk.event_type == "interaction.start":
            interaction_id = chunk.interaction.id
            print(f"Interaction started: {interaction_id}")
        if chunk.event_id:
            last_event_id = chunk.event_id
        if chunk.event_type == "content.delta":
            if chunk.delta.type == "text":
                print(chunk.delta.text, end="", flush=True)
            elif chunk.delta.type == "thought_summary":
                print(f"\n💭 {chunk.delta.content.text}", flush=True)
            elif chunk.delta.type == "image" and chunk.delta.data:
                image_bytes = base64.b64decode(chunk.delta.data)
                display(Image(data=image_bytes))
        elif chunk.event_type in ("interaction.complete", "error"):
            is_complete = True
            if chunk.event_type == "interaction.complete":
                print("\n\n✅ Research Complete")

process_stream(stream)

# Reconnect if the connection drops
while not is_complete and interaction_id:
    status = client.interactions.get(interaction_id)
    if status.status != "in_progress":
        break
    print("\n🔄 Reconnecting...")
    stream = client.interactions.get(
        id=interaction_id, stream=True, last_event_id=last_event_id,
    )
    process_stream(stream)

工具配置

默认情况下,代理使用 Google 搜索、URL 上下文和代码执行。您可以通过传递 tools 列表来自定义工具。这使您可以将代理限制为仅进行网络搜索、仅使用私有来源,或两者兼用。

| 工具 | 类型值 | 默认 | 描述 |

| :--- | :--- | :--- | :--- |

| Google 搜索 | google_search | ✅ | 搜索公共网络 |

| URL 上下文 | url_context | ✅ | 读取并总结网页 |

| 代码执行 | code_execution | ✅ | 运行代码以进行计算和数据分析 |

| MCP 服务器 | mcp_server | — | 连接远程 MCP 服务器 |

| 文件搜索 | file_search | — | 搜索上传的文档语料库 |

仅限制为 Google 搜索

interaction = client.interactions.create(
    agent=AGENT,
    input="What are the latest developments in quantum computing?",
    tools=[{"type": "google_search"}],
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)

组合多个工具

interaction = client.interactions.create(
    agent=AGENT,
    input="Research the latest breakthroughs in fusion energy. Include data analysis of funding trends.",
    tools=[
        {"type": "google_search"},
        {"type": "url_context"},
        {"type": "code_execution"},
    ],
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)

远程 MCP 服务器

连接远程 MCP(模型上下文协议) 服务器,让代理能够访问外部工具和服务。传入服务器 name、url 以及可选的认证请求头。

interaction = client.interactions.create(
    agent=AGENT,
    input="Check the status of my last server deployment.",
    tools=[
        {
            "type": "mcp_server",
            "name": "Deployment Tracker",
            "url": "https://mcp.example.com/mcp",
            "headers": {"Authorization": "Bearer YOUR_TOKEN"},
        }
    ],
    background=True,
)

你可以使用 allowed_tools 来限制代理可以从 MCP 服务器调用哪些工具:

interaction = client.interactions.create(
    agent=AGENT,
    input="Get recent tickets from our issue tracker.",
    tools=[
        {
            "type": "mcp_server",
            "name": "Issue Tracker",
            "url": "https://mcp.example.com/mcp",
            "headers": {"Authorization": "Bearer YOUR_TOKEN"},
            "allowed_tools": ["list_tickets", "get_ticket"],
        }
    ],
    background=True,
)
注意: MCP 服务器支持无认证、Bearer 令牌和 OAuth。对于 OAuth,请使用 google-auth 之类的库获取令牌,并通过 headers 传递。

文件搜索

通过使用 文件搜索,让代理访问您自己的数据。这使代理能够与网络一起搜索您上传的文档语料库。

interaction = client.interactions.create(
    input="Compare our 2025 fiscal year report against current public web news.",
    agent=AGENT,
    background=True,
    tools=[
        {
            "type": "file_search",
            "file_search_store_names": ["fileSearchStores/my-store-name"],
        }
    ],
)

result = wait_for_result(interaction)
display_outputs(result)

多模态输入

深度研究支持多模态输入,包括图像和文档(PDF)。智能体会分析所提供的内容,并基于这些输入进行网络研究。

图像输入

在文本提示中附带图像,使智能体的研究基于视觉内容。

interaction = client.interactions.create(
    input=[
        {
            "type": "text",
            "text": "Identify the architectural style shown in this image. Research its historical origins, key characteristics, and notable examples worldwide.",
        },
        {
            "type": "image",
            "uri": "https://storage.googleapis.com/generativeai-downloads/images/generated_elephants_giraffes_zebras_sunset.jpg",
        },
    ],
    agent=AGENT,
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)

文档输入(PDF)

直接将文档作为输入传入。智能体将分析该文档,并针对其内容在网络上进行研究。

interaction = client.interactions.create(
    agent=AGENT,
    input=[
        {"type": "text", "text": "What has been the impact of this research paper? Who are the key authors and what have they worked on since?"},
        {
            "type": "document",
            "uri": "https://arxiv.org/pdf/1706.03762",
            "mime_type": "application/pdf",
        },
    ],
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)

可控性与格式

通过在提示中提供明确的格式指令,可以控制输出的结构和语气。你可以要求特定的章节、数据表格,或针对不同受众调整语气。

prompt = """
Research the competitive landscape of EV batteries.

Format the output as a technical report with the following structure:
1. Executive Summary (max 200 words)
2. Key Players (Must include a data table comparing capacity, chemistry, and market share)
3. Technology Trends
4. Supply Chain Risks
5. Outlook for 2026-2030

Use a professional, technical tone suitable for an engineering audience.
"""

interaction = client.interactions.create(
    input=prompt,
    agent=AGENT,
    background=True,
)

result = wait_for_result(interaction)
display_outputs(result)

后续问题

收到报告后,您可以使用 previous_interaction_id 继续对话,询问澄清、总结或详细说明特定部分,而无需重新启动整个研究任务。

注意: 后续问题使用标准的 Gemini 模型(而非 Deep Research 代理),因此它们会立即返回,无需 background=True。
# Use the interaction ID from any completed research task above
follow_up = client.interactions.create(
    input="Summarize the key findings in 3 bullet points. What was the most surprising insight?",
    model="gemini-3.1-pro-preview",
    previous_interaction_id=interaction.id,
)

display(Markdown(follow_up.output_text))

Agent 配置参考

Deep Research 使用 agent_config 参数来控制行为。以下是所有可配置字段的摘要:

| 字段 | 类型 | 默认值 | 描述 |

| :--- | :--- | :--- | :--- |

| type | string | 必填 | 必须为 "deep-research" |

| thinking_summaries | string | "none" | 设置为 "auto" 以在流式传输期间接收中间推理步骤 |

| visualization | string | "auto" | 设置为 "auto" 以启用图表和图像;设置为 "off" 以禁用 |

| collaborative_planning | boolean | false | 设置为 true 以在研究前启用多轮计划审查 |

# Example: all options enabled
interaction = client.interactions.create(
    agent=AGENT,
    input="Research the competitive landscape of cloud GPUs.",
    agent_config={
        "type": "deep-research",
        "thinking_summaries": "auto",
        "visualization": "auto",
        "collaborative_planning": False,
    },
    background=True,
    stream=True,
)

延伸阅读

常见问题

常见错误:1) 未设置 GEMINI_API_KEY 导致认证失败,需在 Colab Secret 中配置。2) 使用 generate_content 调用 Deep Research 报错,应改用 interactions.create。3) 协作规划中未设置 collaborative_planning=False 导致无法生成报告,需在最终轮显式关闭。4) 流式连接断开,需实现重连逻辑(如示例中的 while 循环)。5) MCP 服务器认证失败,需正确传递 headers。排查时检查 API 密钥、参数配置、网络状态,并利用流式事件调试。

企业应用扩展

生产环境优化:1) 使用异步回调或消息队列处理任务,避免阻塞。2) 实现指数退避重试策略,应对轮询超时。3) 缓存研究结果,减少重复调用。4) 结合文件搜索与私有数据,提升相关性。5) 利用协作规划确保研究质量,减少返工。6) 监控 API 配额与成本,设置预算告警。7) 对输出进行后处理,提取结构化数据。8) 考虑使用 deep-research-max 代理获取更全面报告,但需权衡延迟与成本。

总结

本文深入解析 Gemini API 的 Deep Research Agent,涵盖其异步交互模型、协作规划、可视化、流式传输、工具配置及多模态输入等核心能力。通过代码示例与配置详解,帮助开发者掌握构建自主研究系统的工程实践,并针对常见错误与生产环境优化提供实用建议。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部AI 智能体教程