使用 Google 搜索建立依据

使用 Google Search 接地会将 Gemini 模型连接到 实时、公开提供的 Web 内容。这让模型能够提供更准确、最新的回答,并引用其知识截点之外的可验证来源。

使用 Google Search 接地具有以下优势:

  • 提高事实准确性:通过以真实世界的信息为依据生成 回答,减少模型产生幻觉的情况。
  • 获取实时信息:回答有关近期事件 和主题的问题。
  • 提供来源:通过显示模型声明的来源,赢得用户信任或允许用户浏览 相关网站。
  • 完成更复杂的任务:检索工件和相关图片、 视频或其他媒体,以协助完成推理任务。
  • 改进特定于区域或语言的回答:查找特定于区域的 信息,或协助准确翻译内容。

支持的模型

  • gemini-3.1-pro-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-3-pro-image-preview(又称“Nano Banana Pro”)
  • gemini-3.1-flash-image-preview(又称“Nano Banana 2”)
  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite

支持的语言

请参阅 支持的语言,了解 Gemini 模型。

使用 Google Search 接地

点击您的 Gemini API 提供商,以查看此页面上特定于提供商的内容 和代码。

创建 GenerativeModel 实例时,请提供 GoogleSearch 作为模型可用于生成回答的 tool

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(
    modelName: "GEMINI_MODEL_NAME",
    // Provide Google Search as a tool that the model can use to generate its response.
    tools: [Tool.googleSearch()]
)

let response = try await model.generateContent("Who won the euro 2024?")
print(response.text ?? "No text in response.")

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

Kotlin


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Provide Google Search as a tool that the model can use to generate its response
    tools = listOf(Tool.googleSearch())
)

val response = model.generateContent("Who won the euro 2024?")
print(response.text)

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

Java


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Provide Google Search as a tool that the model can use to generate its response
                        List.of(Tool.GoogleSearch()));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

ListenableFuture response = model.generateContent("Who won the euro 2024?");
  Futures.addCallback(response, new FutureCallback() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
          String resultText = result.getText();
          System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
          t.printStackTrace();
      }
  }, executor);

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Provide Google Search as a tool that the model can use to generate its response
    tools: [{ googleSearch: {} }]
  }
);

const result = await model.generateContent("Who won the euro 2024?");

console.log(result.response.text());

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

Dart


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp.
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  // Provide Google Search as a tool that the model can use to generate its response.
  tools: [
    Tool.googleSearch(),
  ],
);

final response = await model.generateContent([Content.text("Who won the euro 2024?")]);
print(response.text);

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide Google Search as a tool that the model can use to generate its response.
  tools: new[] { new Tool(new GoogleSearch()) }
);

var response = await model.GenerateContentAsync("Who won the euro 2024?");
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

了解如何选择适合您的用例和应用的模型 (可选)。

使用 Google Search 接地的工作原理

使用 GoogleSearch 工具时,模型会自动处理搜索、处理和引用信息的整个工作流程。

模型的工作流程如下:

  1. 接收提示:您的应用会向启 2/}模型 用GoogleSearch工具的 Gemini 模型发送提示。Gemini
  2. 分析提示:模型会分析提示,并确定 Google Search是否可以改进其回答。
  3. Google Search发送查询:如果需要,模型 会自动生成一个或多个搜索查询并执行这些查询。
  4. 处理搜索结果:模型会处理 Google Search结果,并针对原始 提示生成回答。
  5. 返回“接地结果”:模型会返回最终的、用户友好的 回答,该回答以Google Search结果为依据。此回答包含模型的文本回答和 groundingMetadata,其中包含搜索查询、Web 结果和来源。

请注意,即使您向模型提供 Google Search 作为工具,模型也不一定总是使用 Google Search 工具来生成回答。在这些情况下,回答不会包含 groundingMetadata 对象,因此不属于“接地结果”。

图表:显示了“依托 Google 搜索进行接地”功能如何让模型与 Google 搜索互动

了解接地结果

如果模型以 Google Search 结果为依据生成回答,则 回答会包含 groundingMetadata 对象,其中包含结构化数据 ,这些数据对于验证声明和在应用中打造丰富的来源体验至关重要。

