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

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

يوفّر التأسيس باستخدام Google Search المزايا التالية:

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

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

  • gemini-3.1-pro-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-3-pro-image (المعروف أيضًا باسم "Nano Banana Pro")
  • gemini-3.1-flash-image (المعروف أيضًا باسم "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

تعرَّف على كيفية اختيار نموذج اختياري مناسبَين لحالة الاستخدام والتطبيق.

طريقة عمل ميزة Grounding with Google Search

عند استخدام أداة GoogleSearch، يتعامل النموذج مع سير العمل بالكامل، بدءًا من البحث عن المعلومات ومعالجتها والاقتباس منها تلقائيًا.

في ما يلي سير عمل النموذج:

  1. تلقّي الطلب: يرسل تطبيقك طلبًا إلى نموذج Gemini مع تفعيل أداة GoogleSearch.
  2. تحليل الطلب: يحلّل النموذج الطلب ويحدّد ما إذا كان بإمكان Google Search تحسين الرد.
  3. إرسال طلبات البحث إلى Google Search: إذا لزم الأمر، ينشئ النموذج تلقائيًا طلب بحث واحدًا أو أكثر وينفّذها.
  4. معالجة نتائج "بحث Google": يعالج النموذج نتائج 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 أو 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"، عليك الالتزام بمتطلبات الاستخدام الخاصة بـ "الاستناد إلى 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
}

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

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

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

الأسعار والحدود

يُرجى مراجعة الأسعار ومدى توفّر النموذج والحدود القصوى لاستخدام ميزة Grounding with Google Search في مستندات موفّر Gemini API الذي اخترته: Gemini Developer API | Vertex AI Gemini API.