Tìm hiểu thông tin cơ bản trên Google Tìm kiếm

Tính năng liên kết thực tế với Google Search kết nối mô hình Gemini với nội dung web theo thời gian thực và công khai. Nhờ đó, mô hình có thể đưa ra câu trả lời chính xác hơn, cập nhật hơn và trích dẫn các nguồn có thể xác minh ngoài điểm cắt kiến thức.

Tính năng liên kết thực tế với Google Search 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 ả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-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-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-pro
  • gemini-2.5-flash
  • gemini-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:

  1. 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.
  2. 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.
  3. 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 đó.
  4. 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.
  5. 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à groundingMetadata vớ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 Search làm 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 Search để 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ế".

Sơ đồ minh hoạ cách tính năng Bám sát nguồn bằng Google Tìm kiếm liên quan đến việc mô hình tương tác với Google Tìm kiếm

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ả Google Search, 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à 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 đến Google 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ới Google 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 (urititle).

  • groundingSupports: Một mảng các khối để kết nối câu trả lời text của mô hình với các nguồn trong groundingChunks. Mỗi khối liên kết một segment văn bản (được xác định bởi startIndexendIndex) với một hoặc nhiều groundingChunkIndices. 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ụ Google Search để tạo câu trả lời, thì mô hình sẽ cung cấp đối tượng groundingMetadata trong câu trả lời.

Bạn phải hiển thị đề xuấtGoogle Searchphả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 Search, việc hiển thị thông tin này sẽ 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 Google Search

Nếu một câu trả lời có chứa "Google Search đề xuất", 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 Search" bao gồm cả cách bạn hiển thị Google Search đề xuất.

Đối tượng groundingMetadata chứa "Google Search đề xuất", 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 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.Google SearchGoogle Cloud Xin lưu ý rằng mặc dù hướng dẫn chi tiết này có trong tài liệu 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 groundingSupportsgroundingChunks. 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 Google Search trong tài liệu của nhà cung cấp Gemini API mà bạn chọn: Gemini Developer API | Vertex AI Gemini API.