Skip to content
,

Gemini API Grounding with Google Search and URL Context: Python Tutorial (2026)

12โ€“18 minutes
Woman in a home lab with a PC tower holding a tablet with a GROUNDING card, hook $14 per 1,000 searches

Gemini can answer from live Google Search results and from web pages you pass in, with real citations. This guide shows how to switch on Grounding with Google Search and the URL context tool in Python, read the citation data, and keep the bill under control.

Prices changed on 1 December 2026, and Google now pushes the newer Interactions API. So I have covered both the classic generate_content call (with groundingMetadata) and the new Interactions style.

TLDR

  • Enable search: pass google_search as a tool. For pages you choose, add url_context. Both work together.
  • Citations: with generate_content, read grounding_metadata (chunks + supports). With the Interactions API, read url_citation annotations.
  • Price (Gemini 3 and newer): 5,000 free search queries a month on the paid tier, then $14 per 1,000 queries. Each query the model runs is billed.
  • Gemini 2.5: billed per grounded prompt, $35 per 1,000 after a free daily allowance.
  • Limits: 1,500 grounded requests per day by default; URL context reads up to 20 URLs and 34 MB per URL.
  • Display rule: if you show grounded answers to users, show the Search suggestions widget too.

What Grounding and URL Context Do

A normal model call answers only from training data. That data has a cutoff date, so the model can miss recent news, prices or releases. Grounding fixes this by letting the model fetch fresh facts while it answers.

  • Grounding with Google Search: the model decides if a search would help, writes one or more queries, runs them, and builds an answer with citations.
  • URL context: you give the model specific links (up to 20). It reads those pages and answers from them. It does not follow links inside the pages.
  • Both together: the model can search first, then read the pages it found, or mix your URLs with search results.

Use Search grounding for questions about current events, prices or anything that changes. Use URL context when you already know the source, such as a docs page, a PDF report or a product page you want compared.

Quick answer: add {"google_search": {}} and/or {"url_context": {}} to the tools list. Then read citations from response.candidates[0].grounding_metadata (classic API) or from the url_citation annotations (Interactions API).

Which Models Support Grounding and URL Context

I checked the official docs on 3 December 2026 (pages last updated 13 to 28 October 2026). Current models use the google_search tool. Older models used a google_search_retrieval tool, which you should not use for new code.

Model Model ID Google Search URL context
Gemini 4 Argon gemini-4-argon Yes Yes
Gemini 3.8 Flash gemini-3.8-flash Yes Yes
Gemini 3.6 Flash gemini-3.6-flash Yes Yes
Gemini 3.5 Flash-Lite gemini-3.5-flash-lite Yes Yes
Gemini 3.1 Flash-Lite gemini-3.1-flash-lite Yes Yes
Gemini 3.1 Pro Preview gemini-3.1-pro-preview Yes Yes
Gemini 3 Flash Preview gemini-3-flash-preview Yes Yes
Nano Banana 2 / Nano Banana Pro (image) gemini-3.1-flash-image, gemini-3-pro-image Yes No
Gemini 2.5 Pro / Flash / Flash-Lite gemini-2.5-pro etc. Yes Yes

Note: the Gemini 2.5 models are still served, but the models page says access is limited to users who have used them before. New projects should start on Gemini 3.8 Flash or Gemini 4 Argon.

Setup Steps

You need Python 3.9 or newer, a Gemini API key and a billing-enabled project. Grounding on Gemini 3 and newer models is a paid-tier feature on the Gemini Developer API (you can still try it in Google AI Studio).

  1. Get an API key. Open Google AI Studio, go to API keys and create a key. See my Google AI Studio guide if this is your first time.
  2. Turn on billing. Link a billing account to the project. Without it, grounded calls on Gemini 3+ models are not available.
  3. Install the SDK. Run pip install -U google-genai. I checked version 3.7.0 (released 2 December 2026). The Interactions examples need version 2.0.0 or newer.
  4. Set the key as an environment variable. On macOS or Linux run export GEMINI_API_KEY="your-key". On Windows PowerShell use $env:GEMINI_API_KEY="your-key". The client reads it automatically.
  5. Run a test. Paste Example 1 below into ground.py and run python ground.py.

New to the SDK itself? Start with my Gemini API Python tutorial, then come back here.

Example 1: Basic Google Search Grounding

This is the classic generate_content call. You wrap GoogleSearch() in a Tool and pass it in the config.

from google import genai
from google.genai import types

client = genai.Client()  # reads GEMINI_API_KEY

grounding_tool = types.Tool(
    google_search=types.GoogleSearch()
)

config = types.GenerateContentConfig(
    tools=[grounding_tool]
)

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Who won the euro 2024?",
    config=config,
)

print(response.text)

