ファイル検索

Gemini API では、ファイル検索ツールを使用して検索拡張生成(RAG)が可能です。ファイル検索では、ユーザーのプロンプトに基づいて関連情報をすばやく取得できるように、データのインポート、チャンク化、インデックス登録が行われます。この情報はモデルにコンテキストとして提供され、モデルはより正確で関連性の高い回答を提供できるようになります。

uploadToFileSearchStore API を使用すると、既存のファイルをファイル検索ストアに直接アップロードできます。また、ファイルを同時に作成する場合は、ファイルを個別にアップロードしてからインポートすることもできます。

ファイル検索ストアに直接アップロードする

この例では、ファイルをファイル ストアに直接アップロードする方法を示します。

Python

from google import genai
from google.genai import types
import time

client = genai.Client()

# Create the file search store with an optional display name that shows in the grounding metadata
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})

# Upload and import a file into the file search store, supply a unique file name which will be visible in citations
operation = client.file_search_stores.upload_to_file_search_store(
  file='path/to/your/file.txt',
  file_search_store_name='unique_file_name'
)

# Wait until import is complete
while not operation.done:
    time.sleep(5)
    operation = client.operations.get(operation)

# Ask a question about the file
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="""Can you tell me about Robert Graves""",
    config=types.GenerateContentConfig(
        tools=[
            file_search=(
                  file_search_store_names=[file_search_store.name]
            )
        ]
    )
)

print(response.text)

ファイルのインポート

または、既存のファイルをアップロードしてファイル ストアにインポートすることもできます。

Python

from google import genai
from google.genai import types
import time

client = genai.Client()

# Upload the file using the Files API, supply a unique file name which will be visible in citations
sample_file = client.files.upload(file='sample.txt', config={'name': 'unique_file_name'})

# Create the file search store with an optional display name that shows in the grounding metadata
file_search_store = client.file_search_stores.create(config={'display_name': 'your-fileSearchStore-name'})

# Import the file into the file search store
operation = client.file_search_stores.import_file(
    file_search_store_name=file_search_store.name,
    file_name=sample_file.name
)

# Wait until import is complete
while not operation.done:
    time.sleep(5)
    operation = client.operations.get(operation)

# Ask a question about the file
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="""Can you tell me about Robert Graves""",
    config=types.GenerateContentConfig(
        tools=[
            file_search=(
                  file_search_store_names=[file_search_store.name]
            )
        ]
    )
)

print(response.text)

チャンク化構成

ファイルをファイル検索ストアにインポートすると、ファイルは自動的にチャンクに分割され、埋め込み、インデックス登録され、ファイル検索ストアにアップロードされます。チャンク分割戦略をより細かく制御する必要がある場合は、chunking_config 設定を指定して、チャンクあたりの最大トークン数と重複するトークンの最大数を設定できます。

# Upload and import and upload the file into the file search store with a custom chunking configuration
operation = client.file_search_stores.upload_to_file_search_store(
    file_search_store_name=file_search_store.name,
    file_name=sample_file.name,
    config={
        'chunking_config': {
          'white_space_config': {
            'max_tokens_per_chunk': 200,
            'max_overlap_tokens': 20
          }
        }
    }
)

ファイル検索ストアを使用するには、アップロードインポートの例に示すように、ツールとして generateContent メソッドに渡します。

仕組み

ファイル検索では、セマンティック検索と呼ばれる手法を使用して、ユーザーのプロンプトに関連する情報を見つけます。従来のキーワードベースの検索とは異なり、セマンティック検索はクエリの意味とコンテキストを理解します。

ファイルをインポートすると、テキストの意味を捉えるエンベディングと呼ばれる数値表現に変換されます。これらのエンベディングは、専用のファイル検索データベースに保存されます。クエリを行うと、クエリもエンベディングに変換されます。次に、システムはファイル検索を実行して、ファイル検索ストアから最も類似した関連性の高いドキュメント チャンクを見つけます。

ファイル検索 uploadToFileSearchStore API を使用する手順は次のとおりです。

  1. ファイル検索ストアを作成する: ファイル検索ストアには、ファイルから処理されたデータが含まれます。これは、セマンティック検索が動作するエンベディングの永続コンテナです。

  2. ファイルをアップロードしてファイル検索ストアにインポートする: ファイルをアップロードすると同時に、結果をファイル検索ストアにインポートします。これにより、未加工ドキュメントへの参照である一時的な File オブジェクトが作成されます。このデータはチャンク化され、ファイル検索エンベディングに変換されて、インデックスが作成されます。File オブジェクトは 48 時間後に削除されますが、ファイル検索ストアにインポートされたデータは、削除するまで無期限に保存されます。

  3. ファイル検索でクエリを実行する: 最後に、generateContent 呼び出しで FileSearch ツールを使用します。ツール構成で、検索する FileSearchStore を指す FileSearchRetrievalResource を指定します。これにより、モデルは特定のファイル検索ストアでセマンティック検索を実行し、回答のグラウンディングに関連する情報を見つけるようになります。

