עיגון באמצעות חיפוש Google

העיגון באמצעות Google Search מחבר מודל של Gemini לתוכן מהאינטרנט שזמין לציבור ומתעדכן בזמן אמת. כך המודל יכול לספק תשובות מדויקות ועדכניות יותר ולצטט מקורות ניתנים לאימות, מעבר לתאריך סף הידע שלו.

היתרונות של ביסוס עם Google Search:

  • שיפור הדיוק העובדתי: צמצום ההזיות של המודל על ידי ביסוס התשובות על מידע מהעולם האמיתי.
  • גישה למידע בזמן אמת: מענה לשאלות על אירועים ונושאים מהזמן האחרון.
  • ציון מקורות: כדי לבנות אמון בקרב המשתמשים או לאפשר להם לעיין באתרים רלוונטיים, כדאי להציג את המקורות של הטענות של המודל.
  • השלמת משימות מורכבות יותר: שליפת ארטיפקטים ותמונות, סרטונים או מדיה רלוונטיים אחרים כדי לסייע במשימות של חשיבה רציונלית.
  • שיפור התשובות שספציפיות לאזור או לשפה: חיפוש מידע שספציפי לאזור מסוים או עזרה בתרגום תוכן בצורה מדויקת.

מודלים נתמכים

  • gemini-3.1-pro-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-3-pro-image-preview (או Nano Banana Pro)
  • gemini-3.1-flash-image-preview (נקרא גם Nano Banana 2)
  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite

שפות נתמכות

כאן מפורטות השפות הנתמכות במודלים של Gemini.

הקרקוע של המודל באמצעות Google Search

לוחצים על הספק 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

כאן מוסבר איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה שלכם.

איך ההארקה עם Google Search עובדת

כשמשתמשים בכלי GoogleSearch, המודל מטפל בכל תהליך העבודה של חיפוש, עיבוד וציטוט מידע באופן אוטומטי.

זהו תהליך העבודה של המודל:

  1. קבלת הנחיה: האפליקציה שולחת הנחיה למודל Gemini עם הכלי GoogleSearch מופעל.
  2. ניתוח ההנחיה: המודל מנתח את ההנחיה וקובע אם Google Search יכול לשפר את התשובה.
  3. שליחת שאילתות אל Google Search: אם צריך, המודל יוצר באופן אוטומטי שאילתת חיפוש אחת או יותר ומריץ אותן.
  4. עיבוד תוצאות החיפוש: המודל מעבד את Google Search התוצאות ומנסח תשובה להנחיה המקורית.
  5. החזרת תוצאה מבוססת: המודל מחזיר תשובה סופית וידידותית למשתמש שמבוססת על תוצאות Google Search. התשובה הזו כוללת את התשובה הטקסטואלית של המודל ואת groundingMetadata עם שאילתות החיפוש, תוצאות האינטרנט והמקורות.

חשוב לדעת שאם מספקים Google Search ככלי למודל, המודל לא חייב להשתמש בכלי Google Search כדי ליצור את התשובה. במקרים כאלה, התשובה לא תכיל אובייקט groundingMetadata ולכן היא לא תוצאה מבוססת.

תרשים שמראה איך עיגון בנתונים באמצעות חיפוש Google כולל אינטראקציה של המודל עם חיפוש Google

הסבר על התוצאה המבוססת

אם התשובה של המודל מבוססת על תוצאות של Google Search, היא תכלול אובייקט groundingMetadata שמכיל נתונים מובנים שחשובים לאימות טענות וליצירת חוויית מקור עשירה באפליקציה.

אובייקט groundingMetadata בתוצאה מבוססת-הקשר מכיל את הפרטים הבאים:

  • webSearchQueries: מערך של שאילתות החיפוש שנשלחו אל Google Search. המידע הזה שימושי לניפוי באגים ולהבנת תהליך ההיגיון של המודל.

  • searchEntryPoint: מכיל את ה-HTML וה-CSS לעיבוד של 'הצעות לשיפורים' Google Search. אתם נדרשים לעמוד בדרישות השימוש ב-Google Search'Grounding with Google Search' של ספק ה-API שבחרתם: Gemini Developer API או Vertex AI Gemini API (ראו את הקטע תנאי השירות בתנאים הספציפיים לשירות). בהמשך הדף מוסבר איך משתמשים בתוצאה מבוססת-קרקע ומציגים אותה.

  • 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 Search כדי ליצור תשובה, הוא יספק אובייקט groundingMetadata בתשובה.

חובה להציג הצעות של Google Search וחובה להציג מקורות.

בנוסף לעמידה בדרישות השימוש בכלי Google Search, הצגת המידע הזה עוזרת לכם ולמשתמשי הקצה שלכם לאמת את התשובות, ומאפשרת לכם ללמוד עוד.

(חובה) הצגת הצעות Google Search

אם התשובה מכילה את המחרוזת Google Search suggestions, אתם נדרשים לעמוד בדרישות השימוש של 'הצגת תשובות עם Google Search', כולל איך להציג הצעות של Google Search.

האובייקט groundingMetadata מכיל את ההצעות Google Search, ובפרט את השדה searchEntryPoint, שיש בו שדה renderedContent שמספק עיצוב HTML ו-CSS תואם, שצריך להטמיע כדי להציג הצעות לחיפוש באפליקציה.

מידע מפורט על הדרישות לגבי התצוגה וההתנהגות של הצעות Google Search מופיע במסמכי התיעוד של Google Cloud. שימו לב: ההנחיות המפורטות האלה מופיעות במסמכי התיעוד של Vertex AI Gemini API, אבל הן רלוונטיות גם לספק Gemini Developer API.

בהמשך הקטע הזה מפורטות דוגמאות קוד.

(חובה) מקורות לרשת המדיה

האובייקט 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
}

תוצאות מבוססות ומעקב אחרי שימוש בתכונות AI במסוף Firebase

אם הפעלתם מעקב אחרי שימוש בתכונות AI במסוף Firebase, התשובות נשמרות ב-Cloud Logging. כברירת מחדל, תקופת השמירה של הנתונים האלה היא 30 יום.

באחריותכם לוודא שתקופת השמירה הזו, או כל תקופה מותאמת אישית שתגדירו, תתאים באופן מלא לתרחיש השימוש הספציפי שלכם ולכל דרישות התאימות הנוספות של ספק Gemini API שבחרתם: Gemini Developer API או Vertex AI Gemini API (ראו את הקטע תנאי השירות בתנאים הספציפיים לשירות). יכול להיות שתצטרכו לשנות את תקופת השמירה ב-Cloud Logging כדי לעמוד בדרישות האלה.

תמחור ומגבלות

חשוב לעיין בתמחור, בזמינות המודלים ובמגבלות של Grounding עם Google Search במסמכי הספק של Gemini API שבחרתם: Gemini Developer API | Vertex AI Gemini API.