# What did the model search for?
meta = response.candidates[0].grounding_metadata
if meta and meta.web_search_queries:
    print("Queries:", meta.web_search_queries)

The model decides on its own if a search is needed. For a question like “What is 2 + 2?” it may answer without searching. In that case grounding_metadata can be empty, and you are not billed for a search.

What is inside groundingMetadata

  • webSearchQueries: the list of queries the model ran. Handy for debugging and for counting billable queries.
  • searchEntryPoint: holds renderedContent, the HTML and CSS for the Search suggestions widget you must show.
  • groundingChunks: the sources. Each has a web object with uri and title.
  • groundingSupports: links parts of the answer to sources. Each has a segment (startIndex, endIndex, text) and groundingChunkIndices.

In Python the fields use snake_case, so groundingChunks becomes grounding_chunks.

Example 2: Read groundingMetadata and Add Inline Citations

This function is based on the official sample. It walks the supports from the end of the text to the start, so inserting a link never shifts the positions still to come.

from google import genai
from google.genai import types

client = genai.Client()

def add_citations(response):
    text = response.text
    meta = response.candidates[0].grounding_metadata
    if not meta or not meta.grounding_supports:
        return text  # the model did not search

    supports = meta.grounding_supports
    chunks = meta.grounding_chunks

    # Insert from the end so earlier indexes stay valid
    sorted_supports = sorted(
        supports, key=lambda s: s.segment.end_index, reverse=True
    )

    for support in sorted_supports:
        end_index = support.segment.end_index
        if support.grounding_chunk_indices:
            links = []
            for i in support.grounding_chunk_indices:
                if i < len(chunks):
                    uri = chunks[i].web.uri
                    links.append(f"[{i + 1}]({uri})")
            text = text[:end_index] + ", ".join(links) + text[end_index:]
    return text

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="What changed in the Gemini API pricing this month?",
    config=types.GenerateContentConfig(
        tools=[types.Tool(google_search=types.GoogleSearch())]
    ),
)

print(add_citations(response))

# Print a numbered source list too
meta = response.candidates[0].grounding_metadata
if meta and meta.grounding_chunks:
    for n, chunk in enumerate(meta.grounding_chunks, start=1):
        print(f"{n}. {chunk.web.title} - {chunk.web.uri}")

The output is Markdown, with links like [1](https://...) after each supported sentence. If you render in HTML, build <a> tags instead.

Tip: the source uri may not be the final page address, so do not parse it. Show it as a clickable link and use the title as the label.

Example 3: URL Context, Alone and With Search

URL context is a separate tool. Put the links in your prompt and add {"url_context": {}} to the tools. The model fetches each page from Google’s index cache first, and does a live fetch if the page is not there.

from google import genai
from google.genai.types import GenerateContentConfig

client = genai.Client()

url1 = "https://ai.google.dev/gemini-api/docs/pricing"
url2 = "https://ai.google.dev/gemini-api/docs/models"

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=f"Using {url1} and {url2}, list the stable Gemini models and their input price.",
    config=GenerateContentConfig(
        tools=[{"url_context": {}}],
    ),
)

print(response.text)

# Which URLs were fetched, and did each one work?
ucm = response.candidates[0].url_context_metadata
if ucm:
    for item in ucm.url_metadata:
        print(item.retrieved_url, item.url_retrieval_status)

# Tokens used by fetched page content
print(response.usage_metadata.tool_use_prompt_token_count)

A good fetch shows URL_RETRIEVAL_STATUS_SUCCESS. A page that fails the safety check shows URL_RETRIEVAL_STATUS_UNSAFE.

Combine URL context with Google Search

Just list both tools. The model can read your URL and search the web for anything the page does not cover.

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=(
        "Read https://ai.google.dev/gemini-api/docs/url-context and tell me its limits. "
        "Then search for any newer changes announced since."
    ),
    config=GenerateContentConfig(
        tools=[{"url_context": {}}, {"google_search": {}}],
    ),
)
print(response.text)
print(response.candidates[0].url_context_metadata)
print(response.candidates[0].grounding_metadata)
Gemini API URL context docs Limitations section: up to 20 URLs per request, 34MB per URL, public URLs only
Official Gemini API URL context page, Limitations section (checked 3 December 2026).

Example 4: The Interactions API Way (Plus Function Calling)

Google’s main docs now show grounding through the Interactions API. Google says generateContent “remains fully supported”, but it recommends Interactions for new projects.

The big change is the response shape. Instead of one groundingMetadata object, you get a list of steps.

  • google_search_call: the queries the model ran (was webSearchQueries).
  • google_search_result: includes search_suggestions, the widget HTML (was searchEntryPoint).
  • model_output: text blocks with url_citation annotations holding url, title, start_index and end_index (replaces chunks and supports).
  • url_context_result: the status of each URL fetch, for debugging.
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Who won the euro 2024?",
    tools=[{"type": "google_search"}, {"type": "url_context"}],
)

