Grounding with Google Search

Grounding with Google Search connects aGemini model to real-time,publicly-available web content. This allows the model to provide more accurate,up-to-date answers and cite verifiable sources beyond its knowledge cutoff.

Grounding with Google Search has the following benefits:

  • Increase factual accuracy: Reduce model hallucinations by basingresponses on real-world information.
  • Access real-time information: Answer questions about recent eventsand topics.
  • Provide sources: Build user trust or allow users to browserelevant sites by showing the sources for the model's claims.
  • Complete more complex tasks: Retrieve artifacts and relevant images,videos, or other media to assist in reasoning tasks.
  • Improve region or language-specific responses: Find region-specificinformation, or assist in translating content accurately.
Note for web publishers: Grounding with Google Search does not use web pages for grounding that have disallowed Google-Extended. Web publishers canmanage inclusion in Google-Extended with arobots.txt file.

Supported models

  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite
  • gemini-2.0-flash-001 (and its auto-updated aliasgemini-2.0-flash)
  • gemini-2.0-flash-live-preview-04-09

Supported languages

Seesupported languages forGeminimodels.

Ground the model with Google Search

Click yourGemini API provider to view provider-specific content and code on this page.

Important: If a response contains "Google Search suggestions" (thesearchEntryPoint field within thegroundingMetadata object), then thatresponse is a "grounded result" soyou're required to comply with the"Grounding with Google Search" usage requirements, which includes how youdisplay the result. Learn how touse and display a grounded resultlater on this page.

When you create theGenerativeModel instance, provideGoogleSearch as atool that the model can use to generate its response.

Swift

importFirebaseAI// Initialize the Gemini Developer API backend serviceletai=FirebaseAI.firebaseAI(backend:.googleAI())// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=ai.generativeModel(modelName:"GEMINI_MODEL_NAME",// Provide Google Search as a tool that the model can use to generate its responsetools:[Tool.googleSearch()])letresponse=tryawaitmodel.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 youuse and display the grounded result

Kotlin

// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casevalmodel=Firebase.ai(backend=GenerativeBackend.googleAI()).generativeModel(modelName="GEMINI_MODEL_NAME",// Provide Google Search as a tool that the model can use to generate its responsetools=listOf(Tool.googleSearch()))valresponse=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 youuse and display the grounded result

Java

// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use caseGenerativeModelai=FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel("GEMINI_MODEL_NAME",null,null,// Provide Google Search as a tool that the model can use to generate its responseList.of(Tool.GoogleSearch()));// Use the GenerativeModelFutures Java compatibility layer which offers// support for ListenableFuture and Publisher APIsGenerativeModelFuturesmodel=GenerativeModelFutures.from(ai);ListenableFutureresponse=model.generateContent("Who won the euro 2024?");Futures.addCallback(response,newFutureCallback(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){StringresultText=result.getText();System.out.println(resultText);}@OverridepublicvoidonFailure(Throwablet){t.printStackTrace();}},executor);// Make sure to comply with the "Grounding with Google Search" usage requirements,// which includes how youuse 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-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Gemini Developer API backend serviceconstai=getAI(firebaseApp,{backend:newGoogleAIBackend()});// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(ai,{model:"GEMINI_MODEL_NAME",// Provide Google Search as a tool that the model can use to generate its responsetools:[{googleSearch:{}}]});constresult=awaitmodel.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 youuse 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 FirebaseAppawaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casefinalmodel=FirebaseAI.googleAI().generativeModel(model:'GEMINI_MODEL_NAME',// Provide Google Search as a tool that the model can use to generate its responsetools:[Tool.googleSearch(),],);finalresponse=awaitmodel.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 youuse and display the grounded result

Unity

usingFirebase;usingFirebase.AI;// Initialize the Gemini Developer API backend servicevarai=FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());// Create a `GenerativeModel` instance with a model that supports your use casevarmodel=ai.GetGenerativeModel(modelName:"GEMINI_MODEL_NAME",// Provide Google Search as a tool that the model can use to generate its responsetools:new[]{newTool(newGoogleSearch())});varresponse=awaitmodel.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 youuse and display the grounded result

Learn how to choose amodelappropriate for your use case and app.

For ideal results, use a temperature of1.0 (which is the default for all 2.5models). Learn how to set temperature in themodel's configuration.

How grounding with Google Search works

When you use theGoogleSearch tool, the model handles the entire workflow ofsearching, processing, and citing information automatically.

Here's the workflow of the model:

  1. Receive prompt: Your app sends a prompt to theGemini modelwith theGoogleSearch tool enabled.
  2. Analyze prompt: The model analyzes the prompt and determines ifGoogle Search can improve its response.
  3. Send queries to Google Search: If needed, the model automaticallygenerates one or multiple search queries and executes them.
  4. Process the Search results: The model processes the Google Searchresults and formulates a response to the original prompt.
  5. Return a "grounded result": The model returns a final, user-friendlyresponse that is grounded in the Google Search results. This responseincludes the model's text answer andgroundingMetadata with the searchqueries, web results, and sources.

Note that providing Google Search as a tool to the model doesn't require themodel to always use the Google Search tool to generate its response. In thesecases, the response won't contain agroundingMetadata object and thus it'snot a "grounded result".

Diagram showing how grounding with Google Search involves the model interacting with Google Search

Understand the grounded result

If the model grounds its response in Google Search results, then the responseincludes agroundingMetadata object that contains structured data that'sessential for verifying claims and building a rich source experience in yourapplication.

Important: If a response contains "Google Search suggestions" (thesearchEntryPoint field within thegroundingMetadata object), then thatresponse is a "grounded result" soyou're required to comply with the"Grounding with Google Search" usage requirements, which includes how youdisplay the result. Learn how touse and display a grounded resultlater on this page.

ThegroundingMetadata object in a "grounded result" contains the followinginformation:

  • webSearchQueries: An array of the search queries sent to GoogleSearch. This information is useful for debugging and understanding themodel's reasoning process.

  • searchEntryPoint: Contains the HTML and CSS to render the required"Google Search suggestions". You're required to comply with the "Groundingwith Google Search" usage requirements for your chosen API provider:Gemini Developer API orVertex AI Gemini API (seeService Terms section within the Service Specific Terms). Learn how touse and display a grounded resultlater on this page.

  • groundingChunks: An array of objects containing the web sources(uri andtitle).

  • groundingSupports: An array of chunks to connect model responsetext to the sources ingroundingChunks. Each chunk links a textsegment (defined bystartIndex andendIndex) to one or moregroundingChunkIndices. This field helps you build inline source links.Learn how touse and display a grounded resultlater on this page.

Here's an example response that includes agroundingMetadata object:

