使用 Google 搜索建立依据

本页面介绍了如何使用 Google 搜索引擎的结果(该搜索引擎使用公开提供的 Web 数据)为 Gemini 回答建立依据。此外,还说明了回答中包含的搜索建议。

如果您想将模型与世界知识、各种主题或互联网上的最新信息相连接,请使用“依托 Google 搜索进行接地”功能。

如需详细了解 Gemini Enterprise Agent Platform 中的模型接地功能, 请参阅接地概览

支持的模型

本部分列出了支持“依托搜索进行接地”的模型。

点击即可展开支持的模型

支持的语言

如需查看受支持的语言列表,请参阅 语言

请按照以下说明使用公开提供的 Web 数据为模型建立依据。

注意事项

  • 如需使用“依托 Google 搜索进行接地”,您必须启用 Google 搜索建议。如需了解详情,请参阅 使用 Google 搜索建议

  • 为了获得理想的结果,请使用 1.0 温度。如需详细了解如何设置此配置,请参阅模型参考文档中的 Gemini API 请求正文

  • “借助 Google 搜索接地”功能的查询次数上限为每天 100 万次。如果您需要更多查询,请与Google Cloud 支持团队联系以获取帮助。

您可以使用纬度和经度坐标,针对最终用户的特定地理位置自定义搜索结果。如需了解详情,请参阅 接地 API

控制台

如需将“依托 Google 搜索进行接地”与 Gemini Enterprise Agent Platform 上的 Agent Studio 搭配使用,请按照以下步骤操作:

  1. 在 Google Cloud 控制台中,前往 Agent Studio 页面。

    前往 Agent Studio

  2. 点击 Freeform 标签页。
  3. 在侧边栏中,点击让模型回答接地 切换开关。
  4. 点击自定义 ,并将“依托 Google 搜索进行接地”设置为来源。
  5. 在文本框中输入提示,然后点击提交

您的提示回答现在会使用“依托 Google 搜索进行接地”功能。

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import (
    GenerateContentConfig,
    GoogleSearch,
    HttpOptions,
    Tool,
)

client = genai.Client(http_options=HttpOptions(api_version="v1"))

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="When is the next total solar eclipse in the United States?",
    config=GenerateContentConfig(
        tools=[
            # Use Google Search Tool
            Tool(
                google_search=GoogleSearch(
                    # Optional: Domains to exclude from results
                    exclude_domains=["domain.com", "domain2.com"]
                )
            )
        ],
    ),
)

print(response.text)
# Example response:
# 'The next total solar eclipse in the United States will occur on ...'

Go

了解如何安装或更新 Go

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithGoogleSearch shows how to generate text using Google Search.
func generateWithGoogleSearch(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.5-flash"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "When is the next total solar eclipse in the United States?"},
		},
			Role: genai.RoleUser},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{GoogleSearch: &genai.GoogleSearch{ExcludeDomains: []string{"example.com", "example.org"}}},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// The next total solar eclipse in the United States will occur on March 30, 2033, but it will only ...

	return nil
}

Java

了解如何安装或更新 Java

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GoogleSearch;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Tool;

public class ToolsGoogleSearchWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    generateContent(modelId);
  }

  // Generates content with Google Search tool
  public static String generateContent(String modelId) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Create a GenerateContentConfig and set Google Search tool
      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId, "When is the next total solar eclipse in the United States?", contentConfig);

      System.out.print(response.text());
      // Example response:
      // The next total solar eclipse in the United States will occur on...
      return response.text();
    }
  }
}

Node.js

安装

npm install @google/genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateGoogleSearch(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: 'When is the next total solar eclipse in the United States?',
    config: {
      tools: [
        {
          googleSearch: {},
        },
      ],
    },
  });

  console.log(response.text);

  // Example response:
  //    'The next total solar eclipse in United States will occur on ...'

  return response.text;
}

REST

