Gemini 中文指南
获取 API 密钥 ↗

文件搜索

↓ 下载 Markdown

Gemini API 通过文件搜索工具启用检索增强生成(“RAG”)。文件搜索导入、分块并索引您的数据,以便根据提供的提示快速检索相关信息。然后,检索到的信息将用作模型的上下文,使其能够提供更准确和相关的答案。文件搜索还能够提供多模态功能以及支持的文本嵌入 gemini-embedding-001,以及支持的图像/多模态嵌入 gemini-embedding-2.

查询时的文件存储和嵌入生成是免费的,您只需在首次索引文件时支付创建嵌入的费用以及正常的 Gemini 模型输入/输出 token 成本。这种新的计费模式使文件搜索工具的构建和扩展变得更容易、更经济高效。参见 定价 部分了解详细信息。

直接上传到文件搜索存储 #

本例演示如何直接上传文件到 文件搜索存储:

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

  client = genai.Client()

  # File name will be visible in citations
  file_search_store = client.file_search_stores.create(
      config={
          'display_name': 'your-fileSearchStore-name',
          'embedding_model': 'models/gemini-embedding-2'
      }
  )

  operation = client.file_search_stores.upload_to_file_search_store(
    file='sample.txt',
    file_search_store_name=file_search_store.name,
    config={
        'display_name' : 'display-file-name',
    }
  )

  while not operation.done:
      time.sleep(5)
      operation = client.operations.get(operation)

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents="""Can you tell me about [insert question]""",
      config=types.GenerateContentConfig(
          tools=[
              types.Tool(
                  file_search=types.FileSearch(
                      file_search_store_names=[file_search_store.name]
                  )
              )
          ]
      )
  )

  print(response.text)

检查 API 参考 uploadToFileSearchStore 了解更多信息。

导入文件 #

或者,您可以上传现有文件并 将其导入您的文件搜索存储:

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

  client = genai.Client()

  # File name will be visible in citations
  sample_file = client.files.upload(file='sample.txt', config={'name': 'display_file_name'})

  file_search_store = client.file_search_stores.create(
      config={
          'display_name': 'your-fileSearchStore-name',
          'embedding_model': 'models/gemini-embedding-2'
      }
  )

  operation = client.file_search_stores.import_file(
      file_search_store_name=file_search_store.name,
      file_name=sample_file.name
  )

  while not operation.done:
      time.sleep(5)
      operation = client.operations.get(operation)

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents="""Can you tell me about [insert question]""",
      config=types.GenerateContentConfig(
          tools=[
              types.Tool(
                  file_search=types.FileSearch(
                      file_search_store_names=[file_search_store.name]
                  )
              )
          ]
      )
  )

  print(response.text)

检查 API 参考 importFile 了解更多信息。

分块配置 #

当您将文件导入文件搜索存储时,它会自动分解为块、嵌入、索引并上传到文件搜索存储。如果您需要对分块策略进行更多控制,您可以指定 chunking_config 设置每个块的 token 的最大数量和重叠的 token 的最大数量。

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

  client = genai.Client()

  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
            }
          }
      }
  )

  while not operation.done:
      time.sleep(5)
      operation = client.operations.get(operation)

  print("Custom chunking complete.")

要使用文件搜索存储,请将其作为工具传递给 generateContent 方法,如图所示 上传 和 进口 例子。

它是如何运作的 #

文件搜索使用称为语义搜索的技术来查找与用户提示相关的信息。与标准的基于关键字的搜索不同,语义搜索可以理解查询的含义和上下文。

当您导入文件时,它会转换为称为的数字表示形式 嵌入,捕获上传内容的语义。这些嵌入存储在专门的文件搜索数据库中。当您进行查询时,它也会转换为嵌入。然后,系统执行文件搜索,从文件搜索存储中查找最相似和相关的文档块。

嵌入没有生存时间 (TTL);它们会一直存在,直到手动删除或模型被弃用。但是,文件会在 48 小时后被删除。

