Gemini File Search教程:构建文档问答与RAG应用
技术背景
在AI应用中,模型常因缺乏私有或最新数据而产生幻觉。RAG(检索增强生成)通过检索外部文档来增强模型回答的准确性。传统RAG需自行搭建向量数据库、嵌入模型和检索管道,成本高且复杂。Google Gemini File Search工具提供托管式解决方案,将文档上传至云端存储,模型生成时自动检索相关片段,并返回引用来源,简化了RAG开发。适用于客服问答、文档分析、知识库查询等场景。主要限制包括依赖Google云基础设施、API密钥管理风险、以及当前Interactions API中grounding metadata支持不完整。
核心原理
File Search工具的核心原理是:将文档上传至托管存储,系统自动对文档进行分块、嵌入(使用gemini-embedding-001或gemini-embedding-2),并建立索引。当模型生成时,工具根据用户输入进行语义搜索,返回最相关的文本块(top_k控制数量),作为上下文提供给模型,模型基于这些上下文生成有依据的回答。元数据过滤允许在搜索时附加条件,如genre='fiction',以缩小检索范围。多模态搜索使用gemini-embedding-2直接嵌入图像,实现视觉检索。
架构分析
系统架构包括:客户端(Colab笔记本)通过Google Gen AI SDK与Gemini API交互。核心组件有:FileSearchStore(存储容器)、Document(存储中的文档)、FileSearch工具(模型生成时的检索工具)。数据流:上传文档→存储分块嵌入→interactions.create请求携带工具→模型检索并生成→返回grounding metadata。设计决策:使用托管存储简化运维;API密钥控制访问;支持自定义元数据过滤;多模态嵌入模型选择。
完整实战教程
##### 版权所有 2026 Google LLC.
# @title Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
文件搜索快速入门
<a target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/File_Search.ipynb">
</a>
File Search 工具 允许您使用 Gemini 构建强大的检索增强生成(RAG)应用程序。它允许您将文档上传到托管存储中,然后在模型生成期间将其用作工具,使 Gemini 能够基于您的特定数据回答准确引用的问题。
在本快速入门中,您将学习如何:
* 创建 File Search 存储。
* 将文档上传到存储。
* 在 interactions.create 中将存储用作工具。
* 引用生成过程中使用的来源。
* 使用自定义元数据过滤搜索结果。
* 管理您的文档和存储。
有关 File Search 定价方式的信息,包括免费提供的内容详情,请参阅定价信息。
注意: 本笔记本使用 Interactions API,这是与 Gemini 模型交互的最新方式。正在寻找 generateContent 版本?请查看 归档分支。
安装依赖
首先,安装 Google Gen AI SDK。
# SDK 1.75.0 has latest multimodal File Search features
%pip install -U -q "google-genai>=2.9.0" # 1.75+ for Interactions API + File Search
身份验证
重要提示: File Search API 使用 API 密钥进行身份验证和访问控制。上传的文件与 API 密钥的云项目相关联。与其他使用 API 密钥的 Gemini API 不同,您的 API 密钥还授予对您上传到文件存储的所有数据的访问权限,因此请格外小心地保护您的 API 密钥。有关保护 API 密钥的最佳实践,请参阅 Google 的文档。
设置你的 API 密钥
要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果你还没有 API 密钥,或者不确定如何创建 Colab 密钥,请参阅身份验证了解详细步骤。
from google import genai
from google.colab import userdata
from google.genai import types
GEMINI_API_KEY = userdata.get("GEMINI_API_KEY")
client = genai.Client(api_key=GEMINI_API_KEY)
基础文件搜索
在本节中,你将下载一个示例文档,创建一个文件搜索存储,并使用它来回答问题。
创建文件搜索存储
创建一个新的文件搜索存储来存放您的文档。
file_search_store = client.file_search_stores.create(
config=types.CreateFileSearchStoreConfig(
display_name='My File Search Store'
)
)
print(f"Created store: {file_search_store.name}")
下载示例文档
从 Project Gutenberg 下载《现代主义诗歌概览》作为示例文本文件。
!wget -q https://www.gutenberg.org/cache/epub/76401/pg76401.txt -O sample_poetry.txt
!head sample_poetry.txt
将文件上传到存储库
直接将文本文件上传到存储库。摄取过程包含一些处理,因此您需要等待其完成才能进行搜索。
import time
upload_op = client.file_search_stores.upload_to_file_search_store(
file_search_store_name=file_search_store.name,
file='sample_poetry.txt',
config=types.UploadToFileSearchStoreConfig(
display_name='A Survey of Modernist Poetry',
)
)
print(f"Upload started: {upload_op.name}")
while not (upload_op := client.operations.get(upload_op)).done:
time.sleep(1)
print(".", end="")
print()
print("Processing complete.")
备选方案:从 File API 导入
如果你已经将文档上传到 File API,你可以直接将它们导入到 File Store 中。如果用户已经对文件进行过某些交互(例如生成摘要),并且已批准该文件用于存储,这可能会很有帮助。
file_ref = client.files.upload(
file='sample_poetry.txt',
config=types.UploadFileConfig(
display_name='A Survey of Modernist Poetry',
mime_type='text/plain',
)
)
print(f"Uploaded via File API: {file_ref.name}")
import_op = client.file_search_stores.import_file(
file_search_store_name=file_search_store.name,
file_name=file_ref.name,
)
print(f"File import started: {import_op.name}")
while not (import_op := client.operations.get(import_op)).done:
time.sleep(1)
print(".", end="")
print()
print("Processing complete.")
使用文件搜索生成内容
现在,在 interactions.create 请求中使用 file_search 工具,提出一个需要从上传文档中获取信息的问题。
MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}
interaction = client.interactions.create(
model=MODEL_ID,
input='What does the text say about E.E. Cummings?',
tools=[{"type": "file_search", "file_search_store_names": [file_search_store.name]}],
)
print(interaction.steps[-1].content[0].text)
附加字段
FileSearch 工具提供了一些选项来配置工具的工作方式,包括 top_k 和 metadata_filter。
top_k 控制从搜索工具返回并传递给生成步骤的块数。这与之前的示例相同,但只有 1 个块将用于生成答案。如果您知道只有一个正确的块需要考虑(k=1),或者您期望块之间有更多重叠并希望包含更多上下文(更高的 top_k),此控制有助于引导模型。
元数据过滤将在下一节中描述,您可以在 API 参考 中找到完整规范。
top_K = 1 # @param {"allow-input":true, isTemplate: true}
interaction = client.interactions.create(
model=MODEL_ID,
input='What does the text say about E.E. Cummings?',
tools=[{"type": "file_search", "file_search_store_names": [file_search_store.name], "top_k": top_K}],
)
print(interaction.steps[-1].content[0].text)
检查接地元数据和页码
响应中包含 grounding_metadata,其中包含对源文档的引用和参考。生成上下文中使用的文档块可在 grounding_metadata.grounding_chunks 中找到,如下所示。
每个块还包含一个 page_number 字段,它告诉你该块来自源文档的确切页码。这对于大型文档的事实核查和验证尤其有用。
[
GroundingChunk(
retrieved_context=GroundingChunkRetrievedContext(
text="""(the snippet of text contained in this chunk)""",
title='(the title of the document)',
page_number=5
)
), ...
]
import textwrap
# Note: Grounding metadata with detailed chunk information is not yet
# available in the Interactions API. Use generate_content API for grounding
print("File Search grounding metadata not yet available in Interactions API")
print("The response text is available via interaction.steps[-1].content[0].text")
此外,grounding_metadata 包含 grounding_supports,它提供了从响应文本到支持文档的引用,可用于提供注释。
支持项如下所示。
[
GroundingSupport(
grounding_chunk_indices=[
0, # The index in `grounding_chunks` to which this corresponds
],
segment=Segment(
start_index=123, # Indices into the generated text
end_index=456,
text='(the span of generated text being supported)'
)
), ...
]
from IPython.display import Markdown, display
# Annotated response display requires grounding metadata.
print("Annotated response display requires grounding metadata (not yet in Interactions API)")
元数据过滤
在添加文档时,你可以为文件附加自定义元数据,并使用它来过滤搜索结果。
上传带元数据的文件
下载另一本书《爱丽丝梦游仙境》,并上传它,附带关于体裁和作者的信息。
!wget -q https://www.gutenberg.org/files/11/11-0.txt -O alice_in_wonderland.txt
!head alice_in_wonderland.txt
upload_op = client.file_search_stores.upload_to_file_search_store(
file_search_store_name=file_search_store.name,
file='alice_in_wonderland.txt',
config=types.UploadToFileSearchStoreConfig(
display_name='Alice in Wonderland',
custom_metadata=[
types.CustomMetadata(key='genre', string_value='fiction'),
types.CustomMetadata(key='author', string_value='Lewis Carroll'),
]
)
)
while not (upload_op := client.operations.get(upload_op)).done:
time.sleep(1)
print(".", end="")
print()
print("Upload complete.")
自定义元数据可以以 string_value、numeric_value 或 string_list_value 类型提供。
types.CustomMetadata.model_fields.keys() - {'key'}
带元数据过滤的查询
现在,提出一个可能适用于两本书的问题,但使用过滤器将其限制为仅一本书。例如,询问关于“女王”的问题,但过滤条件为“小说”。
interaction = client.interactions.create(
model=MODEL_ID,
input='Who is the Queen?',
tools=[{"type": "file_search", "file_search_store_names": [file_search_store.name], "metadata_filter": 'genre = "fiction"'}],
)
print(interaction.steps[-1].content[0].text)
要了解如何构建复杂过滤器,请阅读 AIP-160 规范。
多模态文件搜索
借助多模态文件搜索,您可以原生嵌入并搜索文档和图像。通过使用 gemini-embedding-2 嵌入模型,图像被直接嵌入(而非通过 OCR),从而实现真正的视觉检索。
在本节中,您将创建一个多模态文件搜索存储,上传图像,使用 Gemini 查询它们,并检索媒体引用。
创建多模态文件搜索存储
要启用多模态搜索,请在创建存储时将 gemini-embedding-2 指定为 embedding_model。如果省略,存储将默认使用 gemini-embedding-001,该模型针对纯文本工作负载进行了优化。
| 嵌入模型 | 最适合的场景 |
|---|---|
| gemini-embedding-001(默认) | 文本密集型工作负载,成本优化 |
| gemini-embedding-2 | 多模态检索(文本*和*图像) |
mm_file_search_store = client.file_search_stores.create(
config=types.CreateFileSearchStoreConfig(
display_name='Multimodal Store',
embedding_model='models/gemini-embedding-2'
)
)
print(f"Created multimodal store: {mm_file_search_store.name}")
上传图片
使用 upload_to_file_search_store 将文件上传到存储中。使用 gemini-embedding-2 时,这适用于文档和图片(PNG、JPEG)。PDF 中的图片也会与文本一起被原生嵌入。
from IPython.display import Image, display
# Download a sample image
!curl -so sample_image.jpg "https://storage.googleapis.com/generativeai-downloads/images/jetpack.jpg"
display(Image("sample_image.jpg", width=300))
# Upload the image to the multimodal store
upload_op = client.file_search_stores.upload_to_file_search_store(
file_search_store_name=mm_file_search_store.name,
file='sample_image.jpg',
config=types.UploadToFileSearchStoreConfig(
display_name='Jetpack Image',
)
)
print(f"Upload started: {upload_op.name}")
while not (upload_op := client.operations.get(upload_op)).done:
time.sleep(1)
print(".", end="")
print()
print("Processing complete.")
使用多模态文件搜索进行查询
使用 file_search 工具查询多模态存储。模型会对文本和图像数据进行语义搜索,以生成有依据的响应。
interaction = client.interactions.create(
model=MODEL_ID,
input='Describe what is in the image stored in the file search store.',
tools=[{"type": "file_search", "file_search_store_names": [mm_file_search_store.name]}],
)
print(interaction.steps[-1].content[0].text)
获取媒体引用和页码
当模型引用图像块时,grounding 元数据包含一个 media_id 字段。您可以使用它来下载模型用于响应的确切图像。
对于文本引用,元数据还包含一个 page_number 字段,该字段告诉您块来自源文档中的确切页码。这对于大型文档的事实核查和验证特别有用。
# Grounding metadata for file search is not yet available in the Interactions API.
print("Grounding metadata not yet available in Interactions API")
管理文档
您还可以管理存储库中的单个文档。
列出文档
列出当前存储库中的所有文档。
print(f"Documents in {file_search_store.name}:")
for doc in client.file_search_stores.documents.list(parent=file_search_store.name):
print(f"- {doc.display_name} ({doc.name})")
获取文档
检索特定文档的详细信息,例如其处理状态或元数据。
# Get a document by ID
doc_id = doc.name # Or set a specific ID here.
sample_doc = client.file_search_stores.documents.get(name=doc_id)
if sample_doc:
print(f"Document details for {sample_doc.display_name}:")
print(f" Name: {sample_doc.name}")
print(f" Custom Metadata: {sample_doc.custom_metadata}")
删除文档
从存储中移除特定文档,而无需删除整个存储。
# Delete a specific document.
doc_to_be_deleted = doc_id
client.file_search_stores.documents.delete(
name=doc_to_be_deleted,
config=types.DeleteDocumentConfig(
# Set force to delete a non-empty document.
force=True
)
)
print(f"Deleted document: {doc_to_be_deleted}")
# Verify deletion
print("\nRemaining documents:")
for doc in client.file_search_stores.documents.list(parent=file_search_store.name):
print(f"- {doc.display_name}")
管理文件搜索存储
您可以列出、获取和删除您的文件搜索存储。
print("Stores:")
for store in client.file_search_stores.list():
print(f"- {store.name} ({store.display_name})")
清理
用完文件搜索存储后,最好将其删除,以避免不必要的存储成本。
client.file_search_stores.delete(name=file_search_store.name, config=types.DeleteFileSearchStoreConfig(force=True))
print(f"Deleted store: {file_search_store.name}")
client.file_search_stores.delete(name=mm_file_search_store.name, config=types.DeleteFileSearchStoreConfig(force=True))
print(f"Deleted store: {mm_file_search_store.name}")
下一步
有关 File Search 工具的更多信息,请务必查看以下内容。
* 定价信息
* 详细的 API 参考
常见问题
常见错误:1) API密钥未设置或权限不足,导致认证失败;2) 上传后未等待处理完成就查询,返回空结果;3) 元数据过滤语法错误,如使用单引号而非双引号;4) 存储或文档删除时未设置force=True,导致删除失败;5) 使用Interactions API时grounding metadata不可用,需改用generateContent。排查方法:检查API密钥、轮询操作状态、验证元数据格式、查看官方文档。
企业应用扩展
生产环境优化:1) 使用更合适的嵌入模型(gemini-embedding-2)提升多模态检索效果;2) 调整top_k参数平衡相关性和上下文长度;3) 利用元数据过滤减少检索噪声;4) 定期清理无用存储和文档以控制成本;5) 监控API调用量和延迟,必要时增加缓存。可扩展方向:结合File API实现文件预处理,使用自定义元数据实现多租户隔离,集成到Web应用或聊天机器人中。
总结
本教程面向有编程基础的开发者,深入讲解Google Gemini File Search工具,用于构建RAG应用。内容涵盖创建存储、上传文档、在interactions.create中使用工具、引用来源、元数据过滤、多模态搜索及文档管理。通过实践步骤和代码分析,帮助开发者掌握文件搜索的核心原理、架构设计、常见错误排查及生产优化,实现基于特定数据的准确问答。
- --
内容来源与验证
- 内容等级:PREMIUM_A
- 质量等级:S_CANDIDATE
- 难度:中级
- 验证等级:V1
- 原文作者:
- 原文日期:
- 来源许可:Apache-2.0
- 来源版本:
58306123ec70a653b5c86d853b0e55ce8ccf7ca0 - 查看原文
站内还有更多完整实战教程
加入会员,解锁全部教程、完整代码与持续更新内容。
加入会员