Tính năng liên kết thực tế với Google Tìm kiếm kết nối mô hình Gemini với nội dung web có sẵn công khai theo thời gian thực. Nhờ đó, mô hình có thể đưa ra câu trả lời chính xác và cập nhật hơn, đồng thời trích dẫn các nguồn có thể xác minh ngoài điểm cắt kiến thức của mô hình.
Tính năng liên kết thực tế với Google Tìm kiếm mang lại các lợi ích sau:
- Tăng độ chính xác về mặt thực tế: Giảm hiện tượng mô hình tạo ra thông tin không có thật bằng cách dựa trên thông tin thực tế.
- Truy cập thông tin theo thời gian thực: Trả lời các câu hỏi về các sự kiện gần đây và chủ đề.
- Cung cấp nguồn: Xây dựng lòng tin của người dùng hoặc cho phép người dùng duyệt xem các trang web có liên quan bằng cách hiển thị nguồn cho các tuyên bố của mô hình.
- Hoàn thành các tác vụ phức tạp hơn: Truy xuất các cấu phần phần mềm và hình ảnh, video hoặc nội dung nghe nhìn khác có liên quan để hỗ trợ các tác vụ suy luận.
- Cải thiện câu trả lời dành riêng cho khu vực hoặc ngôn ngữ: Tìm thông tin dành riêng cho khu vực hoặc hỗ trợ dịch nội dung một cách chính xác.
Mô hình được hỗ trợ
gemini-3.1-pro-previewgemini-3-flash-previewgemini-3.1-flash-lite-previewgemini-3-pro-image-preview(còn gọi là "Nano Banana Pro")gemini-3.1-flash-image-preview(còn gọi là "Nano Banana 2")gemini-2.5-progemini-2.5-flashgemini-2.5-flash-litegemini-2.0-flash-001(và bí danh tự động cập nhậtgemini-2.0-flash)
Ngôn ngữ được hỗ trợ
Xem các ngôn ngữ được hỗ trợ cho Gemini mô hình.
Liên kết thực tế mô hình với Google Tìm kiếm
|
Nhấp vào nhà cung định Gemini API để xem nội dung dành riêng cho nhà cung cấp và mã trên trang này. |
Khi tạo thực thể GenerativeModel, hãy cung cấp GoogleSearch dưới dạng tool mà mô hình có thể dùng để tạo câu trả lời.
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
Tìm hiểu cách chọn mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.
Để có kết quả lý tưởng, hãy sử dụng nhiệt độ 1.0 (đây là giá trị mặc định cho tất cả các mô hình 2.5). Tìm hiểu cách đặt nhiệt độ trong cấu hình của
mô hình.
Cách hoạt động của tính năng liên kết thực tế với Google Tìm kiếm
Khi bạn sử dụng công cụ GoogleSearch, mô hình sẽ tự động xử lý toàn bộ quy trình tìm kiếm, xử lý và trích dẫn thông tin.
Sau đây là quy trình làm việc của mô hình:
- Nhận câu lệnh: Ứng dụng của bạn gửi một câu lệnh đến mô hình Gemini
khi công cụ
GoogleSearchđược bật. - Phân tích câu lệnh: Mô hình phân tích câu lệnh và xác định xem Google Tìm kiếm có thể cải thiện câu trả lời hay không.
- Gửi truy vấn đến Google Tìm kiếm: Nếu cần, mô hình sẽ tự động tạo một hoặc nhiều truy vấn tìm kiếm và thực thi các truy vấn đó.
- Xử lý kết quả Tìm kiếm: Mô hình xử lý kết quả của Google Tìm kiếm và xây dựng câu trả lời cho câu lệnh ban đầu.
- Trả về "kết quả liên kết thực tế": Mô hình trả về câu trả lời cuối cùng, thân thiện với người dùng và được liên kết thực tế với kết quả của Google Tìm kiếm. Câu trả lời này bao gồm câu trả lời bằng văn bản của mô hình và
groundingMetadatavới các truy vấn tìm kiếm, kết quả trên web và nguồn.
Xin lưu ý rằng việc cung cấp Google Tìm kiếm dưới dạng một công cụ cho mô hình không yêu cầu mô hình luôn sử dụng công cụ Google Tìm kiếm để tạo câu trả lời. Trong những trường hợp này, câu trả lời sẽ không chứa đối tượng groundingMetadata và do đó, đây không phải là "kết quả liên kết thực tế".

