ההארקה באמצעות חיפוש Google מקשרת את מודל Gemini לתוכן אינטרנט בזמן אמת, והיא פועלת בכל השפות הזמינות. כך Gemini יכול לספק תשובות מדויקות יותר ולצטט מקורות שאפשר לאמת מעבר לנקודת הזמן שעד אליה יש לו ידע.
ההארקה עוזרת לכם ליצור אפליקציות שיכולות:
- שיפור הדיוק העובדתי: צמצום ההזיות של המודל על ידי ביסוס התשובות על מידע מהעולם האמיתי.
- גישה למידע בזמן אמת: אפשר לקבל תשובות לשאלות על אירועים ונושאים עדכניים.
ציון מקורות: כדי לבסס את אמון המשתמשים, כדאי להציג את המקורות של הטענות שהמודל מציג.
Python
from google import genai
from google.genai import types
client = genai.Client()
grounding_tool = types.Tool(
google_search=types.GoogleSearch()
)
config = types.GenerateContentConfig(
tools=[grounding_tool]
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Who won the euro 2024?",
config=config,
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const groundingTool = {
googleSearch: {},
};
const config = {
tools: [groundingTool],
};
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Who won the euro 2024?",
config,
});
console.log(response.text);
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [
{
"parts": [
{"text": "Who won the euro 2024?"}
]
}
],
"tools": [
{
"google_search": {}
}
]
}'
אפשר לנסות את מחברת כלי החיפוש כדי לקבל מידע נוסף.
איך עיגון באמצעות חיפוש Google פועל
כשמפעילים את הכלי google_search, המודל מטפל בכל תהליך העבודה של חיפוש, עיבוד וציטוט מידע באופן אוטומטי.

- הנחיית משתמש: האפליקציה שולחת הנחיית משתמש אל Gemini API עם ההגדרה של הכלי
google_search. - ניתוח ההנחיה: המודל מנתח את ההנחיה וקובע אם חיפוש ב-Google יכול לשפר את התשובה.
- חיפוש Google: אם צריך, המודל יוצר באופן אוטומטי שאילתת חיפוש אחת או יותר ומריץ אותן.
- עיבוד תוצאות החיפוש: המודל מעבד את תוצאות החיפוש, מסנתז את המידע ומנסח תגובה.
- תשובה מבוססת: ה-API מחזיר תשובה סופית וידידותית למשתמש שמבוססת על תוצאות החיפוש. התשובה הזו כוללת את התשובה הטקסטואלית של המודל,
groundingMetadataעם שאילתות החיפוש, תוצאות החיפוש והציטוטים.
הסבר על תגובת ההארקה
אם ההארקה של התשובה מצליחה, התשובה כוללת את השדה groundingMetadata. הנתונים המובנים האלה חיוניים לאימות הטענות וליצירת חוויית ציטוט עשירה באפליקציה שלכם.
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title."
}
],
"role": "model"
},
"groundingMetadata": {
"webSearchQueries": [
"UEFA Euro 2024 winner",
"who won euro 2024"
],
"searchEntryPoint": {
"renderedContent": "<!-- HTML and CSS for the search widget -->"
},
"groundingChunks": [
{"web": {"uri": "https://vertexaisearch.cloud.google.com.....", "title": "aljazeera.com"}},
{"web": {"uri": "https://vertexaisearch.cloud.google.com.....", "title": "uefa.com"}}
],
"groundingSupports": [
{
"segment": {"startIndex": 0, "endIndex": 85, "text": "Spain won Euro 2024, defeatin..."},
"groundingChunkIndices": [0]
},
{
"segment": {"startIndex": 86, "endIndex": 210, "text": "This victory marks Spain's..."},
"groundingChunkIndices": [0, 1]
}
]
}
}
]
}
Gemini API מחזיר את המידע הבא עם groundingMetadata:
-
webSearchQueries: מערך של שאילתות החיפוש שנעשה בהן שימוש. המידע הזה שימושי לניפוי באגים ולהבנת תהליך החשיבה של המודל. -
searchEntryPoint: מכיל את ה-HTML ואת ה-CSS לעיבוד הצעות החיפוש הנדרשות. דרישות השימוש המלאות מפורטות בתנאים ובהגבלות. -
groundingChunks: מערך של אובייקטים שמכילים את המקורות מהאינטרנט (uriו-title). -
groundingSupports: מערך של נתחים לחיבור התגובה של המודלtextלמקורות ב-groundingChunks. כל מקטע מקשר טקסטsegment(מוגדר על ידיstartIndexו-endIndex) ל-groundingChunkIndicesאחד או יותר. זהו המפתח ליצירת ציטוטים בגוף הטקסט.
אפשר גם להשתמש בהארקה באמצעות חיפוש Google בשילוב עם כלי ההקשר של כתובת ה-URL כדי להארק את התשובות גם על נתונים מהאינטרנט הציבורי וגם על כתובות ה-URL הספציפיות שאתם מספקים.
ציטוט מקורות עם הפניות למקורות
ממשק ה-API מחזיר נתוני ציטוט מובְנים, כך שיש לכם שליטה מלאה באופן שבו אתם מציגים מקורות בממשק המשתמש. אפשר להשתמש בשדות groundingSupports ו-groundingChunks כדי לקשר את ההצהרות של המודל ישירות למקורות שלהן. הנה דפוס נפוץ לעיבוד המטא-נתונים כדי ליצור תגובה עם ציטוטים מוטבעים שאפשר ללחוץ עליהם.
Python
def add_citations(response):
text = response.text
supports = response.candidates[0].grounding_metadata.grounding_supports
chunks = response.candidates[0].grounding_metadata.grounding_chunks
# Sort supports by end_index in descending order to avoid shifting issues when inserting.
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:
# Create citation string like [1](link1)[2](link2)
citation_links = []
for i in support.grounding_chunk_indices:
if i < len(chunks):
uri = chunks[i].web.uri
citation_links.append(f"[{i + 1}]({uri})")
citation_string = ", ".join(citation_links)
text = text[:end_index] + citation_string + text[end_index:]
return text
# Assuming response with grounding metadata
text_with_citations = add_citations(response)
print(text_with_citations)
JavaScript
function addCitations(response) {
let text = response.text;
const supports = response.candidates[0]?.groundingMetadata?.groundingSupports;
const chunks = response.candidates[0]?.groundingMetadata?.groundingChunks;
// Sort supports by end_index in descending order to avoid shifting issues when inserting.
const sortedSupports = [...supports].sort(
(a, b) => (b.segment?.endIndex ?? 0) - (a.segment?.endIndex ?? 0),
);
for (const support of sortedSupports) {
const endIndex = support.segment?.endIndex;
if (endIndex === undefined || !support.groundingChunkIndices?.length) {
continue;
}
const citationLinks = support.groundingChunkIndices
.map(i => {
const uri = chunks[i]?.web?.uri;
if (uri) {
return `[${i + 1}](${uri})`;
}
return null;
})
.filter(Boolean);
if (citationLinks.length > 0) {
const citationString = citationLinks.join(", ");
text = text.slice(0, endIndex) + citationString + text.slice(endIndex);
}
}
return text;
}
const textWithCitations = addCitations(response);
console.log(textWithCitations);
התשובה החדשה עם הציטוטים בתוך הטקסט תיראה כך:
Spain won Euro 2024, defeating England 2-1 in the final.[1](https:/...), [2](https:/...), [4](https:/...), [5](https:/...) This victory marks Spain's record-breaking fourth European Championship title.[5]((https:/...), [2](https:/...), [3](https:/...), [4](https:/...)
תמחור
כשמשתמשים ב-Grounding עם חיפוש Google, הפרויקט מחויב על כל שאילתת חיפוש שהמודל מחליט להריץ. אם המודל מחליט להריץ כמה שאילתות חיפוש כדי לענות על הנחיה אחת (לדוגמה, חיפוש של "UEFA Euro 2024 winner" ושל "Spain vs England Euro 2024 final score" באותה קריאה ל-API), זה נחשב כשני שימושים מחויבים בכלי עבור הבקשה הזו.
למידע מפורט על התמחור, אפשר לעיין בדף התמחור של Gemini API.
מודלים נתמכים
מודלים ניסיוניים ומודלים בתצוגה מקדימה לא נכללים. אפשר לראות את היכולות שלהם בדף סקירה כללית של הדגם.
| דגם | עיגון באמצעות חיפוש Google |
|---|---|
| Gemini 2.5 Pro | ✔️ |
| Gemini 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
| Gemini 2.0 Flash | ✔️ |
| Gemini 1.5 Pro | ✔️ |
| Gemini 1.5 Flash | ✔️ |
שילובים נתמכים של כלים
אתם יכולים להשתמש ב-Grounding עם חיפוש Google יחד עם כלים אחרים כמו הרצת קוד והקשר של כתובת URL כדי להפעיל תרחישי שימוש מורכבים יותר.
הארקה באמצעות מודלים של Gemini 1.5 (גרסה קודמת)
מומלץ להשתמש בכלי google_search ב-Gemini 2.0 ואילך, אבל Gemini 1.5 תומך בכלי מדור קודם בשם google_search_retrieval. הכלי הזה כולל מצב dynamic שבו המודל מחליט אם לבצע חיפוש על סמך רמת הביטחון שלו בכך שההנחיה דורשת מידע עדכני. אם רמת הביטחון של המודל גבוהה מערך dynamic_threshold שהגדרתם (ערך בין 0.0 ל-1.0), הוא יבצע חיפוש.
Python
# Note: This is a legacy approach for Gemini 1.5 models.
# The 'google_search' tool is recommended for all new development.
import os
from google import genai
from google.genai import types
client = genai.Client()
retrieval_tool = types.Tool(
google_search_retrieval=types.GoogleSearchRetrieval(
dynamic_retrieval_config=types.DynamicRetrievalConfig(
mode=types.DynamicRetrievalConfigMode.MODE_DYNAMIC,
dynamic_threshold=0.7 # Only search if confidence > 70%
)
)
)
config = types.GenerateContentConfig(
tools=[retrieval_tool]
)
response = client.models.generate_content(
model='gemini-1.5-flash',
contents="Who won the euro 2024?",
config=config,
)
print(response.text)
if not response.candidates[0].grounding_metadata:
print("\nModel answered from its own knowledge.")
JavaScript
// Note: This is a legacy approach for Gemini 1.5 models.
// The 'googleSearch' tool is recommended for all new development.
import { GoogleGenAI, DynamicRetrievalConfigMode } from "@google/genai";
const ai = new GoogleGenAI({});
const retrievalTool = {
googleSearchRetrieval: {
dynamicRetrievalConfig: {
mode: DynamicRetrievalConfigMode.MODE_DYNAMIC,
dynamicThreshold: 0.7, // Only search if confidence > 70%
},
},
};
const config = {
tools: [retrievalTool],
};
const response = await ai.models.generateContent({
model: "gemini-1.5-flash",
contents: "Who won the euro 2024?",
config,
});
console.log(response.text);
if (!response.candidates?.[0]?.groundingMetadata) {
console.log("\nModel answered from its own knowledge.");
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [
{"parts": [{"text": "Who won the euro 2024?"}]}
],
"tools": [{
"google_search_retrieval": {
"dynamic_retrieval_config": {
"mode": "MODE_DYNAMIC",
"dynamic_threshold": 0.7
}
}
}]
}'
המאמרים הבאים
- כדאי לנסות את העיגון בחיפוש Google ב-Gemini API Cookbook.
- אפשר לקרוא על כלים זמינים אחרים, כמו הפעלת פונקציות.
- כאן מוסבר איך להוסיף לתיאורים כתובות URL ספציפיות באמצעות הכלי 'הקשר של כתובת URL'.