Grounding with Google Search

This page explains how to ground a model's responses using Google Search, which uses publicly-available web data.

If you want to connect your model with world knowledge, a wide possible range of topics, or up-to-date information on the Internet, then use Grounding with Google Search.

To learn more about model grounding in Vertex AI, see the Grounding overview.

Supported models

This section lists the models that support grounding with Search. To explore how each model generates grounded responses, follow these instructions:

  1. Try a model listed in this table in the Google Cloud console.

  2. Click the Grounding toggle to the on position.

Model Description Try a model
Gemini 2.0 Flash

Text, code, images, audio, video, video with audio, PDF

For more information, see Considerations.

Try the Gemini 2.0 Flash model
Gemini 2.5 Pro

Text, code, images, audio, video, video with audio, PDF

For more information, see Considerations.

Try the Gemini 2.5 Pro model

Supported languages

For a listed of supported languages, see Languages.

Use the following instructions to ground a model with publicly available web data.

Considerations

  • To use grounding with Google Search, you must enable Google Search Suggestions. See more at Use Google Search suggestions.

  • For ideal results, use a temperature of 0.0. To learn more about setting this config, see the Gemini API request body from the model reference.

  • Grounding with Google Search has a limit of one million queries per day. If you require more queries, contact Google Cloud support for assistance.

Console

To use Grounding with Google Search with the Vertex AI Studio, follow these steps:

  1. In the Google Cloud console, go to the Vertex AI Studio page.

    Go to Vertex AI Studio

  2. Click the Freeform tab.
  3. In the side panel, click the Ground model responses toggle.
  4. Click Customize and set Google Search as the source.
  5. Enter your prompt in the text box and click Submit.

Your prompt responses now ground to Google Search.

Gen AI SDK for Python

Install

pip install --upgrade google-genai
To learn more, see the SDK reference documentation.

Set environment variables to use the Gen AI SDK with Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import (
    GenerateContentConfig,
    GoogleSearch,
    HttpOptions,
    Tool,
)

client = genai.Client(http_options=HttpOptions(api_version="v1"))

response = client.models.generate_content(
    model="gemini-2.0-flash-001",
    contents="When is the next total solar eclipse in the United States?",
    config=GenerateContentConfig(
        tools=[
            # Use Google Search Tool
            Tool(google_search=GoogleSearch())
        ],
    ),
)

print(response.text)
# Example response:
# 'The next total solar eclipse in the United States will occur on ...'

Go

Before trying this sample, follow the Go setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Go API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateWithGoogleSearch shows how to generate text using Google Search.
func generateWithGoogleSearch(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "When is the next total solar eclipse in the United States?"},
		}},
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{
			{GoogleSearch: &genai.GoogleSearch{}},
		},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	respText, err := resp.Text()
	if err != nil {
		return fmt.Errorf("failed to convert model response to text: %w", err)
	}
	fmt.Fprintln(w, respText)

	// Example response:
	// The next total solar eclipse in the United States will occur on March 30, 2033, but it will only ...

	return nil
}

REST

Before using any of the request data, make the following replacements:

  • LOCATION: The region to process the request.
  • PROJECT_ID: Your project ID.
  • MODEL_ID: The model ID of the multimodal model. The Gemini 2.0 models don't support dynamic retrieval.
  • TEXT: The text instructions to include in the prompt.
  • DYNAMIC_THRESHOLD: An optional field to set the threshold to invoke the dynamic retrieval configuration. It is a floating point value in the range [0,1]. If you don't set the dynamicThreshold field, the threshold value defaults to 0.7.

HTTP method and URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

Request JSON body:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "tools": [{
    "googleSearchRetrieval": {
      "dynamicRetrievalConfig": {
        "mode": "MODE_DYNAMIC",
        "dynamicThreshold": DYNAMIC_THRESHOLD
      }
    }
  }],
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID"
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
   "candidates": [
     {
       "content": {
         "role": "model",
         "parts": [
           {
             "text": "Chicago weather changes rapidly, so layers let you adjust easily. Consider a base layer, a warm mid-layer (sweater-fleece), and a weatherproof outer layer."
           }
         ]
       },
       "finishReason": "STOP",
       "safetyRatings":[
       "..."
    ],
       "groundingMetadata": {
         "webSearchQueries": [
           "What's the weather in Chicago this weekend?"
         ],
         "searchEntryPoint": {
            "renderedContent": "....................."
         }
         "groundingSupports": [
            {
              "segment": {
                "startIndex": 0,
                "endIndex": 65,
                "text": "Chicago weather changes rapidly, so layers let you adjust easily."
              },
              "groundingChunkIndices": [
                0
              ],
              "confidenceScores": [
                0.99
              ]
            },
          ]
          "retrievalMetadata": {
              "webDynamicRetrievalScore": 0.96879
            }
       }
     }
   ],
   "usageMetadata": { "..."
   }
 }

Understand your response

If your model prompt successfully grounds to Google Search from the Vertex AI Studio or from the API, then the responses include metadata with source links (web URLs). However, there are several reasons this metadata might not be provided, and the prompt response won't be grounded. These reasons include low source relevance or incomplete information within the model's response.

Grounding support

Displaying grounding support is recommended, because it aids you in validating responses from the publishers and adds avenues for further learning.

Grounding support for responses from Google Search sources should be shown both inline and in aggregate. For example, see the following image as a suggestion on how to do this.

Grounding support examples

Use of alternative search engine options

Customer's use of Grounding with Google Search does not prevent Customer from offering alternative search engine options, making alternative search options the default option for Customer Applications, or displaying their own or third party search suggestions or search results in Customer Applications, provided that that any such non-Google Search services or associated results are displayed separately from the Grounded Results and Search Suggestions and can't reasonably be attributed to, or confused with results provided by, Google.

Use Grounding with Google Search as a tool

Grounding with Google Search lets you provide the most current and accurate information to your model to improve the model's responses. Gemini 2.0 and later models can use Google Search as a tool in the following ways:

  • The model can decide when to use Google Search.
  • You can enable multi-turn searches and multi-tool queries like combining Grounding with Google Search and code execution.

The following example shows you how to configure Google Search as a tool.

  from google import genai
  from google.genai.types import Tool, GenerateContentConfig, GoogleSearch

  client = genai.Client()
  model_id = "gemini-2.0-flash-001"

  google_search_tool = Tool(
      google_search = GoogleSearch()
  )

  response = client.models.generate_content(
      model=model_id,
      contents="When is the next total solar eclipse in the United States?",
      config=GenerateContentConfig(
          tools=[google_search_tool],
          response_modalities=[text="TEXT"],
      )
)

for each in response.candidates[0].content.parts:
    print(each.text)
# Example response:
# The next total solar eclipse visible in the contiguous United States will be on ...

# To get grounding metadata as web content. This also includes Search Suggestions
print(response.candidates[0].grounding_metadata.search_entry_point.rendered_content)

Benefits

The following complex prompts and workflows that require planning, reasoning, and thinking can be done when you use Google Search as a tool:

  • You can ground to help ensure responses are based on the latest and most accurate information.
  • You can retrieve artifacts from the web to do analysis.
  • You can find relevant images, videos, or other media to assist in multimodal reasoning or task generation.
  • You can perform coding, technical troubleshooting, and other specialized tasks.
  • You can find region-specific information, or assist in translating content accurately.
  • You can find relevant websites for browsing.

What's next