الأساسيات باستخدام "بحث 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. تلقّي الطل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 في "نتيجة موثوقة" على المعلومات التالية:

في ما يلي مثال على ردّ يتضمّن عنصر 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" في تطبيقك.

راجِع المعلومات التفصيلية حول متطلبات العرض والسلوك لاقتراحات 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 console

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

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

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

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