在使用任何请求数据之前, 请先进行以下替换:

  • LOCATION:处理请求的区域。 如需使用全球端点, 请清除端点名称中的相应位置,并将资源位置配置为全球。
  • PROJECT_ID: 您的 [项目 ID](/resource-manager/docs/creating-managing-projects#identifiers)。 。
  • MODEL_ID:多模态模型的模型 ID。
  • TEXT:要包含在提示中的文本说明。
  • EXCLUDE_DOMAINS:可选:不用于接地的网域列表。
  • LATITUDE:可选:最终用户所在位置的纬度。例如,纬度 37.7749 表示旧金山。您可以使用 Google 地图或其他地理编码工具等服务获取纬度和经度坐标。
  • LONGITUDE:可选:最终用户所在位置的经度。例如,经度 -122.4194 表示旧金山。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

请求 JSON 正文:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "tools": [{
    "googleSearch": {
      "exclude_domains": [ "domain.com", "domain2.com" ]
    }
  }],
  "toolConfig": {
    "retrievalConfig": {
      "latLng": {
        "latitude": LATITUDE,
        "longitude": LONGITUDE
      }
    }
  },
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "The weather in Chicago this weekend, will be partly cloudy. The temperature will be between 49°F (9°C) and 55°F (13°C) on Saturday and between 51°F (11°C) and 56°F (13°C) on Sunday. There is a slight chance of rain on both days.\n"
          }
        ]
      },
      "finishReason": "STOP",
      "groundingMetadata": {
        "webSearchQueries": [
          "weather in Chicago this weekend"
        ],
        "searchEntryPoint": {
          "renderedContent": "..."
        },
        "groundingChunks": [
          {
            "web": {
              "uri": "https://www.google.com/search?q=weather+in+Chicago,+IL",
              "title": "Weather information for locality: Chicago, administrative_area: IL",
              "domain": "google.com"
            }
          },
          {
            "web": {
              "uri": "...",
              "title": "weatherbug.com",
              "domain": "weatherbug.com"
            }
          }
        ],
        "groundingSupports": [
          {
            "segment": {
              "startIndex": 85,
              "endIndex": 214,
              "text": "The temperature will be between 49°F (9°C) and 55°F (13°C) on Saturday and between 51°F (11°C) and 56°F (13°C) on Sunday."
            },
            "groundingChunkIndices": [
              0
            ],
            "confidenceScores": [
              0.8662828
            ]
          },
          {
            "segment": {
              "startIndex": 215,
              "endIndex": 261,
              "text": "There is a slight chance of rain on both days."
            },
            "groundingChunkIndices": [
              1,
              0
            ],
            "confidenceScores": [
              0.62836814,
              0.6488607
            ]
          }
        ],
        "retrievalMetadata": {}
      }
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 98,
    "totalTokenCount": 108,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 10
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 98
      }
    ]
  },
  "modelVersion": "gemini-2.0-flash",
  "createTime": "2025-05-19T14:42:55.000643Z",
  "responseId": "b0MraIMFoqnf-Q-D66G4BQ"
}

借助“依托 Google 图片搜索进行接地”功能,模型可以在生成图片时使用从 Google 图片搜索检索到的 Web 图片作为视觉背景。Google 图片搜索是现有“依托 Google 搜索进行接地”工具中的一种新搜索类型,与标准 Google 网页搜索并存。“依托 Google 图片搜索进行接地”功能仅在 预览版中提供,且仅适用于 Gemini 3.1 Flash Image 模型

API 请求配置

如需启用 Google 图片搜索,请在 API 请求中配置 googleSearch 工具,并在 searchTypes 对象中指定 imageSearch。您可以单独使用 Google 图片搜索,也可以将其与 Google 网页搜索搭配使用。

REST

在使用任何请求数据之前, 请先进行以下替换:

  • LOCATION:处理请求的区域。如需使用 全球端点,请清除端点名称中的相应位置,并 将资源位置配置为全球。
  • PROJECT_ID:.
  • MODEL_ID:多模态模型的模型 ID。
  • SEARCH_TERM:图片的搜索字词。
  • HTTP 方法和网址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

    请求 JSON 正文:

    {
      "contents": [
        {
          "role": "user",
          "parts": [
            {
            "text": "SEARCH_TERM"
            }
          ]
        }
      ],
      "tools": [
        {
          "googleSearch": {
            "searchTypes": {
              "imageSearch": {},
              "webSearch": {}
            }
          }
        }
      ],
      "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID"
    }
    

    如需发送请求,请选择以下方式之一:

    curl

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"

    PowerShell

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content

    您应该会收到一个成功的状态代码 (2xx) 和一个空响应。

