使用 Google 搜索建立依据

依托 Google 搜索进行接地,可将 Gemini 模型与实时、公开的网络内容相连接。这样一来,模型就可以提供更准确、更及时的回答,并引用知识截止日期之后的可验证来源。

依托 Google 搜索进行接地具有以下优势:

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

请注意,Google 搜索的 Grounding 功能支持 iOS+、Android 和 Web。我们将在即将发布的版本中为 Flutter 和 Unity 提供此功能。

支持的模型

  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite-preview-06-17
  • gemini-2.0-flash-001(及其自动更新的别名 gemini-2.0-flash
  • gemini-2.0-flash-live-preview-04-09

支持的语言

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

借助 Google 搜索让模型接地

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

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

Swift


import FirebaseAI

// 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

我们将在下一个版本中支持 Flutter。

Unity

Unity 支持将在其下一个版本中推出。

了解如何选择适合您的应用场景和应用的模型

为了获得理想的结果,请使用 1.0 的温度(这是所有 2.5 模型的默认温度)。了解如何在模型配置中设置温度。

依托 Google 搜索进行接地的运作方式

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

以下是模型的工作流程:

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

请注意,即使您向模型提供 Google 搜索作为工具,模型也不必始终使用 Google 搜索工具来生成回答。在这些情况下,响应不会包含 groundingMetadata 对象,因此属于“基于事实的结果”。

图表:显示了“使用 Google 搜索建立依据”功能如何让模型与 Google 搜索互动

了解基于事实依据的结果

如果模型依托 Google 搜索结果生成回答,则回答会包含一个 groundingMetadata 对象,其中包含对于验证声明和在应用中打造丰富的引用体验至关重要的结构化数据。

“有根据的结果”中的 groundingMetadata 对象包含以下信息:

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

  • searchEntryPoint:包含用于呈现必需的“Google 搜索建议”的 HTML 和 CSS。您必须遵守所选 API 提供商的“Google 搜索基础”使用要求:Gemini Developer APIVertex AI Gemini API(请参阅服务专用条款中的服务条款部分)。本页面的后面部分会介绍如何使用和显示基于事实依据的回答

  • groundingChunks:一个对象数组,包含网络来源(urititle)。

  • groundingSupports:一个块数组,用于将模型响应 textgroundingChunks 中的来源相关联。每个块都将文本 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 搜索进行接地的结果

如果模型使用 Google 搜索工具生成回答,则会在回答中提供 groundingMetadata 对象

必须显示 Google 搜索建议建议显示引用

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

(必需)显示 Google 搜索建议

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

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

如需详细了解 Google Cloud 文档中有关 Google 搜索建议的显示和行为要求的信息,请参阅该文档。请注意,虽然此详细指南位于 Vertex AI Gemini API 文档中,但该指南也适用于 Gemini Developer API 提供程序。

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

(推荐)显示引用

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
  }

  // RECOMMENDED - display citations
  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 citation 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
}

// RECOMMENDED - display citations
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 citation 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
    }

    // RECOMMENDED - display citations
    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 citation 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
}

// RECOMMENDED - display citations
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 citation in the UI
  }
}

Dart

我们将在下一个版本中支持 Flutter。

Unity

Unity 支持将在其下一个版本中推出。

Firebase 控制台中的有根结果和 AI 监控

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

您有责任确保此保留期限或您设置的任何自定义期限完全符合您的特定使用情形以及您所选Gemini API提供商Gemini Developer APIVertex AI Gemini API 的任何其他合规性要求(请参阅“特定服务条款”中的“服务条款”部分)。您可能需要调整 Cloud Logging 中的保留期限,才能满足这些要求。

价格和限制

请务必查看所选 Gemini API 提供商的文档,了解依托 Google 搜索进行接地的价格、模型可用性和限制:Gemini Developer API | Vertex AI Gemini API