跳转至

Gemini Search Tool(Google 搜索接地)

Gemini 系列模型在本平台既可以通过 Google 原生 Generate Content 接口 使用工具(tools),也可以通过 OpenAI Chat Completions 兼容接口 使用。
本文重点介绍 如何在新 API 平台下,为 Gemini 启用 Google Search Grounding(联网搜索)工具,并对照 Google 官方 REST 示例。


🌐 使用 Google 搜索建立依据(概览)

Google 搜索工具 google_search 可以把 Gemini 模型与实时互联网内容连接起来,让回答:

  • 更真实可靠:基于实时网页内容生成,降低幻觉
  • 支持实时信息:回答最近事件、时效性很强的问题
  • 带引用来源:通过 groundingMetadata 字段返回网页链接和引文片段,便于在前端展示可点击引用

对比 OpenAI 的 Web search 工具(见 gpt/search-tool,参考 OpenAI Web search 文档),Gemini 的 google_search 在设计上非常类似:
只要在请求中开启工具,模型就会根据需要自动决定是否发起搜索,并在响应中携带结构化引用信息。


🧩 基础 REST 调用示例(curl)

以下示例演示如何在本平台和 Google 官方接口中开启 google_search 工具,询问 2024 欧洲杯冠军。

本站 REST 示例(通过新 API 网关)

curl "https://api-cs-al.naci-tech.com/v1beta/models/gemini-3-flash-preview:generateContent?key=$API_KEY" \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "谁赢得了 2024 年欧洲杯?请给出答案,并附上 2~3 个参考链接。"
          }
        ]
      }
    ],
    "tools": [
      {
        "google_search": {}
      }
    ]
  }'

Google 官方 REST 示例

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          { "text": "Who won the Euro 2024? Please provide 2-3 reference links." }
        ]
      }
    ],
    "tools": [
      {
        "google_search": {}
      }
    ]
  }'

两者的 请求体完全兼容,差异主要在于:

  • 网关域名与鉴权方式:本站通过 https://api-cs-al.naci-tech.com/... + $API_KEY,Google 官方通过 https://generativelanguage.googleapis.com/... + $GEMINI_API_KEY
  • 模型名称:建议使用官方支持 google_search 的最新 Gemini 3 / 2.5 模型(见下文“支持的模型”)。

⚙️ 工作原理(How grounding works)

参考 Google 官方文档,当你在请求中启用 google_search 工具后,整体流程如下:

  1. 用户请求:你的应用将用户问题(如“谁赢得了 2024 年欧洲杯?”)连同 google_search 工具一起发送到 Gemini API。
  2. 提示分析:模型会先分析当前问题,判断是否需要调用 Google Search 来提升回答质量。
  3. 自动搜索:若认为搜索有帮助,模型会自动构造一个或多个搜索查询并调用 Google Search。
  4. 结果处理:模型读取搜索结果、综合多方信息,并生成最终回答。
  5. 返回接地响应:API 返回的候选中会包含普通文本回答以及 groundingMetadata 字段,指出该回答是基于哪些网页内容得到的。

对于开发者而言,使用体验非常简单:
只需要在请求中启用 google_search 工具,其余由模型与 Google Search 自动处理。


📦 理解响应:groundingMetadata 结构

当 Gemini 使用了 Google 搜索建立依据后,响应中的某个候选(candidates[i])会带有 groundingMetadata 字段。下面是一个精简示例:

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "西班牙在 2024 年欧洲杯决赛中 2:1 战胜英格兰,获得冠军。"
          }
        ],
        "role": "model"
      },
      "groundingMetadata": {
        "webSearchQueries": [
          "UEFA Euro 2024 winner",
          "who won euro 2024"
        ],
        "groundingChunks": [
          { "web": { "uri": "https://www.uefa.com/...", "title": "UEFA.com" } },
          { "web": { "uri": "https://www.aljazeera.com/...", "title": "Al Jazeera" } }
        ],
        "groundingSupports": [
          {
            "segment": {
              "startIndex": 0,
              "endIndex": 50,
              "text": "西班牙在 2024 年欧洲杯决赛中 2:1 战胜英格兰"
            },
            "groundingChunkIndices": [0, 1]
          }
        ]
      }
    }
  ]
}

