Search Grounding with Gemini
Search grounding is a powerful feature in the Gemini API that allows you to enhance your model's responses by providing relevant search results as context.
See Live Demo built using these code snippets
- Typescript
- Python
import {
DynamicRetrievalMode,
GoogleGenerativeAI,
} from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel(
{
model: "models/gemini-2.0-flash",
}
);
const result = await model.generateContent({
contents: [
{
role: "user",
parts: [{ text: searchQuery }],
},
],
tools: [
{
google_search: {},
},
],
});
console.log(result.response.candidates[0].groundingMetadata);
from google import genai
from google.genai.types import Tool, GenerateContentConfig, GoogleSearch
client = genai.Client()
model_id = "gemini-2.0-flash"
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"],
)
)
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.
print(response.candidates[0].grounding_metadata.search_entry_point.rendered_content)