print(interaction.output_text)

for step in interaction.steps:
    if step.type == "google_search_result":
        widget_html = step.result[0].search_suggestions  # render this in your UI
    if step.type == "model_output":
        for block in step.content:
            if block.type == "text" and block.annotations:
                for a in block.annotations:
                    if a.type == "url_citation":
                        cited = block.text[a.start_index:a.end_index]
                        print(f'[{a.title}]({a.url}) -> "{cited}"')

Warning: output_text only joins the text blocks at the end of the reply. If text is split by tool steps, loop over steps yourself or you may lose part of the answer.

Combine Search with your own functions

Since 18 March 2026, Gemini 3 and 4 models can mix built-in tools with custom function calling in one request (still marked Preview). The model can search first, then call your function with what it found.

get_weather = {
    "type": "function",
    "name": "getWeather",
    "description": "Gets the weather for a requested city.",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "City and state"},
        },
        "required": ["city"],
    },
}

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is the northernmost city in the United States? What's the weather there today?",
    tools=[{"type": "google_search"}, get_weather],
)

for step in interaction.steps:
    if step.type == "function_call":
        print("Call:", step.name, step.arguments)
        # run your function, then send the result back

Built-in tools that support this are Google Search, Google Maps, URL context, File Search and code execution. When you work statelessly, pass each step’s id and signature back. With previous_interaction_id the server handles that for you. For the full loop, see my Gemini function calling tutorial.

Quick curl Test

Use this to check your key and billing without Python. It calls the Interactions endpoint with Search turned on.

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": "Who won the euro 2024?",
    "tools": [{"type": "google_search"}]
  }'

Pricing After 1 December 2026

You pay twice for a grounded call: normal token prices for the model, plus a grounding fee. On Gemini 3 and newer the grounding fee is per search query, not per prompt. If the model runs two queries for one question, that is two billable uses. Empty queries are not counted.

Gemini API grounding docs Pricing section: Gemini 3 and newer billed per search query, 5,000 free per month then $14 per 1,000
Official Grounding with Google Search docs, Pricing section (checked 3 December 2026).
Model Input / output per 1M tokens (Standard) Google Search grounding (paid tier) Free tier
Gemini 4 Argon $4.00 / $20.00 from 1 Dec 2026 (was $2 / $10) 5,000 free queries a month (shared across Gemini 3+), then $14 per 1,000 Not available
Gemini 3.8 Flash $0.75 / $3.75 until 31 Dec 2026, then $1.50 / $7.50 Same shared 5,000, then $14 per 1,000 Not available
Gemini 3.6 Flash $0.75 / $3.75, rising to $1.50 / $7.50 on 1 Jan 2027 Same shared 5,000, then $14 per 1,000 Test in AI Studio
Gemini 3.5 Flash-Lite $0.30 / $2.50 Same shared 5,000, then $14 per 1,000 Test in AI Studio
Gemini 3.1 Pro Preview $2.00 / $12.00 (prompts up to 200k) Same shared 5,000, then $14 per 1,000 Test in AI Studio
Gemini 2.5 Pro $1.25 / $10.00 (up to 200k) 1,500 grounded prompts a day free, then $35 per 1,000 prompts Not available
Gemini 2.5 Flash $0.30 / $2.50 1,500 a day free (shared with Flash-Lite), then $35 per 1,000 prompts Up to 500 a day free

URL context has no separate tool fee. The page content it fetches counts as input tokens at the model’s normal rate. One long PDF can add thousands of tokens, so check tool_use_prompt_token_count.

Worked cost example

Say your app makes 20,000 grounded requests a month on Gemini 3.8 Flash. Each request uses about 1,000 input tokens and 500 output tokens, and the model runs 1.5 searches on average.

  • Search queries: 20,000 x 1.5 = 30,000. Minus 5,000 free = 25,000 billable. 25 x $14 = $350.
  • Input tokens: 20M x $0.75 = $15.
  • Output tokens: 10M x $3.75 = $37.50.
  • Total in December 2026: about $402.50. From January 2027 the token part doubles, so about $455.

The same load on Gemini 4 Argon costs about $80 + $200 + $350 = $630. Notice that search fees are the biggest line in both cases. Cutting needless searches saves more than switching models. For more ways to save, see my Gemini API pricing and free tier guide.

Tip: Batch and Flex modes halve token prices on Argon and 3.8 Flash, but the pricing page lists no grounding row for Argon in Batch. Keep grounded calls on Standard unless the page says otherwise for your model.

Limits

