Il grounding con la Ricerca Google collega un modello Gemini a contenuti web disponibili pubblicamente in tempo reale. In questo modo, il modello può fornire risposte più accurate e aggiornate e citare fonti verificabili oltre il suo knowledge cutoff.
Il grounding con la Ricerca Google presenta i seguenti vantaggi:
- Aumenta l'accuratezza fattuale: riduce le allucinazioni del modello basando le risposte su informazioni del mondo reale.
- Accedi a informazioni in tempo reale: rispondi a domande su eventi recenti e argomenti.
- Fornisci fonti: crea fiducia negli utenti o consenti loro di sfogliare i siti pertinenti mostrando le fonti delle affermazioni del modello.
- Completa attività più complesse: recupera artefatti e immagini, video o altri contenuti multimediali pertinenti per assistere nelle attività di ragionamento.
- Migliora le risposte specifiche per regione o lingua: trova informazioni specifiche per regione o assisti nella traduzione accurata dei contenuti.
Modelli supportati
gemini-3.1-pro-previewgemini-3-flash-previewgemini-3.1-flash-lite-previewgemini-3-pro-image-preview(noto anche come "Nano Banana Pro")gemini-3.1-flash-image-preview(noto anche come "Nano Banana 2")gemini-2.5-progemini-2.5-flashgemini-2.5-flash-litegemini-2.0-flash-001(e il relativo alias aggiornato automaticamentegemini-2.0-flash)
Lingue supportate
Consulta le lingue supportate per i Gemini modelli.
Eseguire il grounding del modello con la Ricerca Google
|
Fai clic sul tuo fornitore Gemini API per visualizzare contenuti specifici del fornitore e codice in questa pagina. |
Quando crei l'istanza GenerativeModel, fornisci GoogleSearch come tool che il modello può utilizzare per generare la risposta.
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
Scopri come scegliere un modello adatti al tuo caso d'uso e alla tua app.
Per risultati ottimali, utilizza una temperatura di 1.0 (che è il valore predefinito per tutti i modelli 2.5). Scopri come impostare la temperatura nella
configurazione del modello.
Come funziona il grounding con la Ricerca Google
Quando utilizzi lo strumento GoogleSearch, il modello gestisce automaticamente l'intero flusso di lavoro di ricerca, elaborazione e citazione delle informazioni.
Di seguito è riportato il flusso di lavoro del modello:
- Ricevi il prompt: la tua app invia un prompt al modello Gemini
con lo strumento
GoogleSearchabilitato. - Analizza il prompt: il modello analizza il prompt e determina se la Ricerca Google può migliorare la risposta.
- Invia query alla Ricerca Google: se necessario, il modello genera automaticamente una o più query di ricerca e le esegue.
- Elabora i risultati di ricerca: il modello elabora i risultati della Ricerca Google e formula una risposta al prompt originale.
- Restituisce un "risultato fondato": il modello restituisce una risposta finale e di facile utilizzo basata sui risultati della Ricerca Google. Questa risposta include la risposta di testo del modello e
groundingMetadatacon le query di ricerca, i risultati web e le fonti.
Tieni presente che fornire la Ricerca Google come strumento al modello non richiede che il modello utilizzi sempre lo strumento Ricerca Google per generare la risposta. In questi casi, la risposta non conterrà un oggetto groundingMetadata e quindi non è un "risultato fondato".

