การอ้างอิงข้อมูลของ Google Search จะเชื่อมต่อโมเดล 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": {}
}
]
}'
ดูข้อมูลเพิ่มเติมได้โดยลองใช้สมุดบันทึกของเครื่องมือค้นหา
วิธีการทำงานของการอ้างอิงข้อมูลของ Google Search
เมื่อคุณเปิดใช้เครื่องมือ google_search
โมเดลจะจัดการเวิร์กโฟลว์ทั้งหมดของการค้นหา การประมวลผล และการอ้างอิงข้อมูลโดยอัตโนมัติ
- พรอมต์ของผู้ใช้: แอปพลิเคชันของคุณส่งพรอมต์ของผู้ใช้ไปยัง Gemini API โดยเปิดใช้เครื่องมือ
google_search
- การวิเคราะห์พรอมต์: โมเดลจะวิเคราะห์พรอมต์และพิจารณาว่า Google Search ช่วยปรับปรุงคำตอบได้หรือไม่
- Google Search: หากจําเป็น โมเดลจะสร้างคําค้นหาอย่างน้อย 1 รายการและดําเนินการโดยอัตโนมัติ
- การประมวลผลผลการค้นหา: โมเดลจะประมวลผลผลการค้นหา สังเคราะห์ข้อมูล และสร้างคำตอบ
- คำตอบที่อิงตามข้อมูลจริง: API จะแสดงคำตอบสุดท้ายที่ใช้งานง่ายซึ่งอิงตามผลการค้นหา การตอบกลับนี้ประกอบด้วยคำตอบแบบข้อความของโมเดลและ
groundingMetadata
พร้อมคำค้นหา ผลการค้นหาบนเว็บ และการอ้างอิง
ทำความเข้าใจการตอบกลับการกราวด์
เมื่อมีการตอบกลับที่สำเร็จแล้ว การตอบกลับจะมีฟิลด์ groundingMetadata
Structured Data นี้จำเป็นต่อการยืนยันการกล่าวอ้างและสร้างประสบการณ์การอ้างอิงที่สมบูรณ์ในแอปพลิเคชัน
{
"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
อย่างน้อย 1 รายการ ข้อมูลนี้เป็นกุญแจสำคัญในการสร้างการอ้างอิงในบรรทัด
นอกจากนี้ คุณยังใช้การเชื่อมโยงกับ Google Search ร่วมกับเครื่องมือบริบท 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 Search ระบบจะเรียกเก็บเงินจากโปรเจ็กต์ของคุณตามคำขอ API ที่มีเครื่องมือ google_search
หากโมเดลตัดสินใจที่จะเรียกใช้การค้นหาหลายรายการเพื่อตอบพรอมต์เดียว (เช่น การค้นหา "UEFA Euro 2024 winner"
และ "Spain vs England Euro 2024 final score"
ภายในการเรียก API เดียวกัน) ระบบจะนับเป็นการใช้เครื่องมือแบบเรียกเก็บเงินครั้งเดียวสําหรับคําขอนั้น
ดูข้อมูลราคาโดยละเอียดได้ที่หน้าราคาของ Gemini API
โมเดลที่รองรับ
ไม่รวมรุ่นทดลองและรุ่นตัวอย่าง คุณดูความสามารถของฟีเจอร์เหล่านี้ได้ในหน้าภาพรวมของโมเดล
รุ่น | การต่อสายกราวด์ด้วย Google Search |
---|---|
Gemini 2.5 Pro | ✔️ |
Gemini 2.5 Flash | ✔️ |
Gemini 2.0 Flash | ✔️ |
Gemini 1.5 Pro | ✔️ |
Gemini 1.5 Flash | ✔️ |
การต่อกราวด์ด้วย 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(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
}
}
}]
}'
ขั้นตอนถัดไป
- ลองใช้การเริ่มต้นใช้งานด้วย Google Search ในสูตรการแก้ปัญหาของ Gemini API
- ดูข้อมูลเกี่ยวกับเครื่องมืออื่นๆ ที่มี เช่น การเรียกใช้ฟังก์ชัน
- ดูวิธีเพิ่มพรอมต์ด้วย URL ที่เฉพาะเจาะจงโดยใช้เครื่องมือบริบทของ URL