ファイル検索のインデックス登録とクエリのプロセス
ファイル検索のインデックス登録とクエリのプロセス

この図では、ドキュメントからエンベディング モデルgemini-embedding-001 を使用)への点線は、uploadToFileSearchStore API(ファイル ストレージをバイパス)を表しています。それ以外の場合、Files API を使用してファイルを個別に作成してからインポートすると、インデックス登録プロセスが Documents から File storage に移動し、Embedding model に移動します。

ファイル検索ストア

ファイル検索ストアは、ドキュメント エンベディングのコンテナです。File API を介してアップロードされた未加工ファイルは 48 時間後に削除されますが、ファイル検索ストアにインポートされたデータは、手動で削除するまで無期限に保存されます。ドキュメントを整理するために、複数のファイル検索ストアを作成できます。FileSearchStore API を使用すると、ファイル検索ストアの作成、一覧表示、取得、削除を行って管理できます。ファイル検索ストア名はグローバル スコープです。

ファイル検索ストアの管理方法の例を次に示します。

# Create a file search store (including optional display_name for easier reference)
file_search_store = client.file_search_stores.create(config={'display_name': 'my-file_search-store-123'})

# List all your file search stores
for file_search_store in client.file_search_stores.list():
    print(file_search_store)

# Get a specific file search store by name
my_file_search_store = client.file_search_stores.get(name='fileSearchStores/my-file_search-store-123')

# Delete a file search store
client.file_search_stores.delete(name='fileSearchStores/my-file_search-store-123', config={'force': True})

ファイルのメタデータ

カスタム メタデータをファイルに追加すると、ファイルをフィルタしたり、追加のコンテキストを提供したりするのに役立ちます。メタデータは Key-Value ペアのセットです。

# Import the file into the file search store with custom metadata
op = client.file_search_stores.import_file(
    file_search_store_name=file_search_store.name,
    file_name=sample_file.name,
    custom_metadata=[
        {"key": "author", "string_value": "Robert Graves"},
        {"key": "year", "numeric_value": 1934}
    ]
)

これは、ファイル検索ストアに複数のドキュメントがあり、そのサブセットのみを検索する場合に便利です。

# Use the metadata filter to search within a subset of documents
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="""Tell me about the book 'I, Claudius'""",
    config=types.GenerateContentConfig(
        tools=[
            types.Tool(
                file_search=types.FileSearch(
                  file_search_store_names=[file_search_store.name],
                  metadata_filter = 'author=Robet Graves',
                  )
            )
        ]
    )
)

print(response.text)

metadata_filter のリスト フィルタ構文の実装に関するガイダンスについては、google.aip.dev/160 をご覧ください。

引用

ファイル検索を使用すると、モデルの回答に、アップロードしたドキュメントのどの部分が回答の生成に使用されたかを指定する引用が含まれることがあります。これは、ファクト チェックと検証に役立ちます。

引用情報には、レスポンスの grounding_metadata 属性からアクセスできます。

print(response.candidates[0].grounding_metadata)

サポートされているモデル

次のモデルはファイル検索をサポートしています。

サポートされているファイル形式

ファイル検索は、次のセクションに記載されている幅広いファイル形式をサポートしています。

アプリケーション ファイルの種類

  • application/dart
  • application/ecmascript
  • application/json
  • application/ms-java
  • application/msword
  • application/pdf
  • application/sql
  • application/typescript
  • application/vnd.curl
  • application/vnd.dart
  • application/vnd.ibm.secure-container
  • application/vnd.jupyter
  • application/vnd.ms-excel
  • application/vnd.oasis.opendocument.text
  • application/vnd.openxmlformats-officedocument.presentationml.presentation
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  • application/vnd.openxmlformats-officedocument.wordprocessingml.document
  • application/vnd.openxmlformats-officedocument.wordprocessingml.template
  • application/x-csh
  • application/x-hwp
  • application/x-hwp-v5
  • application/x-latex
  • application/x-php
  • application/x-powershell
  • application/x-sh
  • application/x-shellscript
  • application/x-tex
  • application/x-zsh
  • application/xml
  • application/zip