以下是使用文件搜索的过程的详细说明 uploadToFileSearchStore API:

  1. 创建文件搜索存储:文件搜索存储包含文件中经过处理的数据。它是语义搜索将操作的嵌入的持久容器。

  2. 上传文件并导入到文件搜索存储中:同时上传文件并将结果导入到您的文件搜索存储中。这会创建一个临时的 File 对象,它是对原始文档的引用。然后,该数据被分块、转换为文件搜索嵌入并建立索引。的 File 对象将在 48 小时后被删除,而导入到文件搜索存储中的数据将无限期存储,直到您选择删除它。

  3. 通过文件搜索进行查询: 最后,你使用 FileSearch 工具在一个 generateContent 打电话。在工具配置中,您指定 FileSearchRetrievalResource,它指向 FileSearchStore 你想要搜索。这告诉模型在特定的文件搜索存储上执行语义搜索,以查找相关信息来支持其响应。

文件搜索的索引和查询过程在此图中,虚线来自 文档 到 嵌入模型 (使用 gemini-embedding-001) 代表 uploadToFileSearchStore API(绕过 文件存储)。否则,使用 Files API 单独创建然后导入文件将索引过程从 文档 到 文件存储 然后到 嵌入模型.

文件搜索存储 #

文件搜索存储是文档嵌入的容器。虽然通过文件 API 上传的原始文件会在 48 小时后删除,但导入到文件搜索存储中的数据将无限期存储,直到您手动将其删除。您可以创建多个文件搜索存储来组织文档。的 FileSearchStore API 允许您创建、列出、获取和删除来管理您的文件搜索存储。文件搜索存储名称具有全局范围。

以下是如何管理文件搜索存储的一些示例:

python
  file_search_store = client.file_search_stores.create(
      config={
          'display_name': 'my-file_search-store-123',
          'embedding_model': 'models/gemini-embedding-2'
      }
  )

  for file_search_store in client.file_search_stores.list():
      print(file_search_store)

  my_file_search_store = client.file_search_stores.get(name='fileSearchStores/my-file_search-store-123')

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

文件搜索文件 #

您可以使用以下命令管理文件存储中的各个文档 文件搜索文件 API 至 list 文件搜索存储中的每个文档, get 有关文档的信息,以及 delete 按名称命名的文档。

python
  for document_in_store in client.file_search_stores.documents.list(parent='fileSearchStores/my-file_search-store-123'):
    print(document_in_store)

  file_search_document = client.file_search_stores.documents.get(name='fileSearchStores/my-file_search-store-123/documents/my_doc')
  print(file_search_document)

  client.file_search_stores.documents.delete(name='fileSearchStores/my-file_search-store-123/documents/my_doc')

文件元数据 #

您可以将自定义元数据添加到文件中以帮助过滤它们或提供其他上下文。元数据是一组键值对。

python
  operation = client.file_search_stores.import_file(
      file_search_store_name=file_search_store.name,
      file_name=sample_file.name,
      config={
          'custom_metadata': [
              {"key": "author", "string_value": "Robert Graves"},
              {"key": "year", "numeric_value": 1934}
          ]
      }
  )

当文件搜索存储中有多个文档并且只想搜索其中的子集时,这非常有用。

python
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      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="Robert Graves"',
                  )
              )
          ]
      )
  )
  print(response.text)

实施列表过滤器语法的指南 metadata_filter 可以在以下位置找到 google.aip.dev/160

多模态文件搜索可让您本地嵌入和搜索图像,从而实现丰富的多模态 RAG 应用程序。

配置嵌入模型 #

当您创建一个 FileSearchStore,您必须覆盖默认的纯文本嵌入模型才能使用多模态模型。使用 models/gemini-embedding-2 处理文本和图像。

python
  store = client.file_search_stores.create(
      config={
          "display_name": "Multimodal Catalog",
          "embedding_model": "models/gemini-embedding-2",
      }
  )

上传图片 #

使用多模态嵌入模型创建商店后,您可以使用中描述的相同上传 API 直接上传图像文件。 直接上传到文件搜索存储 或 导入文件.

图片文件要求:

  • 图像文件的分辨率最多为 4K x 4K 像素。
  • 支持的格式有 PNG、JPEG。

引文 #

当您使用文件搜索时,模型的响应可能包括引用,指定使用上传文档的哪些部分来生成答案。这有助于事实检查和验证。

您可以通过以下方式访问引文信息 grounding_metadata 响应的属性。

python
    print(response.candidates[0].grounding_metadata)

有关事实依据元数据结构的详细信息,请参阅 文件搜索食谱 或 事实依据和 Google 搜索的事实依据部分 文档。

页码 #

当您对包含页面的文档(例如 PDF)使用文件搜索时,模型的响应可能包括找到信息的页码。您可以通过以下方式访问此信息 page_number 的属性 retrieved_context.

