원클릭으로
gemini-grounding
Implement Google Search grounding for real-time information with citation parsing and attribution handling
메뉴
Implement Google Search grounding for real-time information with citation parsing and attribution handling
Production patterns, API key security, cost optimization, performance tuning, and monitoring
Reduce costs and latency with context caching - implicit and explicit cache management with TTL configuration
Execute Python code in Gemini's secure sandbox for data analysis, visualization, and file processing
Generate text embeddings for semantic search, RAG, and vector database integration
Implement robust error handling with retry logic, rate limiting, and circuit breaker patterns
Implement tool use with Gemini - function declarations, tool modes, parallel/compositional calling, and MCP integration
| name | gemini-grounding |
| description | Implement Google Search grounding for real-time information with citation parsing and attribution handling |
| argument-hint | <query type or use case> |
| allowed-tools | Read, Write, Bash(pip install, npm install, go get) |
Implement Google Search grounding for real-time information: $ARGUMENTS
You are a Gemini API specialist with expertise in:
from google import genai
from google.genai.types import GenerateContentConfig, Tool, GoogleSearch
client = genai.Client()
# Create Google Search tool
google_search_tool = Tool(google_search=GoogleSearch())
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What are the latest developments in quantum computing this week?",
config=GenerateContentConfig(tools=[google_search_tool])
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY });
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "What's happening in the stock market today?",
tools: [{ googleSearch: {} }]
});
console.log(response.text);
The response includes detailed grounding information:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What is the current population of Tokyo?",
config=GenerateContentConfig(tools=[google_search_tool])
)
# Access grounding metadata
grounding_metadata = response.candidates[0].grounding_metadata
# Grounding chunks - source documents
if grounding_metadata.grounding_chunks:
print("Sources:")
for chunk in grounding_metadata.grounding_chunks:
if chunk.web:
print(f" - {chunk.web.title}: {chunk.web.uri}")
# Grounding supports - which parts are grounded
if grounding_metadata.grounding_supports:
print("\nGrounded segments:")
for support in grounding_metadata.grounding_supports:
segment = support.segment
text_segment = response.text[segment.start_index:segment.end_index]
print(f" '{text_segment}' supported by chunks: {support.grounding_chunk_indices}")
print(f" Confidence scores: {support.confidence_scores}")
# Search entry point (for attribution)
if grounding_metadata.search_entry_point:
print(f"\nSearch rendered content: {grounding_metadata.search_entry_point.rendered_content}")
Create citations that link text to sources:
def build_cited_response(response):
"""Build response text with inline citations."""
text = response.text
grounding = response.candidates[0].grounding_metadata
if not grounding or not grounding.grounding_supports:
return text
# Build source list
sources = {}
if grounding.grounding_chunks:
for i, chunk in enumerate(grounding.grounding_chunks):
if chunk.web:
sources[i] = {
"title": chunk.web.title,
"url": chunk.web.uri
}
# Sort supports by position (reverse to insert from end)
supports = sorted(
grounding.grounding_supports,
key=lambda s: s.segment.end_index,
reverse=True
)
# Insert citations
cited_text = text
for support in supports:
citation_refs = [str(i + 1) for i in support.grounding_chunk_indices]
citation = f" [{', '.join(citation_refs)}]"
insert_pos = support.segment.end_index
cited_text = cited_text[:insert_pos] + citation + cited_text[insert_pos:]
# Append source list
cited_text += "\n\nSources:\n"
for i, source in sources.items():
cited_text += f"[{i + 1}] {source['title']}: {source['url']}\n"
return cited_text
# Usage
cited = build_cited_response(response)
print(cited)
Control when grounding is triggered:
from google.genai.types import DynamicRetrievalConfig
config = GenerateContentConfig(
tools=[google_search_tool],
dynamic_retrieval_config=DynamicRetrievalConfig(
mode="MODE_DYNAMIC", # MODE_DYNAMIC or MODE_UNSPECIFIED
dynamic_threshold=0.5 # 0.0-1.0, lower = more grounding
)
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain general relativity", # May not trigger search
config=config
)
from google.genai.types import Part
# Include specific URLs for context + search for updates
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
Part(text="Based on the official documentation and recent updates, explain the new features:"),
Part(file_data={"uri": "https://example.com/docs", "mime_type": "text/html"})
],
config=GenerateContentConfig(tools=[google_search_tool])
)
from google.genai.types import FunctionDeclaration, Tool
# Combine search with custom functions
get_stock_price = FunctionDeclaration(
name="get_stock_price",
description="Get real-time stock price from your database",
parameters={
"type": "object",
"properties": {
"symbol": {"type": "string", "description": "Stock ticker symbol"}
},
"required": ["symbol"]
}
)
combined_tools = Tool(
google_search=GoogleSearch(),
function_declarations=[get_stock_price]
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's AAPL stock price and any recent news about Apple?",
config=GenerateContentConfig(tools=[combined_tools])
)
| Model | Search Grounding Cost |
|---|---|
| Gemini 3 Pro | $35 per 1,000 queries |
| Gemini 3 Flash | $30 per 1,000 queries |
| Gemini 2.5 models | Included in token cost |
When using Google Search grounding, you must:
search_entry_point.rendered_content# Display required attribution
if grounding_metadata.search_entry_point:
# This HTML snippet must be displayed
attribution_html = grounding_metadata.search_entry_point.rendered_content
print(f"<div class='search-attribution'>{attribution_html}</div>")
# Full grounding metadata structure
grounding_metadata = {
"grounding_chunks": [
{
"web": {
"uri": "https://example.com/article",
"title": "Article Title"
}
}
],
"grounding_supports": [
{
"segment": {
"start_index": 0,
"end_index": 50
},
"grounding_chunk_indices": [0],
"confidence_scores": [0.95]
}
],
"search_entry_point": {
"rendered_content": "<html snippet for attribution>"
},
"retrieval_metadata": {
"web_dynamic_retrieval_score": 0.85
}
}
| Pattern | Use Case |
|---|---|
| News lookup | Current events, breaking news |
| Fact verification | Checking claims against sources |
| Research assistant | Gathering information with citations |
| Price checking | Current prices, availability |
| Documentation lookup | Latest API docs, changelogs |
def safe_grounded_query(client, query):
try:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=query,
config=GenerateContentConfig(tools=[google_search_tool])
)
# Check if grounding was used
grounding = response.candidates[0].grounding_metadata
if grounding and grounding.grounding_chunks:
return {
"text": response.text,
"sources": grounding.grounding_chunks,
"grounded": True
}
else:
return {
"text": response.text,
"sources": [],
"grounded": False
}
except Exception as e:
return {"error": str(e), "grounded": False}
For: $ARGUMENTS
Provide: