Grounding & Google Search Integration
From the course Google Gemini API Development
Grounding with Google Search
Gemini can ground its responses with real-time Google Search results, providing up-to-date, factual answers.
Enabling Search Grounding
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "What are the latest developments in quantum computing?",
config: {
tools: [{ googleSearch: {} }],
},
});
Grounding Metadata
Responses include grounding metadata with sources:
- Search queries used by the model
- Source URLs and titles for citations
- Grounding chunks mapping response segments to sources
- Support scores indicating confidence levels
Use Cases for Grounding
- Current events — news, stock prices, weather
- Fact-checking — verify claims against web sources
- Research — gather information with citations
- Product info — current pricing, availability, reviews
Best Practices
- Enable grounding only when freshness matters — it adds latency
- Use grounding metadata to display source citations in your UI
- Combine grounding with system instructions for domain-specific searches
- Monitor grounding quality and fallback to non-grounded responses when needed
Common Pitfall: Ignoring Grounding Metadata
Grounding metadata is provided in the response but is often ignored by developers who only read response.text. Users who see factual claims without citations are less likely to trust the output. Always surface the sources:
const text = response.text;
const groundingMeta = response.candidates?.[0]?.groundingMetadata;
const sources = groundingMeta?.groundingChunks?.map(chunk => ({
title: chunk.web?.title,
uri: chunk.web?.uri,
}));
// Display sources alongside the response
return { answer: text, sources };
Best Practice: Use Dynamic Retrieval to Control Grounding Cost
Google charges extra for grounded requests. Dynamic retrieval lets Gemini decide whether to search based on the query — factual, time-sensitive questions trigger a search while stable questions do not:
config: {
tools: [{
googleSearch: {
dynamicRetrievalConfig: {
mode: "MODE_DYNAMIC",
dynamicThreshold: 0.7, // Only search if confidence below 70%
},
},
}],
}
Named Product Reference: Google AI Studio
Google AI Studio (aistudio.google.com) is the free browser-based interface for testing Gemini prompts, exploring models, and generating API keys. It includes a built-in prompt comparison tool that runs the same prompt across Gemini 2.5 Pro, Flash, and Flash Lite simultaneously — invaluable for finding the cheapest model that meets your quality bar before committing to an API integration.
Key Takeaways
- •Google Search grounding provides real-time, cited information
- •Grounding metadata includes source URLs and confidence scores
- •Enable grounding selectively — it adds latency but improves accuracy
- •Display source citations in your UI for user trust
Progress is kept in this browser only.