پایه‌مندسازی با «جستجوی 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-3-pro-image (با نام مستعار «Nano Banana Pro»)
  • gemini-3.1-flash-image (با نام مستعار «Nano Banana 2»)

مدل‌های 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» شامل تعامل مدل با «جستجوی Google» می‌شود

فهمیدن نتیجه مستند

اگر مدل پاسخ خود را براساس نتایج Google Search ارائه دهد، پاسخ شامل یک شیء groundingMetadata است که حاوی داده‌های ساختاریافته‌ای است که برای تأیید ادعاها و ایجاد یک تجربه منبع غنی در برنامه شما ضروری است.

شیء groundingMetadata در «نتیجه مستند» حاوی اطلاعات زیر است:

  • ‫webSearchQueries: آرایه‌ای از پرسمان‌های جستجو که به Google Search ارسال شده است. این اطلاعات برای اشکال‌زدایی و درک فرایند استدلال مدل مفید است.

  • searchEntryPoint: حاوی HTML و CSS برای ارائه «پیشنهادهای Google Search» لازم است. ملزم هستید از الزامات استفاده «استناد به Google Search» برای ارائه‌دهنده API انتخابی‌تان پیروی کنید: 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 ذخیره می‌شوند. به‌طور پیش‌فرض، این داده‌ها ۳۰ روز دوره نگهداری دارند.

این مسئولیت شما است که مطمئن شوید این دوره نگهداری، یا هر دوره سفارشی که تنظیم می‌کنید، کاملاً با مورد استفاده خاص شما و هرگونه الزامات انطباق اضافی برای ارائه‌دهنده انتخابی 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).