Limit Value Notes
Grounded requests per day 1,500 RPD per project Default on Gemini 3+ paid tier. Request more in AI Studio next to the generate_content_search_request_paid limit.
Free search queries 5,000 per month Shared across all Gemini 3 and newer models.
URLs per request (URL context) 20 Only the URLs you give. Linked pages are not followed.
Content per URL 34 MB Text, HTML, JSON, CSV, PNG, JPEG, BMP, WebP and PDF.
Blocked URL types Paywalls, YouTube, Google Docs/Sheets, video, audio Use video understanding for YouTube.
Private addresses Not supported No localhost, private networks, ngrok or pinggy.
Sites excluded from grounding Sites blocking Google-Extended Publishers opt out in robots.txt.

Normal model rate limits (RPM and TPM) still apply on top. My LLM API rate limits guide explains tiers across providers.

Display Requirements (Search Suggestions)

A response that contains Search suggestions counts as a “grounded result”. If you show it to end users, the Gemini API terms for Grounding with Google Search apply. Here is what the docs ask for.

  • Show the suggestions widget: render searchEntryPoint.renderedContent (or search_suggestions in Interactions). Google supplies compliant HTML and CSS, so use it as given.
  • Light and dark mode: the supplied CSS switches with prefers-color-scheme, so you do not need your own theme.
  • Show sources: link statements to their sources inline, and also list them together.
  • Read the terms: the docs point to the Gemini API terms for full rules. Your app is responsible for compliance.

A simple way to render the widget in a Flask or Django page:

meta = response.candidates[0].grounding_metadata
widget = ""
if meta and meta.search_entry_point:
    widget = meta.search_entry_point.rendered_content
# In your template, output widget unescaped, below the answer.
# Jinja2: {{ widget | safe }}

Note: if you only use grounded answers in a backend pipeline that no user sees, there is no widget to show. Still read the terms before you store or reuse grounded results.

Troubleshooting: Common Problems and Fixes

Error or symptom Likely cause Fix
AttributeError: 'NoneType' object has no attribute 'grounding_supports' The model answered without searching, so there is no metadata. Check if meta and meta.grounding_supports first, as in Example 2.
400 INVALID_ARGUMENT Wrong tool name (for example google_search_retrieval on a new model), a malformed tools list, or an unsupported model. Use google_search and url_context, and a model from the support table. Do not retry unchanged.
402 Prepay credits used up. Add credits in billing. Retrying will not help.
403 PERMISSION_DENIED No billing, project restricted, or key reported as leaked. Enable billing, verify the project, or make a new key.
429 RESOURCE_EXHAUSTED Hit the 1,500 grounded RPD or a normal rate limit. Back off with jitter (the SDK retries up to 4 times), cache answers, or ask for more quota.
503 UNAVAILABLE Temporary overload. Retry with exponential backoff.
URL_RETRIEVAL_STATUS_UNSAFE The page failed the content safety check. Use a different source page.
Model says it cannot open your link Paywall, login wall, localhost, YouTube or a Google Doc. Use a public URL with https://, or upload the file instead.
Citations land in the wrong spot Text changed before inserting, or non-English text and emoji shift offsets. Insert from the end, on the untouched response.text. Test with non-ASCII text.
Finish reason RECITATION Output too close to source text. Make the prompt more specific. Gemini 4 and 3.6+ ignore temperature, so do not rely on it.
Bill higher than expected Model runs several queries per prompt. Log web_search_queries length, and only enable the tool when the question needs fresh data.

For more general fixes, see my Gemini API errors guide.

Frequently Asked Questions

Is Grounding with Google Search free?

On Gemini 3 and newer models you get 5,000 free search queries a month on the paid tier, shared across models, then $14 per 1,000. The free API tier does not include grounding on these models, but you can try it in Google AI Studio.

Am I charged per prompt or per search?

On Gemini 3 and newer, per search query the model runs, so one prompt can cost two or more queries. On Gemini 2.5 and older, you pay per grounded prompt.

Does URL context cost extra?

There is no tool fee. The fetched page content is billed as input tokens at the model’s normal price.

Can I force the model to always search?

The docs say the model decides if a search will help. If you need fresh data every time, say so clearly in the prompt, and check web_search_queries to confirm it searched.

Should I use generate_content or the Interactions API?

Both work. Google says generateContent stays fully supported but recommends Interactions for new projects, and its main docs now show Interactions first.

Can I use grounding with structured JSON output or my own functions?

Gemini 3 and 4 models can combine built-in tools like Search with custom function calling (in Preview). For JSON output patterns, see my structured outputs guide.

Do I have to show the Search suggestions?

Yes, if you show grounded results to users. Render the HTML from searchEntryPoint.renderedContent and link the sources.

How does this compare to Claude’s web search tool?

The idea is the same: the model searches and returns citations. Pricing and response format differ, so see my Claude web search API guide for that side.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a home lab with a PC tower holding a tablet with a GROUNDING card, hook $14 per 1,000 searches