依托 Google 搜索进行接地会将 Gemini 模型连接到实时、 公开的网络内容。这样,模型便可以提供更准确、更及时的回答,并引用超出其知识截点范围的可验证来源。
依托 Google 搜索进行接地具有以下优势:
- 提高事实准确性:通过以真实世界的信息为依据,减少模型产生幻觉的情况。
- 访问实时信息:回答有关近期活动 和主题的问题。
- 提供来源:通过显示模型声明的来源,赢得用户信任或允许用户浏览 相关网站。
- 完成更复杂的任务:检索工件和相关图片、 视频或其他媒体,以协助完成推理任务。
- 改进特定于区域或语言的回答:查找特定于某个区域的 信息或协助准确翻译内容。
支持的模型
gemini-3.1-pro-previewgemini-3-flash-previewgemini-3.1-flash-lite-previewgemini-3-pro-image-preview(又称“Nano Banana Pro”)gemini-3.1-flash-image-preview(又称“Nano Banana 2”)gemini-2.5-progemini-2.5-flashgemini-2.5-flash-litegemini-2.0-flash-001(及其自动更新的别名gemini-2.0-flash)
支持的语言
请参阅 支持的语言,了解 Gemini 模型。
借助 Google 搜索让模型接地
|
点击您的 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
了解如何选择适合您的使用场景和应用的模型 (可选)。
为了获得理想的结果,请使用 1.0 的温度(这是所有 2.5 模型的默认值)。了解如何在
模型配置中设置温度。
依托 Google 搜索进行接地的运作方式
使用 GoogleSearch 工具时,模型会自动处理搜索、处理和引用信息的整个工作流程。
模型的工作流程如下:
- 接收提示:您的应用会向启 2/}模型
用
GoogleSearch工具的 Gemini 模型发送提示。Gemini - 分析提示:模型会分析提示,并确定 Google 搜索是否可以改进其回答。
- 向 Google 搜索发送查询:如果需要,模型会自动 生成一个或多个搜索查询并执行这些查询。
- 处理搜索结果:模型会处理 Google 搜索 结果,并针对原始提示制定回答。
- 返回“接地结果” :模型会返回最终的、用户友好的回答,该回答以 Google 搜索结果为依据。此回答包含模型的文本回答和
groundingMetadata,其中包含搜索查询、网页结果和来源。
请注意,向模型提供 Google 搜索作为工具并不要求模型始终使用 Google 搜索工具来生成回答。在这些情况下,回答不会包含 groundingMetadata 对象,因此不属于“接地结果”。

了解接地结果
如果模型以 Google 搜索结果为依据生成回答,则回答会包含 groundingMetadata 对象,其中包含结构化数据,这些数据对于验证声明和在应用中打造丰富的来源体验至关重要。
“接地结果”中的 groundingMetadata 对象包含以下信息:
webSearchQueries:发送给 Google 搜索的搜索查询数组。此信息有助于调试和了解模型的推理过程。searchEntryPoint:包含用于呈现所需“Google 搜索建议”的 HTML 和 CSS。您必须遵守所选 API 提供方(“依托 Google 搜索进行接地”使用要求)的要求: Gemini Developer API 或 Vertex AI Gemini API(请参阅 服务条款 (TOS) 服务专用条款中的部分)。本页面的后面部分会介绍如何 使用和显示接地结果 。groundingChunks:包含网页来源(uri和title)的对象数组。groundingSupports:用于将模型回答text连接到groundingChunks中的来源的块数组。每个块会将文本segment(由startIndex和endIndex定义)链接到一个或多个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 搜索工具生成回答,则会在回答中提供
一个 groundingMetadata 对象。
除了遵守使用 Google 搜索工具的要求之外,显示此信息还有助于您和最终用户验证回答,并为用户提供更多学习途径。
(必需)显示 Google 搜索建议
如果回答包含“Google 搜索建议”,则您必须遵守“依托 Google 搜索进行接地”的使用要求,包括如何显示 Google 搜索建议。
groundingMetadata 对象包含“Google 搜索建议”,具体来说是 searchEntryPoint 字段,该字段具有 renderedContent 字段,该字段提供合规的 HTML 和 CSS 样式,您需要实现该字段以在应用中显示搜索建议。
如需详细了解 Google 搜索建议的 显示和行为要求,请参阅 Google Cloud 文档。请注意,虽然此详细 指南位于 Vertex AI Gemini API 文档中,但该指南也 适用于 Gemini Developer API 提供方。
请参阅本部分后面的示例代码示例 。
@media(prefers-color-scheme)(必需)显示来源
groundingMetadata 对象包含结构化来源数据,具体来说是 groundingSupports 和 groundingChunks 字段。使用此信息将模型的声明直接链接到界面中的来源(内嵌和汇总)。
请参阅本部分后面的示例代码示例 。
示例代码示例
这些代码示例提供了使用和显示接地结果的通用模式。 不过,您有责任确保您的具体实现符合合规性要求。
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 API 或 Vertex AI Gemini API(请参阅服务条款 部分,该部分位于服务专用条款中)。您可能需要 调整保留期限,以Cloud Logging 满足这些要求。
价格和限制
请务必查看所选 Gemini API 提供商文档中的价格、模型可用性和依托 Google 搜索进行接地的限制: Gemini Developer API | Vertex AI Gemini API。