{"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]}]}}]}

Use and display a grounded result

If the model uses the Google Search tool to generate a response, it will provideagroundingMetadata object in the response.

It'srequired todisplay Google Search suggestionsandrequired todisplay sources.

Beyond complying with the requirements of using the Google Search tool,displaying this information helps you and your end users to validate responsesand adds avenues for further learning.

Important: This section describes basic guidance and ageneral pattern for howto use and display a grounded result.Make sure that you review and complywith theusage and display requirements for your chosenGemini APIprovider:Gemini Developer API orVertex AI Gemini API (seeService Terms section within the Service Specific Terms).

(Required) Display Google Search suggestions

If a response contains "Google Search suggestions", then you're required tocomply with the "Grounding with Google Search" usage requirements, whichincludes how you display Google Search suggestions.

ThegroundingMetadata object contains "Google Search suggestions",specifically thesearchEntryPoint field, which has arenderedContent fieldthat provides compliant HTML and CSS styling, which you need to implement todisplay Search suggestions in your app.

Review the detailed information about thedisplay and behavior requirements for Google Search suggestions in theGoogle Cloud documentation. Note that even though this detailedguidance is in theVertex AI Gemini API documentation, the guidance isapplicable to theGemini Developer API provider, as well.

Seeexample code samples later in thissection.

Note: The HTML and CSS provided in the response automatically adapts to thedevice settings, displaying in either light or dark mode based on thepreference indicated by@media(prefers-color-scheme).

(Required) Display sources

ThegroundingMetadata object contains structured source data, specificallythegroundingSupports andgroundingChunks fields. Use this information tolink the model's statements directly to their sources within your UI (inlineand in aggregate).

Seeexample code samples later in thissection.

Example code samples

These code samples providegeneralized patterns for using and displaying thegrounded result. However, it's your responsibility to make sure that yourspecific implementation aligns with the compliance requirements.

Swift

// ...// Get the model's responselettext=response.text// Get the grounding metadataifletcandidate=response.candidates.first,letgroundingMetadata=candidate.groundingMetadata{// REQUIRED - display Google Search suggestions// (renderedContent contains HTML and CSS for the search widget)ifletrenderedContent=groundingMetadata.searchEntryPoint?.renderedContent{// TODO(developer): Display Google Search suggestions using a WebView}// REQUIRED - display sourcesletgroundingChunks=groundingMetadata.groundingChunksforchunkingroundingMetadata.groundingChunks{ifletweb=chunk.web{lettitle=web.title// for example, "uefa.com"leturi=web.uri// for example, "https://vertexaisearch.cloud.google.com..."// TODO(developer): show source in the UI}}}

Kotlin

// ...// Get the model's responsevaltext=response.text// Get the grounding metadatavalgroundingMetadata=response.candidates.firstOrNull()?.groundingMetadata// REQUIRED - display Google Search suggestions// (renderedContent contains HTML and CSS for the search widget)valrenderedContent=groundingMetadata?.searchEntryPoint?.renderedContentif(renderedContent!=null){// TODO(developer): Display Google Search suggestions using a WebView}// REQUIRED - display sourcesvalgroundingChunks=groundingMetadata?.groundingChunksgroundingChunks?.let{chunks->for(chunkinchunks){valtitle=chunk.web?.title// for example, "uefa.com"valuri=chunk.web?.uri// for example, "https://vertexaisearch.cloud.google.com..."// TODO(developer): show source in the UI}}

Java

// ...Futures.addCallback(response,newFutureCallback(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){// Get the model's responseStringtext=result.getText();// Get the grounding metadataGroundingMetadatagroundingMetadata=result.getCandidates()[0].getGroundingMetadata();if(groundingMetadata!=null){// REQUIRED - display Google Search suggestions// (renderedContent contains HTML and CSS for the search widget)StringrenderedContent=groundingMetadata.getSearchEntryPoint().getRenderedContent();if(renderedContent!=null){// TODO(developer): Display Google Search suggestions using a WebView}// REQUIRED - display sourcesListchunks=groundingMetadata.getGroundingChunks();if(chunks!=null){for(GroundingChunkchunk:chunks){WebGroundingChunkweb=chunk.getWeb();if(web!=null){Stringtitle=web.getTitle();// for example, "uefa.com"Stringuri=web.getUri();// for example, "https://vertexaisearch.cloud.google.com..."// TODO(developer): show sources in the UI}}}}}@OverridepublicvoidonFailure(Throwablet){t.printStackTrace();}},executor);

Web

// ...// Get the model's text responseconsttext=result.response.text();// Get the grounding metadataconstgroundingMetadata=result.response.candidates?.[0]?.groundingMetadata;// REQUIRED - display Google Search suggestions// (renderedContent contains HTML and CSS for the search widget)constrenderedContent=groundingMetadata?.searchEntryPoint?.renderedContent;if(renderedContent){// TODO(developer): render this HTML and CSS in the UI}// REQUIRED - display sourcesconstgroundingChunks=groundingMetadata?.groundingChunks;if(groundingChunks){for(constchunkofgroundingChunks){consttitle=chunk.web?.title;// for example, "uefa.com"consturi=chunk.web?.uri;// for example, "https://vertexaisearch.cloud.google.com..."// TODO(developer): show sources in the UI}}

Dart

// ...// Get the model's responsefinaltext=response.text;// Get the grounding metadatafinalgroundingMetadata=response.candidates.first.groundingMetadata;// REQUIRED - display Google Search suggestions// (renderedContent contains HTML and CSS for the search widget)finalrenderedContent=groundingMetadata?.searchEntryPoint?.renderedContent;if(renderedContent!=null){// TODO(developer): Display Google Search suggestions using a WebView}// REQUIRED - display sourcesfinalgroundingChunks=groundingMetadata?.groundingChunks;if(groundingChunks!=null){for(varchunkingroundingChunks){finaltitle=chunk.web?.title;// for example, "uefa.com"finaluri=chunk.web?.uri;// for example, "https://vertexaisearch.cloud.google.com..."// TODO(developer): show sources in the UI}}

Unity

// ...// Get the model's responsevartext=response.Text;// Get the grounding metadatavargroundingMetadata=response.Candidates.First().GroundingMetadata.Value;// REQUIRED - display Google Search suggestions// (renderedContent contains HTML and CSS for the search widget)if(groundingMetadata.SearchEntryPoint.HasValue){varrenderedContent=groundingMetadata.SearchEntryPoint.Value.RenderedContent;// TODO(developer): Display Google Search suggestions using a WebView}// REQUIRED - display sourcesforeach(GroundingChunkchunkingroundingMetadata.GroundingChunks){vartitle=chunk.Web.Value.Title;// for example, "uefa.com"varuri=chunk.Web.Value.Uri;// for example, "https://vertexaisearch.cloud.google.com..."// TODO(developer): show sources in the UI}

Grounded results and AI monitoring in theFirebase console

If you've enabledAI monitoring in theFirebase console,responses are stored inCloud Logging. By default, this data has a 30-dayretention period.

It's your responsibility to ensure that this retention period, or any customperiod you set, fully aligns with your specific use case and any additionalcompliance requirements for your chosenGemini API provider:Gemini Developer API orVertex AI Gemini API (seeService Terms section within the Service Specific Terms). You may need toadjust the retention period inCloud Logging to meet these requirements.

Pricing and limits

Make sure to review pricing, model availability, and limits for grounding withGoogle Search in your chosenGemini API provider documentation:Gemini Developer API |Vertex AI Gemini API.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-03 UTC.