GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
Articles/Advanced
Advanced/2026-03-11Advanced

Grounding with Google Search — Improve Gemini's Accuracy with Search

Learn how to use Gemini API's Grounding with Google Search to generate accurate, up-to-date responses. Covers Dynamic Retrieval, source citations, and cost management.

Gemini API192Grounding4Google Search2RAG14Search Integration

What Is Grounding?

One of the biggest weaknesses of LLMs is "hallucination" — generating responses that sound plausible but are factually incorrect or outdated. Grounding with Google Search addresses this by anchoring Gemini's responses in actual Google search results.

Basic Usage

import google.genai as genai
 
client = genai.Client(api_key="YOUR_API_KEY")
 
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What are the latest AI industry trends in 2026?",
    config={
        "tools": [{"google_search": {}}]
    }
)
 
print(response.text)

With this simple configuration, Gemini automatically performs Google searches and generates responses based on the results.

Using Grounding Metadata

Source information is returned as grounding_metadata.

for candidate in response.candidates:
    meta = candidate.grounding_metadata
    if meta:
        # Search queries used
        for query in meta.web_search_queries:
            print(f"Search query: {query}")
 
        # Source information
        for chunk in meta.grounding_chunks:
            print(f"Title: {chunk.web.title}")
            print(f"URL: {chunk.web.uri}")
 
        # Grounding support details
        for support in meta.grounding_supports:
            print(f"Text: {support.segment.text}")

Dynamic Retrieval

Not every request needs a search. Dynamic Retrieval lets Gemini automatically decide when searching is necessary.

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Explain the basic principles of quantum computing",
    config={
        "tools": [{
            "google_search": {
                "dynamic_retrieval_config": {
                    "mode": "MODE_DYNAMIC",
                    "dynamic_threshold": 0.5
                }
            }
        }]
    }
)

Adjust dynamic_threshold to control search sensitivity:

  • 0.0: Always search
  • 0.5: Balanced threshold (recommended default)
  • 1.0: Rarely search

Comparison with Custom RAG

AspectGrounding with Google SearchCustom RAG
Data sourceGoogle search indexYour own database
SetupZero (API parameter only)Requires vector DB
FreshnessReal-timeDepends on update frequency
CostPer API usageInfrastructure + API costs
CustomizationLowHigh
Internal dataNot availableSupported

Implementation Patterns

News Summary Bot

def get_news_summary(topic: str) -> str:
    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=f"Summarize the 3 latest news items about {topic}. Include source URLs.",
        config={
            "tools": [{"google_search": {}}]
        }
    )
    return response.text

Fact Checker

def fact_check(claim: str) -> str:
    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents=f"Fact-check the following claim using search results. Provide verdict and evidence.\n\nClaim: {claim}",
        config={
            "tools": [{"google_search": {}}]
        }
    )
    return response.text

Cost Management

Grounding with Google Search is powerful but incurs additional cost per request.

Optimization tips:

  • Use Dynamic Retrieval to avoid unnecessary searches
  • Disable grounding for creative tasks that don't need fact-checking
  • For batch processing, generate answers without search first, then apply grounding only to low-confidence sections

Limitations

  • Search results depend on Google's search index — unindexed information cannot be retrieved
  • Internal or private data is inaccessible (use custom RAG for those cases)
  • Search result language is influenced by the prompt language

Common Pitfalls and Things to Watch For

Grounding is easy to enable, but in production you run into subtle issues — searches that never fire, citations that drift, display requirements you didn't know about. Wiring this into my own projects as an indie developer, I lost time to a few of these before I understood what was happening. Here are the ones worth knowing before you ship.

grounding_metadata comes back empty

When no source information is returned, check web_search_queries first. If it's empty, no search ran at all.

Gemini skips the search when it decides its internal knowledge is enough, or when the prompt has no time-sensitive angle. To force a fresh lookup, anchor the prompt in time — "the latest," "as of June 2026" — so the model leans toward searching.

dynamic_threshold has no effect

dynamic_retrieval_config and dynamic_threshold belong to the google_search_retrieval tool on Gemini 1.5 models. On the Gemini 2.5 google_search tool they're ignored, and the model decides whether to search on its own.

If changing the threshold on a 2.5 model seems to do nothing, this mismatch is why. On 2.5, just pass {"google_search": {}}.

Citation offsets drift (especially for multibyte text)

The start_index / end_index in grounding_supports.segment are UTF-8 byte offsets. Python strings are indexed by character, not byte, so slicing response.text directly misaligns citations for Japanese and other multibyte text.

Encode to bytes first, slice, then decode:

raw = response.text.encode("utf-8")
for support in meta.grounding_supports:
    seg = support.segment
    cited = raw[seg.start_index:seg.end_index].decode("utf-8")
    sources = [meta.grounding_chunks[i].web.uri
               for i in support.grounding_chunk_indices]
    print(cited, "→", sources)

Search Suggestions are required

When you display a grounded response, Google's terms require you to show the Search Suggestions. The ready-to-use HTML lives in grounding_metadata.search_entry_point.rendered_content — embed it near the answer. Omitting it may violate the terms of use.

Searches run but return stale or wrong facts

If the search fires but the content is outdated, pin the time period in the prompt and lower temperature to keep the model faithful to the retrieved results.

When fact-checking is the goal, use gemini-2.5-pro instead of gemini-2.5-flash and state explicitly that it should not infer beyond what the search results say.

Looking back

Grounding with Google Search dramatically improves the accuracy of Gemini's responses. It's essential for use cases where up-to-date information and fact-checking matter. Combined with Dynamic Retrieval, you can optimize the balance between cost and accuracy.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Advanced2026-07-08
When Your Knowledge Base Shifts Mid-Run: Pinning File Search to an Execution Epoch for Consistent Agent Grounding
When a File Search store is updated while a Managed Agent is running, a single execution can mix old and new grounding. Borrowing MVCC ideas, pinning an execution epoch keeps one agent run's evidence consistent. Here is the design and implementation.
Advanced2026-07-08
One File Search Store for Many Apps: Splitting Retrieval With customMetadata and Chunk Config
Put several apps' FAQs in a single Gemini File Search store and metadataFilter can silently return empty grounding, or answers get split across chunk boundaries. Here is the customMetadata design, the AIP-160 filter-syntax trap, and measured chunkingConfig tuning.
Advanced2026-06-01
Trimming Gemini Embeddings from 3072 to 768 Dimensions: A Matryoshka Approach to Cutting Vector DB Cost and Latency
gemini-embedding-001 returns 3072-dimensional vectors, but thanks to Matryoshka representation you can keep only the leading dimensions with almost no quality loss. This is a design for trimming to 768 to cut vector DB storage and latency, including the re-normalization pitfall and coarse-to-fine search code.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →