以 Google 搜尋建立 Gemini 模型基準可將模型連結至即時網頁內容,並支援所有可用語言。這可讓 Gemini 提供更準確的答案,並引用知識庫以外的驗證來源。
接地可協助您建構可執行下列操作的應用程式:
- 提高事實查核準確度:根據實際資訊回覆,減少模型幻覺。
- 存取即時資訊:回答有關近期事件和主題的問題。
提供引文:顯示模型聲明的來源,建立使用者信任。
Python
from google import genai
from google.genai import types
# Configure the client
client = genai.Client()
# Define the grounding tool
grounding_tool = types.Tool(
google_search=types.GoogleSearch()
)
# Configure generation settings
config = types.GenerateContentConfig(
tools=[grounding_tool]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Who won the euro 2024?",
config=config,
)
# Print the grounded response
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
// Configure the client
const ai = new GoogleGenAI();
// Define the grounding tool
const groundingTool = {
googleSearch: {},
};
// Configure generation settings
const config = {
tools: [groundingTool],
};
// Make the request
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Who won the euro 2024?",
config,
});
// Print the grounded response
console.log(response.text);
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [
{
"parts": [
{"text": "Who won the euro 2024?"}
]
}
],
"tools": [
{
"google_search": {}
}
]
}'
如要進一步瞭解相關資訊,請試用搜尋工具 Notebook。
利用 Google 搜尋建立基準的運作方式
啟用 google_search
工具後,模型會自動處理搜尋、處理及引用資訊的整個工作流程。
- 使用者提示:應用程式會在啟用
google_search
工具的情況下,將使用者提示傳送至 Gemini API。 - 提示分析:模型會分析提示,並判斷 Google 搜尋是否能改善答案。
- Google 搜尋:模型會視需要自動產生一或多個搜尋查詢並執行。
- 處理搜尋結果:模型會處理搜尋結果、整合資訊,並擬定回覆內容。
- 具體回應:API 會傳回最終的使用者友善回應,並根據搜尋結果提供具體資訊。這個回覆包含模型的文字答案,以及包含搜尋查詢、網頁搜尋結果和引文的
groundingMetadata
。
瞭解 Grounding Response
回應成功接地後,回應會包含 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 搜尋和網址內容工具,在回覆中加入公開網站資料和您提供的特定網址。
使用內嵌引文歸因來源
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:/...)
定價
使用 Google 搜尋建立基準時,系統會根據包含 google_search
工具的 API 要求收取費用。如果模型決定執行多個搜尋查詢來回答單一提示 (例如在同一個 API 呼叫中搜尋 "UEFA Euro 2024 winner"
和 "Spain vs England Euro 2024 final score"
),這會計為對該要求使用該工具的單一計費用途。
如需詳細的定價資訊,請參閱 Gemini API 定價頁面。
支援的型號
實驗版和預覽版模型不在此範圍內。您可以在「模型總覽」頁面中查看這些功能。
模型 | 利用 Google 搜尋建立基準 |
---|---|
Gemini 2.5 Pro | ✔️ |
Gemini 2.5 Flash | ✔️ |
Gemini 2.0 Flash | ✔️ |
Gemini 1.5 Pro | ✔️ |
Gemini 1.5 Flash | ✔️ |
使用 Gemini 1.5 模型建立基準 (舊版)
雖然建議在 Gemini 2.0 以上版本中使用 google_search
工具,但 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(api_key=os.getenv("GEMINI_API_KEY"))
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({ apiKey: process.env.GEMINI_API_KEY });
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?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
}
}
}]
}'
後續步驟
- 請參閱 Gemini API 教戰手冊中的「以 Google 搜尋做為回覆依據」。
- 瞭解其他可用工具,例如函式呼叫。
- 瞭解如何使用網址內容工具,為提示新增特定網址。