الأساسيات باستخدام "بحث Google"

تتيح ميزة "تحديد المصدر باستخدام Google Search" ربط نموذج Gemini بمحتوى على الويب متاح للجميع في الوقت الفعلي. يتيح ذلك للنموذج تقديم إجابات أكثر دقة وحداثة والإشارة إلى مصادر يمكن التحقّق منها بعد تاريخ آخر تحديث للبيانات.

توفّر ميزة "التحقّق من المصادر باستخدام Google Search" المزايا التالية:

  • زيادة الدقة الواقعية: يمكنك تقليل هلوسة النموذج من خلال الاستناد في الردود إلى معلومات واقعية.
  • الوصول إلى معلومات في الوقت الفعلي: الإجابة عن أسئلة حول الأحداث والمواضيع الأخيرة
  • تقديم المصادر: يمكنك كسب ثقة المستخدمين أو السماح لهم بتصفّح المواقع الإلكترونية ذات الصلة من خلال عرض مصادر الادعاءات التي يقدّمها النموذج.
  • إكمال المهام الأكثر تعقيدًا: استرداد العناصر والصور أو الفيديوهات أو الوسائط الأخرى ذات الصلة للمساعدة في مهام الاستدلال
  • تحسين الردود الخاصة بمنطقة أو لغة معيّنة: يمكنك العثور على معلومات خاصة بمنطقة معيّنة أو المساعدة في ترجمة المحتوى بدقة.

النماذج المتوافقة

  • gemini-4-argon
  • ‫gemini-3.8-flash (والإصدارات الأقدم gemini-3.7-flash وgemini-3.6-flash وgemini-3.5-flash)
  • ‫gemini-3.5-flash-lite (والإصدار الأقدم gemini-3.1-flash-lite)
  • gemini-nano-banana-2.1 (Nano Banana 2.1)
  • gemini-3.1-flash-image (Nano Banana 2)
  • gemini-3-pro-image (Nano Banana Pro)

يتيح أيضًا نموذج gemini-3.1-pro-preview ونموذج Gemini 2.5 للاستخدام العام (اللذان تم إيقافهما نهائيًا) هذه الإمكانية.

تتيح أيضًا نماذج Gemini Live API هذه الإمكانية، ولكن جميع عينات التعليمات البرمجية في هذا الدليل مخصّصة لنماذج Gemini ذات الاستخدام العام.

اللغات المتاحة

يمكنك الاطّلاع على اللغات المتاحة لنماذج 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: [.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" عند تفعيل ميزة "تحديد المصدر من خلال بحث Search"

فهم النتائج المستندة إلى المصادر

إذا استند النموذج في ردّه إلى نتائج "Google Search"، سيتضمّن الردّ عنصر groundingMetadata يحتوي على بيانات منظَّمة ضرورية للتحقّق من الادّعاءات وإنشاء تجربة مصدر غنية في تطبيقك.

يحتوي عنصر groundingMetadata في "النتيجة المستندة إلى المصادر" على المعلومات التالية:

  • ‫webSearchQueries: مصفوفة من طلبات البحث المُرسَلة إلى Google Search. هذه المعلومات مفيدة لتصحيح الأخطاء وفهم عملية الاستدلال في النموذج.

  • ‫searchEntryPoint: يحتوي على HTML وCSS لعرض "اقتراحات Google Search" المطلوبة. يجب الالتزام بمتطلبات استخدام ميزة "التحقّق من المصادر باستخدام Google Search" لمزوّد واجهة برمجة التطبيقات الذي اخترته: Gemini Developer API أو Agent Platform Gemini API (formerly Vertex AI) (يُرجى الاطّلاع على قسم بنود الخدمة ضمن "البنود الخاصة بالخدمة"). يمكنك التعرّف على كيفية استخدام نتيجة مستندة إلى المصدر وعرضها لاحقًا في هذه الصفحة.

  • ‫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"، عليك الالتزام بمتطلبات استخدام "الاستناد إلى Google Search"، والتي تشمل كيفية عرض اقتراحات Google Search.

يحتوي العنصر groundingMetadata على "اقتراحات Google Search"، وتحديدًا الحقل searchEntryPoint الذي يتضمّن الحقل renderedContent الذي يوفّر تنسيق HTML وCSS متوافقًا، والذي يجب تنفيذه لعرض اقتراحات البحث في تطبيقك.

راجِع المعلومات التفصيلية حول متطلبات العرض والسلوك لاقتراحات Google Search في مستندات Google Cloud. يُرجى العِلم أنّه على الرغم من أنّ هذه الإرشادات المفصّلة واردة في مستندات Agent Platform Gemini API (formerly Vertex AI)، فإنّها تنطبق أيضًا على مزوّد خدمة 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
}

النتائج المستندة إلى مصادر موثوقة وتتبُّع استخدام الذكاء الاصطناعي في وحدة تحكّم Firebase

إذا فعّلت ميزة تتبُّع استخدام الذكاء الاصطناعي في وحدة تحكّم Firebase، يتم تخزين الردود في Cloud Logging. بشكل تلقائي، يتم الاحتفاظ بهذه البيانات لمدة 30 يومًا.

تقع على عاتقك مسؤولية التأكّد من أنّ فترة الاحتفاظ بالبيانات هذه، أو أي فترة مخصّصة تحدّدها، تتوافق تمامًا مع حالة الاستخدام المحدّدة وأي متطلبات امتثال إضافية لمقدّم خدمة Gemini API الذي اخترته: Gemini Developer API أو Agent Platform Gemini API (formerly Vertex AI) (يُرجى الاطّلاع على قسم بنود الخدمة ضمن البنود الخاصة بالخدمة). قد تحتاج إلى تعديل فترة الاحتفاظ بالبيانات في Cloud Logging لتلبية هذه المتطلبات.

الأسعار والحدود القصوى

يُرجى مراجعة الأسعار والنماذج المتاحة والحدود القصوى لميزة "الربط بمصادر موثوقة" باستخدام Google Search في مستندات موفّر خدمة Gemini API الذي اخترته: Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI).