Tính năng liên kết thực tế với
Tính năng liên kết thực tế với
- Tăng độ chính xác về mặt thực tế: Giảm hiện tượng ảo giác của mô hình 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: Tạo dựng niềm 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 cho thấy nguồn của 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 theo khu vực hoặc ngôn ngữ cụ thể: Tìm thông tin theo khu vực cụ thể 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.5-flashgemini-3.1-flash-litegemini-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-lite
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 Search
|
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 bạn tạo thực thể GenerativeModel, hãy cung cấp GoogleSearch làm 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ách hoạt động của tính năng liên kết thực tế với Google Search
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 Search có thể cải thiện câu trả lời của mô hình hay không. - Gửi truy vấn đến
Google Search : 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ả
Google Search và đưa ra 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ả
Google Search . 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 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ô hình với kết quả groundingMetadata chứa dữ liệu có cấu trúc
cần thiết để xác minh các tuyên bố và tạo 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 các thông tin sau:
webSearchQueries: Một mảng các truy vấn tìm kiếm được gửi đếnGoogle Search . 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 để kết xuất "Google Search đề xuất" 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ớiGoogle Search " cho 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 khối để kết nối câu trả lờitextcủa mô hình với các nguồn tronggroundingChunks. Mỗi khối 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 nội tuyến. 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.
Dưới đây là ví dụ về câu trả lời bao gồm đố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ụ groundingMetadata trong câu
trả lời.
Bạn phải hiển thị
đề xuất
Ngoài việc tuân thủ các yêu cầu về việc sử dụng công cụ
(Bắt buộc) Hiển thị đề xuất Google Search
Nếu một câu trả lời có chứa "
Đối tượng groundingMetadata chứa "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 của mình.
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 trong tài liệu.
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 các câu lệnh đó trong giao diện người dùng (nội tuyến và 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 quá trình 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ả bám sát nguồn 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 cho 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 giá, tính năng cung cấp mô hình và hạn mức cho tính năng liên kết thực tế với