以 Google 搜尋建立基準

「運用 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" \
  -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": {}
      }
    ]
  }'

如要瞭解詳情,請試用 Search tool notebook

如何運用 Google 搜尋建立基準

啟用 google_search 工具後,模型會自動處理搜尋、處理及引用資訊的整個工作流程。

grounding-overview

  1. 使用者提示:應用程式會將使用者提示傳送至 Gemini API,並啟用 google_search 工具。
  2. 提示分析:模型會分析提示,判斷 Google 搜尋是否能提供更完善的答案。
  3. Google 搜尋:如有需要,模型會自動生成一或多個搜尋查詢並執行。
  4. 處理搜尋結果:模型會處理搜尋結果、綜合分析資訊,並擬定回覆內容。
  5. 以搜尋結果為依據的回覆: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:包含網頁來源 (urititle) 的物件陣列。
  • groundingSupports:要將模型回應 text 連結至 groundingChunks 中來源的區塊陣列。每個區塊都會將文字 segment (由 startIndexendIndex 定義) 連結至一或多個 groundingChunkIndices。這是建立內文引用內容的關鍵。

您也可以搭配網址脈絡工具使用 Google 搜尋,同時以公開網路資料和您提供的特定網址做為回覆的基準。

使用內嵌引文標註來源

這項 API 會傳回結構化引用資料,讓您完全掌控如何在使用者介面中顯示來源。您可以使用 groundingSupportsgroundingChunks 欄位,將模型陳述直接連結至來源。以下是處理中繼資料的常見模式,可建立內嵌且可點選的引文。

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 模型 (舊版) 建立基準

建議使用 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
        }
      }
    }]
  }'

後續步驟