文件搜索

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 设置,以设置每个块的 token 数量上限和重叠 token 数量上限。

# 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 工具。在工具配置中,您需要指定一个 FileSearchRetrievalResource,该 FileSearchRetrievalResource 指向您要搜索的 FileSearchStore。这会指示模型对该特定文件搜索存储区执行语义搜索,以查找相关信息来为回答提供依据。

文件搜索的索引编制和查询流程
文件搜索的索引和查询过程

在此图中,从文档嵌入模型(使用 gemini-embedding-001)的虚线表示 uploadToFileSearchStore API(绕过文件存储)。否则,使用 Files API 单独创建文件,然后导入文件,会将索引编制流程从文档移至文件存储空间,然后再移至嵌入模型

文件搜索存储区

文件搜索存储区是文档嵌入的容器。虽然通过 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})

文件元数据

您可以为文件添加自定义元数据,以便过滤文件或提供更多背景信息。元数据是一组键值对。

# 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

速率限制

为了确保服务稳定性,文件搜索 API 具有以下限制:

  • 文件大小上限 / 每个文档的限制:100 MB
  • 每个项目的文件搜索存储次数:10
  • 项目文件搜索存储空间总大小(取决于用户层级):
    • 免费:1 GB
    • 第 1 级:10 GB
    • 第 2 级:100 GB
    • 3 级:1 TB
  • 建议:将每个文件搜索存储区的大小限制在 20 GB 以下,以确保最佳检索延迟时间。

价格

  • 开发者需在编入索引时根据现有的嵌入定价(每 100 万个令牌 0.15 美元)支付嵌入费用。
  • 存储空间免费。
  • 查询时嵌入是免费的。
  • 检索到的文档令牌按常规上下文令牌收费。