显示要求

将 Google 图片搜索与“依托 Google 搜索进行接地”功能搭配使用时,您必须遵守以下条件:

  • 来源归因:您必须以用户能够识别为链接的方式,提供指向包含来源图片的网页(“包含网页”,而不是图片文件 本身)的链接。

  • 直接导航:如果您还选择显示来源图片,则您 必须提供从来源图片到其 包含来源网页的直接单次点击路径。任何其他延迟或抽象最终用户对来源网页的访问的实现方式(包括但不限于任何多次点击路径或使用中间图片查看器)都是不允许的。

响应

对于使用图片搜索的接地回答,API 会提供明确的归因和元数据,以将其输出链接到经过验证的来源。groundingMetadata 对象包含以下字段:

  • imageSearchQueries:模型用于视觉背景的具体查询(也称为“图片搜索”)。

  • groundingChunks:包含检索到的结果的来源信息。对于图片来源,这些信息将使用新的图片块类型作为重定向网址返回。该块包含以下内容:

    • url:用于归因的网页网址(也称为“着陆页”)。
    • image_url:直接图片网址。
  • groundingSupports:提供将生成的内容链接到块中相关引用来源的具体映射。

  • searchEntryPoint:包含 Google 搜索条状标签,其中包含用于呈现 Google 搜索建议的合规 HTML 和 CSS。

理解回答

如果您的模型提示从 Agent Studio 或 API 成功使用“依托 Google 搜索进行接地”功能,则回答会包含带有来源链接(网址)的元数据。但是,有多种原因可能会导致此元数据无法提供,并且提示回答不会落地。这些原因包括模型回答中的来源相关性低或信息不完整。

文内引用

文内引用使用 API 返回的结构化 grounding_metadata,将生成的文本的特定部分链接到可验证的来源。

此功能支持所有接地方法,包括 Google 搜索、Google 地图和 Agent Search,并提供在应用中显示准确的交互式引用所需的精确来源详细信息。

response = client.models.generate_content(
   model="gemini-3.5-flash",
   contents="Where will the next FIFA World Cup be held?",
   config=types.GenerateContentConfig(
       tools=[types.Tool(google_search=types.GoogleSearch())],
   ),
)

display(Markdown(response.text))
print(response.candidates[0].grounding_metadata.grounding_chunks)
display(HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content))

输出示例:

…