python
    # Iterate through citations and check for page numbers
    for chunk in response.candidates[0].grounding_metadata.grounding_chunks:
       if chunk.retrieved_context and chunk.retrieved_context.page_number:
           print(f"Cited Page: {chunk.retrieved_context.page_number}")

媒体引用 #

当模型在生成过程中引用图像块时,API 在事实依据元数据中返回一个引用,其中包括 media_id。您可以使用此 ID 下载模型引用的确切图像块。这个 media_id 在多个搜索调用中保持不变,这使您可以可靠地检索相同的图像或使用 ID 缓存它。

以下代码片段是 REST 响应示例:

json
"groundingMetadata": {
  "groundingChunks": [
    {
      "retrievedContext": {
        "title": "product_image",
        "fileSearchStore": "fileSearchStores/my-store-123",
        "mediaId": "fileSearchStores/my-store-123/media/BlobId-456"
      }
    }
  ]
}

以下代码片段演示了如何检索 media_id 并下载媒体:

python
    # Iterate through citations and download media if present
    for chunk in response.candidates[0].grounding_metadata.grounding_chunks:
       if chunk.retrieved_context and chunk.retrieved_context.media_id:
           print(f"Cited Media ID: {chunk.retrieved_context.media_id}")
           # Download the blob using the SDK
           blob_content = client.file_search_stores.download_media(
               media_id=chunk.retrieved_context.media_id
           )
           # Save blob_content to file...

事实依据数据中的自定义元数据 #

如果您已将自定义元数据添加到文件中,则可以在模型响应的事实依据元数据中访问它。这对于将其他上下文(如 URL、页码或作者)从源文档传递到应用程序逻辑非常有用。每个 grounding_chunk 在 retrieved_context 包含此自定义元数据。

python
    response = client.models.generate_content(
        model="gemini-4-hydrogen",
        contents="Tell me about [insert question]",
        config=types.GenerateContentConfig(
            tools=[
                types.Tool(
                    file_search=types.FileSearch(
                        file_search_store_names=[file_search_store.name]
                    )
                )
            ]
        )
    )

    for chunk in response.candidates[0].grounding_metadata.grounding_chunks:
        if chunk.retrieved_context:
            print(f"Text: {chunk.retrieved_context.text}")
            if chunk.retrieved_context.custom_metadata:
                for metadata in chunk.retrieved_context.custom_metadata:
                    print(f"Metadata Key: {metadata.key}")
                    print(f"Value: {metadata.string_value or metadata.numeric_value}")

结构化输出 #

从 Gemini 3 型号开始,您可以将文件搜索工具与 结构化输出.

python
  from google import genai
  from google.genai import types
  from pydantic import BaseModel, Field

  class Money(BaseModel):
      amount: str = Field(description="The numerical part of the amount.")
      currency: str = Field(description="The currency of amount.")

  client = genai.Client()

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents="What is the minimum hourly wage in Tokyo right now?",
      config=types.GenerateContentConfig(
          tools=[
              types.Tool(
                  file_search=types.FileSearch(
                      file_search_store_names=[file_search_store.name]
                  )
              )
          ],
          response_mime_type="application/json",
          response_json_schema=Money.model_json_schema(),
      )
  )
  result = Money.model_validate_json(response.text)
  print(result)

支持的模型 #

以下型号支持文件搜索:

支持的工具组合 #

Gemini 4 和 Gemini 3 型号支持将内置工具(如文件搜索)与自定义工具 (函数调用) 相结合。了解更多信息 工具组合 页。

支持的文件类型 #

文件搜索支持多种文件格式,在以下部分中列出。

限制 #

速率限制 #

文件搜索 API 有以下限制以增强服务稳定性:

  • 最大文件大小/每个文档限制:100 MB

  • 项目文件搜索存储的总大小 (基于用户等级):* 免费:1国标

    • 等级 1:10国标
    • 等级 2:100国标
    • 等级 3:1 TB
  • 推荐:将每个文件搜索存储的大小限制在 20 GB 以下,以确保最佳检索延迟。

价格 #

  • 您需要根据现有的索引时间为嵌入付费 嵌入定价.

  • 存储免费。

  • 查询时嵌入是免费的。

  • 检索到的文档 token 按常规收费 上下文 token.

后续步骤 #

搜索标题、API 名称或正文内容