Tìm hiểu kết quả liên kết thực tế
Nếu mô hình liên kết thực tế câu trả lời của mình với kết quả của Google Tìm kiếm, thì câu trả lời đó sẽ bao gồm đối tượng groundingMetadata chứa dữ liệu có cấu trúc cần thiết để xác minh các tuyên bố và xây dựng trải nghiệm nguồn phong phú trong ứng dụng của bạn.
Đối tượng groundingMetadata trong "kết quả liên kết thực tế" chứa thông tin sau:
webSearchQueries: Một mảng các truy vấn tìm kiếm được gửi đến Google Tìm kiếm. Thông tin này hữu ích cho việc gỡ lỗi và tìm hiểu quy trình suy luận của mô hình.searchEntryPoint: Chứa HTML và CSS để hiển thị "Đề xuất của Google Tìm kiếm" bắt buộc. Bạn phải tuân thủ các yêu cầu về việc sử dụng "Tính năng liên kết thực tế với Google Tìm kiếm" đối với nhà cung cấp API mà bạn chọn: Gemini Developer API hoặc Vertex AI Gemini API (xem Điều khoản dịch vụ trong Điều khoản dành riêng cho dịch vụ). Tìm hiểu cách sử dụng và hiển thị kết quả liên kết thực tế ở phần sau trên trang này.groundingChunks: Một mảng các đối tượng chứa nguồn trên web (urivàtitle).groundingSupports: Một mảng các đoạn để kết nối câu trả lờitextcủa mô hình với các nguồn tronggroundingChunks. Mỗi đoạn liên kết mộtsegmentvăn bản (được xác định bởistartIndexvàendIndex) với một hoặc nhiềugroundingChunkIndices. Trường này giúp bạn tạo đường liên kết nguồn cùng dòng. Tìm hiểu cách sử dụng và hiển thị kết quả liên kết thực tế ở phần sau trên trang này.
Sau đây là ví dụ về câu trả lời có chứa đối tượng 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]
}
]
}
}
]
}
Sử dụng và hiển thị kết quả liên kết thực tế
Nếu mô hình sử dụng công cụ Google Tìm kiếm để tạo câu trả lời, thì mô hình sẽ cung cấp
một groundingMetadata đối tượng trong câu trả lời.
Bạn phải hiển thị đề xuất của Google Tìm kiếm và phải hiển thị nguồn.
Ngoài việc tuân thủ các yêu cầu về việc sử dụng công cụ Google Tìm kiếm, việc hiển thị thông tin này giúp bạn và người dùng cuối xác thực câu trả lời và bổ sung các phương thức để tìm hiểu thêm.
(Bắt buộc) Hiển thị đề xuất của Google Tìm kiếm
Nếu một câu trả lời có chứa "Đề xuất của Google Tìm kiếm", thì bạn phải tuân thủ các yêu cầu về việc sử dụng "Tính năng liên kết thực tế với Google Tìm kiếm", bao gồm cả cách bạn hiển thị đề xuất của Google Tìm kiếm.
Đối tượng groundingMetadata chứa "Đề xuất của Google Tìm kiếm", cụ thể là trường searchEntryPoint. Trường này có trường renderedContent cung cấp kiểu HTML và CSS tuân thủ. Bạn cần triển khai kiểu này để hiển thị đề xuất của Tìm kiếm trong ứng dụng.
Xem thông tin chi tiết về các yêu cầu về hành vi và cách hiển thị đối với đề xuất của Google Tìm kiếm trong tài liệu.Google Cloud Xin lưu ý rằng mặc dù hướng dẫn chi tiết này nằm trong tài liệu về Vertex AI Gemini API, nhưng hướng dẫn này cũng áp dụng cho nhà cung cấp Gemini Developer API.
Xem mã mẫu ví dụ ở phần sau trong phần này.
(Bắt buộc) Hiển thị nguồn
Đối tượng groundingMetadata chứa dữ liệu nguồn có cấu trúc, cụ thể là các trường groundingSupports và groundingChunks. Sử dụng thông tin này để liên kết trực tiếp các câu lệnh của mô hình với nguồn của chúng trong giao diện người dùng (nội tuyến và ở dạng tổng hợp).
Xem mã mẫu ví dụ ở phần sau trong phần này.
Mã mẫu ví dụ
Các mã mẫu này cung cấp các mẫu chung để sử dụng và hiển thị kết quả liên kết thực tế. Tuy nhiên, bạn có trách nhiệm đảm bảo rằng việc triển khai cụ thể của bạn phù hợp với các yêu cầu tuân thủ.
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
}
Kết quả liên kết thực tế và tính năng giám sát bằng AI trong bảng điều khiển Firebase
Nếu bạn đã bật tính năng giám sát bằng AI trong bảng điều khiển, thì các câu trả lời sẽ được lưu trữ trong Cloud Logging.FirebaseCloud Logging Theo mặc định, dữ liệu này có khoảng thời gian lưu giữ là 30 ngày.
Bạn có trách nhiệm đảm bảo rằng khoảng thời gian lưu giữ này hoặc bất kỳ khoảng thời gian tuỳ chỉnh nào mà bạn đặt đều hoàn toàn phù hợp với trường hợp sử dụng cụ thể của bạn và mọi yêu cầu tuân thủ bổ sung đối với nhà cung cấp Gemini API mà bạn chọn: Gemini Developer API hoặc Vertex AI Gemini API (xem Điều khoản dịch vụ trong Điều khoản dành riêng cho dịch vụ). Bạn có thể cần điều chỉnh khoảng thời gian lưu giữ trong Cloud Logging để đáp ứng các yêu cầu này.
Giá và hạn mức
Hãy nhớ xem xét giá, tính khả dụng của mô hình và hạn mức đối với tính năng liên kết thực tế với Google Tìm kiếm trong tài liệu về nhà cung cấp Gemini API mà bạn chọn: Gemini Developer API | Vertex AI Gemini API.