Comprendere il risultato fondato
Se il modello basa la risposta sui risultati della Ricerca Google, la risposta include un oggetto groundingMetadata che contiene dati strutturati essenziali per verificare le affermazioni e creare un'esperienza di origine avanzata nella tua applicazione.
L'oggetto groundingMetadata in un "risultato fondato" contiene le seguenti informazioni:
webSearchQueries: un array delle query di ricerca inviate alla Ricerca Google. Queste informazioni sono utili per il debug e per comprendere il processo di ragionamento del modello.searchEntryPoint: contiene il codice HTML e CSS per eseguire il rendering dei "Suggerimenti della Ricerca Google" richiesti. Devi rispettare i requisiti di utilizzo del "Grounding con la Ricerca Google" per il fornitore dell'API scelto: Gemini Developer API o Vertex AI Gemini API (vedi Termini di servizio sezione all'interno dei Termini di servizio specifici). Scopri come utilizzare e visualizzare un risultato fondato più avanti in questa pagina.groundingChunks: un array di oggetti contenenti le fonti web (urietitle).groundingSupports: un array di blocchi per collegare iltextdella risposta del modello alle fonti ingroundingChunks. Ogni blocco collega unsegmentdi testo (definito dastartIndexeendIndex) a uno o piùgroundingChunkIndices. Questo campo ti aiuta a creare link di origine in linea. Scopri come utilizzare e visualizzare un risultato fondato più avanti in questa pagina.
Di seguito è riportata una risposta di esempio che include un oggetto 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]
}
]
}
}
]
}
Utilizzare e visualizzare un risultato fondato
Se il modello utilizza lo strumento Ricerca Google per generare una risposta, fornirà
un groundingMetadata oggetto nella risposta.
È obbligatorio visualizzare i suggerimenti della Ricerca Google ed è obbligatorio visualizzare le fonti.
Oltre a rispettare i requisiti per l'utilizzo dello strumento Ricerca Google, la visualizzazione di queste informazioni aiuta te e i tuoi utenti finali a convalidare le risposte e aggiunge ulteriori opportunità di apprendimento.
(Obbligatorio) Visualizzare i suggerimenti della Ricerca Google
Se una risposta contiene "Suggerimenti della Ricerca Google", devi rispettare i requisiti di utilizzo del "Grounding con la Ricerca Google", incluso il modo in cui visualizzi i suggerimenti della Ricerca Google.
L'oggetto groundingMetadata contiene "Suggerimenti della Ricerca Google", in particolare il campo searchEntryPoint, che ha un campo renderedContent che fornisce uno stile HTML e CSS conforme, che devi implementare per visualizzare i suggerimenti di ricerca nella tua app.
Consulta le informazioni dettagliate sui requisiti di visualizzazione e comportamento per i suggerimenti della Ricerca Google nella Google Cloud documentazione. Tieni presente che, anche se queste indicazioni dettagliate sono riportate nella documentazione Vertex AI Gemini API, sono applicabili anche al fornitore Gemini Developer API.
Vedi esempi di codice più avanti in questa sezione.
(Obbligatorio) Visualizzare le fonti
L'oggetto groundingMetadata contiene dati di origine strutturati, in particolare i campi groundingSupports e groundingChunks. Utilizza queste informazioni per collegare le affermazioni del modello direttamente alle relative fonti all'interno dell'interfaccia utente (in linea e in forma aggregata).
Vedi esempi di codice più avanti in questa sezione.
Esempi di codice
Questi esempi di codice forniscono pattern generalizzati per l'utilizzo e la visualizzazione del risultato fondato. Tuttavia, è tua responsabilità assicurarti che la tua implementazione specifica sia conforme ai requisiti di conformità.
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
}
Risultati fondati e monitoraggio dell'AI nella console Firebase
Se hai attivato il monitoraggio dell'AI nella consoleFirebase, le risposte vengono archiviate in Cloud Logging. Per impostazione predefinita, questi dati hanno un periodo di conservazione di 30 giorni.
È tua responsabilità assicurarti che questo periodo di conservazione, o qualsiasi periodo personalizzato che imposti, sia completamente in linea con il tuo caso d'uso specifico e con eventuali requisiti di conformità aggiuntivi per il fornitore scelto: Gemini Developer API o Vertex AI Gemini API (vedi Termini di servizio sezione all'interno dei Termini di servizio specifici).Gemini API Potresti dover modificare il periodo di conservazione in Cloud Logging per soddisfare questi requisiti.
Prezzi e limiti
Assicurati di esaminare i prezzi, la disponibilità dei modelli e i limiti per il grounding con Ricerca Google nella documentazione del fornitore Gemini API scelto: Gemini Developer API | Vertex AI Gemini API.