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?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. ユーザー プロンプト: アプリは、google_search ツールを有効にして、ユーザーのプロンプトを Gemini API に送信します。
  2. プロンプトの分析: モデルはプロンプトを分析し、Google 検索で回答を改善できるかどうかを判断します。
  3. Google 検索: 必要に応じて、モデルは 1 つ以上の検索語句を自動的に生成して実行します。
  4. 検索結果の処理: モデルは検索結果を処理し、情報を統合して回答を作成します。
  5. Grounded Response: 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 : モデル レスポンス textgroundingChunks のソースに接続するチャンクの配列。各チャンクは、テキスト segmentstartIndexendIndex で定義)を 1 つ以上の groundingChunkIndices にリンクします。これが、インライン引用を作成するうえで重要なポイントです。

Google 検索によるグラウンディングは、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 検索でグラウンディングを使用する場合、プロジェクトは google_search ツールを含む API リクエストごとに課金されます。モデルが 1 つのプロンプトに応答するために複数の検索クエリを実行する場合(同じ API 呼び出し内で "UEFA Euro 2024 winner""Spain vs England Euro 2024 final score" を検索する場合など)、そのリクエストに対するツールの課金対象の使用は 1 回とカウントされます。

料金の詳細については、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
        }
      }
    }]
  }'

次のステップ