テキスト ファイルの種類

  • text/1d-interleaved-parityfec
  • text/RED
  • text/SGML
  • text/cache-manifest
  • text/calendar
  • text/cql
  • text/cql-extension
  • text/cql-identifier
  • text/css
  • text/csv
  • text/csv-schema
  • text/dns
  • text/encaprtp
  • text/enriched
  • text/example
  • text/fhirpath
  • text/flexfec
  • text/fwdred
  • text/gff3
  • text/grammar-ref-list
  • text/hl7v2
  • text/html
  • text/javascript
  • text/jcr-cnd
  • text/jsx
  • text/markdown
  • text/mizar
  • text/n3
  • text/parameters
  • text/parityfec
  • text/php
  • text/plain
  • text/provenance-notation
  • text/prs.fallenstein.rst
  • text/prs.lines.tag
  • text/prs.prop.logic
  • text/raptorfec
  • text/rfc822-headers
  • text/rtf
  • text/rtp-enc-aescm128
  • text/rtploopback
  • text/rtx
  • text/sgml
  • text/shaclc
  • text/shex
  • text/spdx
  • text/strings
  • text/t140
  • text/tab-separated-values
  • text/texmacs
  • text/troff
  • text/tsv
  • text/tsx
  • text/turtle
  • text/ulpfec
  • text/uri-list
  • text/vcard
  • text/vnd.DMClientScript
  • text/vnd.IPTC.NITF
  • text/vnd.IPTC.NewsML
  • text/vnd.a
  • text/vnd.abc
  • text/vnd.ascii-art
  • text/vnd.curl
  • text/vnd.debian.copyright
  • text/vnd.dvb.subtitle
  • text/vnd.esmertec.theme-descriptor
  • text/vnd.exchangeable
  • text/vnd.familysearch.gedcom
  • text/vnd.ficlab.flt
  • text/vnd.fly
  • text/vnd.fmi.flexstor
  • text/vnd.gml
  • text/vnd.graphviz
  • text/vnd.hans
  • text/vnd.hgl
  • text/vnd.in3d.3dml
  • text/vnd.in3d.spot
  • text/vnd.latex-z
  • text/vnd.motorola.reflex
  • text/vnd.ms-mediapackage
  • text/vnd.net2phone.commcenter.command
  • text/vnd.radisys.msml-basic-layout
  • text/vnd.senx.warpscript
  • text/vnd.sosi
  • text/vnd.sun.j2me.app-descriptor
  • text/vnd.trolltech.linguist
  • text/vnd.wap.si
  • text/vnd.wap.sl
  • text/vnd.wap.wml
  • text/vnd.wap.wmlscript
  • text/vtt
  • text/wgsl
  • text/x-asm
  • text/x-bibtex
  • text/x-boo
  • text/x-c
  • text/x-c++hdr
  • text/x-c++src
  • text/x-cassandra
  • text/x-chdr
  • text/x-coffeescript
  • text/x-component
  • text/x-csh
  • text/x-csharp
  • text/x-csrc
  • text/x-cuda
  • text/x-d
  • text/x-diff
  • text/x-dsrc
  • text/x-emacs-lisp
  • text/x-erlang
  • text/x-gff3
  • text/x-go
  • text/x-haskell
  • text/x-java
  • text/x-java-properties
  • text/x-java-source
  • text/x-kotlin
  • text/x-lilypond
  • text/x-lisp
  • text/x-literate-haskell
  • text/x-lua
  • text/x-moc
  • text/x-objcsrc
  • text/x-pascal
  • text/x-pcs-gcd
  • text/x-perl
  • text/x-perl-script
  • text/x-python
  • text/x-python-script
  • text/x-r-markdown
  • text/x-rsrc
  • text/x-rst
  • text/x-ruby-script
  • text/x-rust
  • text/x-sass
  • text/x-scala
  • text/x-scheme
  • text/x-script.python
  • text/x-scss
  • text/x-setext
  • text/x-sfv
  • text/x-sh
  • text/x-siesta
  • text/x-sos
  • text/x-sql
  • text/x-swift
  • text/x-tcl
  • text/x-tex
  • text/x-vbasic
  • text/x-vcalendar
  • text/xml
  • text/xml-dtd
  • text/xml-external-parsed-entity
  • text/yaml

レート上限

File Search API には、サービスの安定性を維持するため、次の制限が適用されます。

  • 最大ファイルサイズ / ドキュメントあたりの上限: 100 MB
  • プロジェクトあたりのファイル検索ストア: 10
  • プロジェクト ファイル検索ストアの合計サイズ(ユーザーの階層に基づく):
    • 無料: 1 GB
    • Tier 1: 10 GB
    • Tier 2: 100 GB
    • Tier 3: 1 TB
  • 推奨事項: 最適な取得レイテンシを確保するため、各ファイル検索ストアのサイズを 20 GB 未満に制限します。

料金

  • デベロッパーには、既存のエンベディングの料金(100 万トークンあたり $0.15)に基づいて、インデックス登録時にエンベディングの料金が請求されます。
  • ストレージは無料です。
  • クエリタイム エンベディングは無料です。
  • 取得したドキュメント トークンは、通常のコンテキスト トークンとして課金されます。