การอ้างอิงข้อมูลด้วย 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" \
-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 Search
เมื่อเปิดใช้เครื่องมือ google_search
โมเดลจะจัดการเวิร์กโฟลว์ทั้งหมดของการค้นหา ประมวลผล และอ้างอิงข้อมูลโดยอัตโนมัติ
- พรอมต์ของผู้ใช้: แอปพลิเคชันของคุณจะส่งพรอมต์ของผู้ใช้ไปยัง Gemini API โดย
google_search
เปิดใช้เครื่องมือ - การวิเคราะห์พรอมท์: โมเดลจะวิเคราะห์พรอมท์และพิจารณาว่า Google Search จะช่วยปรับปรุงคำตอบได้หรือไม่
- Google Search: หากจำเป็น โมเดลจะสร้างคำค้นหาอย่างน้อย 1 รายการโดยอัตโนมัติและดำเนินการค้นหา
- การประมวลผลผลการค้นหา: โมเดลจะประมวลผลผลการค้นหา สังเคราะห์ข้อมูล และสร้างคำตอบ
- คำตอบที่อิงตามข้อมูล: 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
อย่างน้อย 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:/...)
ราคา
เมื่อใช้การอ้างอิงจากข้อมูลใน Google Search ระบบจะเรียกเก็บเงินจากโปรเจ็กต์ต่อคำขอ API ที่มีเครื่องมือ google_search
หากโมเดลตัดสินใจที่จะเรียกใช้คำค้นหาหลายรายการเพื่อตอบพรอมต์เดียว (เช่น ค้นหา "UEFA Euro 2024 winner"
และ "Spain vs England Euro 2024 final score"
ภายใน API Call เดียวกัน) ระบบจะนับเป็นการใช้เครื่องมือที่เรียกเก็บเงินได้ครั้งเดียวสำหรับคำขอนั้น
ดูข้อมูลการกำหนดราคาโดยละเอียดได้ที่หน้าราคาของ 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()
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 Search ในสูตรการแก้ปัญหาของ Gemini API
- ดูข้อมูลเกี่ยวกับเครื่องมืออื่นๆ ที่พร้อมใช้งาน เช่น การเรียกใช้ฟังก์ชัน
- ดูวิธีเพิ่มพรอมต์ด้วย URL ที่เฉพาะเจาะจงโดยใช้เครื่องมือบริบท URL