“接地结果”中的 groundingMetadata 对象包含以下信息:

  • webSearchQueries:发送给 Google Search的搜索查询数组。此信息有助于调试和了解模型的推理过程。

  • searchEntryPoint:包含用于呈现所需的 “Google Search建议”的 HTML 和 CSS。您必须遵守所选 API 提供方(Gemini Developer APIVertex AI Gemini API)的“使用 Google Search 接地”的使用要求(请参阅服务专用条款中的 服务条款 (TOS) 部分)。本页面的后面部分会介绍如何 使用和显示接地结果

  • groundingChunks:包含 Web 来源(urititle)的对象数组。

  • groundingSupports:用于将模型回答 text 连接到 groundingChunks 中的来源的块数组。每个块会将文本 segment(由 startIndexendIndex 定义)链接到一个或多个 groundingChunkIndices。此字段有助于您构建内嵌来源链接。 本页面的后面部分会介绍如何 使用和显示接地结果

以下是包含 groundingMetadata 对象的回答示例:

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title."
          }
        ],
        "role": "model"
      },
      "groundingMetadata": {
        "webSearchQueries": [
          "UEFA Euro 2024 winner",
          "who won euro 2024"
        ],
        "searchEntryPoint": {
          "renderedContent": "<!-- HTML and CSS for the search widget -->"
        },
        "groundingChunks": [
          {"web": {"uri": "https://vertexaisearch.cloud.google.com.....", "title": "aljazeera.com"}},
          {"web": {"uri": "https://vertexaisearch.cloud.google.com.....", "title": "uefa.com"}}
        ],
        "groundingSupports": [
          {
            "segment": {"startIndex": 0, "endIndex": 85, "text": "Spain won Euro 2024, defeatin..."},
            "groundingChunkIndices": [0]
          },
          {
            "segment": {"startIndex": 86, "endIndex": 210, "text": "This victory marks Spain's..."},
            "groundingChunkIndices": [0, 1]
          }
        ]
      }
    }
  ]
}

使用和显示接地结果

如果模型使用 Google Search 工具生成回答,则会在回答中提供 groundingMetadata 对象 in the response。

您必须显示 建议Google Search,并且必须显示来源

除了遵守使用 Google Search 工具的要求之外, 显示此信息还有助于您和最终用户验证回答, 并为用户提供更多学习途径。

(必需) 显示 Google Search 建议

如果回答包含“Google Search 建议”,则您必须遵守“使用 Google Search 接地”的使用要求,包括如何显示 Google Search 建议。

groundingMetadata 对象包含“Google Search 建议”,具体来说是 searchEntryPoint 字段,该字段具有 renderedContent 字段,该字段提供合规的 HTML 和 CSS 样式,您需要实现这些样式以在应用中显示搜索建议。

请查看 有关Google Search建议的显示和行为要求的详细信息 ,Google Cloud文档中提供了这些信息。请注意,虽然此详细 指南位于 Vertex AI Gemini API 文档中,但该指南也 适用于 Gemini Developer API 提供商。

请参阅本部分后面的示例代码示例

@media(prefers-color-scheme)

(必需)显示来源

groundingMetadata 对象包含结构化来源数据,具体来说是 groundingSupportsgroundingChunks 字段。使用此信息将模型的声明直接链接到界面中的来源(内嵌和汇总)。

请参阅本部分后面的示例代码示例

示例代码示例

这些代码示例提供了使用和显示接地结果的通用模式。 不过,您有责任确保您的具体实现符合合规性要求。

Swift

// ...

// Get the model's response
let text = response.text

// Get the grounding metadata
if let candidate = response.candidates.first,
   let groundingMetadata = candidate.groundingMetadata {
  // REQUIRED - display Google Search suggestions
  // (renderedContent contains HTML and CSS for the search widget)
  if let renderedContent = groundingMetadata.searchEntryPoint?.renderedContent {
    // TODO(developer): Display Google Search suggestions using a WebView
  }

  // REQUIRED - display sources
  let groundingChunks = groundingMetadata.groundingChunks
  for chunk in groundingMetadata.groundingChunks {
    if let web = chunk.web {
      let title = web.title  // for example, "uefa.com"
      let uri = web.uri  // for example, "https://vertexaisearch.cloud.google.com..."
      // TODO(developer): show source in the UI
    }
  }
}

Kotlin

// ...

// Get the model's response
val text = response.text

// Get the grounding metadata
val groundingMetadata = response.candidates.firstOrNull()?.groundingMetadata

// REQUIRED - display Google Search suggestions
// (renderedContent contains HTML and CSS for the search widget)
val renderedContent = groundingMetadata?.searchEntryPoint?.renderedContent
if (renderedContent != null) {
    // TODO(developer): Display Google Search suggestions using a WebView
}

// REQUIRED - display sources
val groundingChunks = groundingMetadata?.groundingChunks
groundingChunks?.let { chunks ->
  for (chunk in chunks) {
  	val title = chunk.web?.title  // for example, "uefa.com"
	val uri = chunk.web?.uri  // for example, "https://vertexaisearch.cloud.google.com..."
// TODO(developer): show source in the UI
  }
}