Citations:
Wikipedia. "2026 FIFA World Cup." Retrieved February 11, 2026. (https://en.wikipedia.org/wiki/2026_FIFA_World_Cup)
US Soccer Players. "2026 FIFA World Cup FAQ — Dates, Hosts, Tickets, Teams & More." (https://ussoccerplayers.com/2026-fifa-world-cup-faq)
Holafly. "2026 World Cup host cities and countries: Full list of stadiums." (https://travel.holafly.com/esims/2026-world-cup-host-cities/)
…

接地支持

必须显示接地支持,因为这有助于您验证发布方的回答,并为用户提供更多学习途径。

对来自 Web 来源的回答的接地支持应以内嵌和汇总形式显示。例如,请参阅下图,了解如何执行此操作。

接地支持示例

使用备用搜索引擎选项

使用“依托 Google 搜索进行接地”时,客户应用可以:

  • 提供备用搜索引擎选项,
  • 将其他搜索引擎设为默认选项,
  • 显示自己的或第三方搜索建议或搜索结果,前提是:任何非 Google 结果都必须与 Google 的接地结果和搜索建议分开显示,并且显示方式不会让用户感到困惑或暗示这些结果来自 Google。

福利

当您使用“依托 Google 搜索进行接地”作为工具时,可以执行以下需要规划、推理和思考的复杂提示和工作流:

  • 您可以进行接地,以帮助确保回答基于最新、最准确的信息。
  • 您可以从 Web 检索制品以进行分析。
  • 您可以查找相关图片、视频或其他媒体,以协助进行多模态推理或任务生成。
  • 您可以执行编码、技术问题排查和其他专业任务。
  • 您可以查找特定于某个区域的信息或协助准确翻译内容。
  • 您可以查找相关网站以进行浏览。

使用 Google 搜索建议

使用“依托 Google 搜索进行接地”时,如果您在响应中收到 Google 搜索建议,则必须在生产环境和应用中显示搜索建议。

具体而言,您必须显示接地的回答的元数据中包含的搜索查询。回答包括:

  • "content":LLM 生成的回答。
  • "webSearchQueries":用于 搜索建议的查询。

例如,在以下代码段中,Gemini 会回答 Google 搜索连接提示,该提示询问一种热带植物。

"predictions": [
  {
    "content": "Monstera is a type of vine that thrives in bright indirect light…",
    "groundingMetadata": {
      "webSearchQueries": ["What's a monstera?"],
    }
  }
]

您可以使用 Google 搜索建议获取此输出并进行显示。

搜索建议的要求

搜索建议需要满足以下要求:

要求 说明
正确做法
  • 在符合显示 要求的同时,搜索建议将完全按照提供的内容显示,不会进行任何更改。
  • 当您与搜索建议互动时,系统会 直接将您带到“搜索结果”页 (SRP)。
错误做法
  • 在用户点按与 SRP 显示之间包含任何屏幕或其他步骤
  • 在 搜索建议或关联的接地 LLM 回答旁边显示任何其他搜索结果或建议。

显示要求

以下是显示要求:

  • 完全按照所提供的方式显示搜索建议,不对颜色、字体或外观进行任何修改。确保搜索建议按照以下模拟中指定的方式进行渲染,包括针对浅色和深色模式:

  • 每当显示接地回答时,其相应的 Google 搜索建议都应保持可见。
  • 在品牌塑造方面,您必须严格遵循 Google 的指南(第三方使用 Google 品牌特征时适用),详见欢迎访问我们的品牌资源中心
  • 使用“依托搜索进行接地”时,系统会显示搜索建议条状标签。包含搜索建议条状标签的字段必须与 LLM 提供的接地回答宽度相同。

点按时的行为

用户点按条状标签后,会直接前往条状标签中显示的搜索字词的对应 Google 搜索结果页 (SRP)。SRP 可以在应用内浏览器或单独的浏览器应用中打开。请务必不要以任何方式最小化、移除或遮挡 SRP 的显示内容。以下动画模拟展示了点按与 SRP 的交互。

点按时的行为

应用/桌面示例

实现搜索建议的代码

当您使用 API 为搜索回答建立依据时,模型回答会在 renderedContent 字段中提供合规的 HTML 和 CSS 样式,您可以实现该字段以在应用中显示搜索建议。

此外,搜索建议之前被称为“搜索入口点”。 虽然您可能会在某些 API 字段中看到对“搜索入口点”的引用,但这两个术语都指您在 API 响应中收到的当前搜索建议。

以下示例展示了如何使用 curl 为搜索回答建立依据:

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://aiplatform.googleapis.com/v1/projects/PROJEC_ID/locations/global/publishers/google/models/gemini-3.5-flash:generateContent -d '{
    "contents": {
      "role": "user",
      "parts": {
        "text": "Why is the sky blue?"
      }
    },
    "tools": [
      {
        "googleSearch": {}
      }
    ]
  }'

Gemini 3 的结算变化

在 Gemini 3 模型上使用“依托 Google 搜索进行接地”时,系统会针对 Gemini 生成并发送给 Google 搜索的每个搜索查询进行结算。单个提示可能会导致一个或多个搜索查询。

示例

此示例向您展示了示例用户提示以及可能会产生费用的搜索查询。

  • 用户提示: 请介绍一下阿尔伯特·爱因斯坦的一生。
  • Gemini 可能会生成以下搜索查询:
    • 阿尔伯特·爱因斯坦的出生和早年生活教育
    • 阿尔伯特·爱因斯坦的相对论
    • 阿尔伯特·爱因斯坦在美国的生活

在此示例中,这三个搜索查询会产生费用。

后续步骤