以 Google 搜尋建立基準

透過 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-3-flash-preview",
    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-3-flash-preview",
  contents: "Who won the euro 2024?",
  config,
});

console.log(response.text);

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview: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 工具後,模型會自動處理搜尋、處理及引用資訊的整個工作流程。

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:/...)

定價

使用 Gemini 3 搭配「以 Google 搜尋建立基準」功能時,系統會針對模型執行的每項搜尋查詢向專案收費。如果模型決定執行多個搜尋查詢來回應單一提示 (例如在同一個 API 呼叫中搜尋 "UEFA Euro 2024 winner""Spain vs England Euro 2024 final score"),則該要求會計為兩次工具使用次數。為計費起見,計算不重複查詢時,我們會忽略空白的網頁搜尋查詢。這項計費模式僅適用於 Gemini 3 模型;如果使用 Gemini 2.5 或更舊的模型進行搜尋基礎作業,系統會依提示次數向專案收費。

如需詳細的定價資訊,請參閱 Gemini API 定價頁面

支援的模型

不包括實驗版和預覽版模型。如要瞭解模型功能,請前往模型總覽頁面。

型號 以 Google 搜尋建立基準
Gemini 2.5 Pro ✔️
Gemini 2.5 Flash ✔️
Gemini 2.5 Flash-Lite ✔️
Gemini 2.0 Flash ✔️

支援的工具組合

您可以搭配使用「以 Google 搜尋為基礎」功能與其他工具,例如程式碼執行URL 環境,處理更複雜的使用情境。

後續步驟