Java

// ...

Futures.addCallback(response, new FutureCallback() {
  @Override
  public void onSuccess(GenerateContentResponse result) {
  // Get the model's response
  String text = result.getText();

  // Get the grounding metadata
  GroundingMetadata groundingMetadata =
  result.getCandidates()[0].getGroundingMetadata();

  if (groundingMetadata != null) {
    // REQUIRED - display Google Search suggestions
  // (renderedContent contains HTML and CSS for the search widget)
    String renderedContent =
  groundingMetadata.getSearchEntryPoint().getRenderedContent();
    if (renderedContent != null) {
      // TODO(developer): Display Google Search suggestions using a WebView
    }

    // REQUIRED - display sources
    List chunks = groundingMetadata.getGroundingChunks();
    if (chunks != null) {
      for(GroundingChunk chunk : chunks) {
        WebGroundingChunk web = chunk.getWeb();
        if (web != null) {
          String title = web.getTitle();  // for example, "uefa.com"
          String uri = web.getUri();  // for example, "https://vertexaisearch.cloud.google.com..."
          // TODO(developer): show sources in the UI
        }
      }
    }
  }
  }

  @Override
  public void onFailure(Throwable t) {
  t.printStackTrace();
  }
  }, executor);

Web

// ...

// Get the model's text response
const text = result.response.text();

// Get the grounding metadata
const groundingMetadata = result.response.candidates?.[0]?.groundingMetadata;

// REQUIRED - display Google Search suggestions
// (renderedContent contains HTML and CSS for the search widget)
const renderedContent = groundingMetadata?.searchEntryPoint?.renderedContent;
if (renderedContent) {
  // TODO(developer): render this HTML and CSS in the UI
}

// REQUIRED - display sources
const groundingChunks = groundingMetadata?.groundingChunks;
if (groundingChunks) {
  for (const chunk of groundingChunks) {
    const title = chunk.web?.title;  // for example, "uefa.com"
    const uri = chunk.web?.uri;  // for example, "https://vertexaisearch.cloud.google.com..."
    // TODO(developer): show sources in the UI
  }
}

Dart

// ...

// Get the model's response
final text = response.text;

// Get the grounding metadata
final groundingMetadata = response.candidates.first.groundingMetadata;

// REQUIRED - display Google Search suggestions
// (renderedContent contains HTML and CSS for the search widget)
final renderedContent = groundingMetadata?.searchEntryPoint?.renderedContent;
if (renderedContent != null) {
    // TODO(developer): Display Google Search suggestions using a WebView
}

// REQUIRED - display sources
final groundingChunks = groundingMetadata?.groundingChunks;
if (groundingChunks != null) {
  for (var chunk in groundingChunks) {
    final title = chunk.web?.title;  // for example, "uefa.com"
    final uri = chunk.web?.uri;  // for example, "https://vertexaisearch.cloud.google.com..."
    // TODO(developer): show sources in the UI
  }
}

Unity

// ...

// Get the model's response
var text = response.Text;

// Get the grounding metadata
var groundingMetadata = response.Candidates.First().GroundingMetadata.Value;

// REQUIRED - display Google Search suggestions
// (renderedContent contains HTML and CSS for the search widget)
if (groundingMetadata.SearchEntryPoint.HasValue) {
    var renderedContent = groundingMetadata.SearchEntryPoint.Value.RenderedContent;
    // TODO(developer): Display Google Search suggestions using a WebView
}

// REQUIRED - display sources
foreach(GroundingChunk chunk in groundingMetadata.GroundingChunks) {
    var title = chunk.Web.Value.Title;  // for example, "uefa.com"
    var uri = chunk.Web.Value.Uri;  // for example, "https://vertexaisearch.cloud.google.com..."
    // TODO(developer): show sources in the UI
}

Firebase 控制台中的接地结果和 AI 监控

如果您已在 控制台中Firebase启用 AI 监控,则 回答会存储在Cloud Logging中。默认情况下,此数据的保留期限为 30 天。

您有责任确保此保留期限或您设置的任何自定义 期限与您的具体用例以及所选 Gemini API 提供商的任何其他 合规性要求完全一致: Gemini Developer APIVertex AI Gemini API(请参阅 服务条款 部分,该部分位于服务专用条款中)。您可能需要 调整保留期限,以Cloud Logging 满足这些要求。

价格和限制

请务必查看所选 Gemini API 提供商文档中有关使用 Google Search 接地的价格、模型可用性和限制: Gemini Developer API | Vertex AI Gemini API