其中关键字段含义与官方文档一致:

  • webSearchQueries:模型实际发出的搜索查询列表,有助于调试与理解模型搜索意图。
  • groundingChunks:每个元素代表一个外部网页来源(例如 urititle),类似“引用源列表”。
  • groundingSupports:把模型回答中的某个文本片段(segment.startIndex ~ segment.endIndex)与一个或多个 groundingChunks 关联起来,即“这个片段基于哪些网页内容”。

借助这些字段,你可以在前端构建细粒度的引用展示(如在句子后显示 [1][2]),让用户能够直接点击跳转到对应来源。


🔗 在前端显示内联引用(Inline citations)

Google 官方文档提供了 Python / JavaScript 示例,演示如何把 groundingSupportsgroundingChunks 转换为带 内联引用 的文本。
这里用伪代码说明常见的处理模式(逻辑与官方文档一致,但做了简化说明):

  1. 从响应中取出:
  2. 原始文本:text = candidate.content.parts[0].text
  3. 支持数组:supports = candidate.groundingMetadata.groundingSupports
  4. 引用源数组:chunks = candidate.groundingMetadata.groundingChunks
  5. segment.endIndex 从大到小排序 supports,避免在插入引用时破坏后续索引。
  6. 对每个 support
  7. 读取 support.groundingChunkIndices,查找对应的 chunks[i].web.uri
  8. 为每个索引构造引用字符串,如 [1](uri1), [2](uri2)
  9. 把拼好的引用字符串插入到 textsegment.endIndex 位置之后。
  10. 最终返回带 Markdown 链接的 text_with_citations,可直接在前端渲染。

伪代码示意(JavaScript 风格):

function addCitations(response) {
  let text = response.text;
  const supports = response.candidates[0]?.groundingMetadata?.groundingSupports ?? [];
  const chunks = response.candidates[0]?.groundingMetadata?.groundingChunks ?? [];

  const sortedSupports = [...supports].sort(
    (a, b) => (b.segment?.endIndex ?? 0) - (a.segment?.endIndex ?? 0)
  );

  for (const support of sortedSupports) {
    const endIndex = support.segment?.endIndex;
    if (endIndex == null || !support.groundingChunkIndices?.length) continue;

    const citationLinks = support.groundingChunkIndices
      .map((i) => {
        const uri = chunks[i]?.web?.uri;
        return uri ? `[${i + 1}](${uri})` : null;
      })
      .filter(Boolean);

    if (citationLinks.length > 0) {
      const citationString = citationLinks.join(", ");
      text = text.slice(0, endIndex) + citationString + text.slice(endIndex);
    }
  }

  return text;
}

你可以在此基础上,自定义 UI 展示样式(例如鼠标悬浮展示网页标题、在新标签页打开链接等)。


✅ 支持的模型(Supported models)

根据 Google 官方文档,目前以下模型支持 Grounding with Google Search(google_search 工具):

模型 是否支持 Google Search Grounding
gemini-3.1-flash-image-preview ✔︎
gemini-3.1-pro-preview ✔︎
gemini-3-pro-image-preview ✔︎
gemini-3-flash-preview ✔︎
gemini-2.5-pro ✔︎
gemini-2.5-flash ✔︎
gemini-2.5-flash-lite ✔︎
gemini-2.0-flash ✔︎

注意:更老的模型曾使用 google_search_retrieval 工具;对于当前模型,请统一使用 google_search

在本平台调用时,建议优先选择最新一代的 Gemini 3 / 2.5 模型,例如:

  • 快速场景:gemini-3-flash-previewgemini-2.5-flash
  • 高精度场景:gemini-3.1-pro-previewgemini-2.5-pro