File API 使用指南:Google AI 文件上传与处理
技术背景
Gemini API 支持多模态提示,但直接传递大文件(如视频、长文本)会受限于请求大小和延迟。File API 提供异步上传机制,将文件存储于云端,通过 URI 引用,使提示请求轻量化。它解决大文件传输、重复上传和生命周期管理问题,适用于需要处理视频、音频、大型文档或代码库的场景。限制包括:文件大小上限 2GB,项目总存储 20GB,保留 48 小时,且不可下载。
核心原理
File API 基于 REST 架构,提供 files.upload、files.get、files.delete 和 files.register_files 等端点。上传时,客户端将文件内容发送至服务端,服务端存储并返回元数据(name、uri、display_name)。uri 用于在 GenerateContent 或 Interactions API 中引用文件。文件与 API 密钥的云项目关联,存储 48 小时。对于 GCS 对象,需先注册以建立关联。
架构分析
系统组件包括:客户端 SDK(google-genai)、File API 服务、Gemini 模型 API。数据流:客户端上传文件 -> File API 存储并返回 URI -> 客户端在提示中引用 URI -> Gemini API 获取文件并生成响应。设计决策:异步上传解耦文件传输与推理,支持大文件;URI 引用简化提示构造;存储生命周期管理自动清理。
完整实战教程
##### 版权所有 2026 Google LLC.
# @title 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.
Gemini API:文件 API 快速入门
<a target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/File_API.ipynb">
</a>
Gemini API 支持使用文本、图像和音频数据进行提示,也称为*多模态*提示。您可以在提示中包含文本、图像和音频。对于小图像,您可以在提供提示时直接指向本地文件。对于较大的文本文件、图像、视频和音频,请先使用 File API 上传文件,然后再将其包含在提示中。
File API 允许每个项目存储最多 20GB 的文件,每个文件大小不超过 2GB。文件存储 48 小时,在此期间可以使用您的 API 密钥进行生成。在 Gemini API 可用的所有区域 中,此功能免费提供。
有关有效文件格式(MIME 类型)和支持的模型的信息,请参阅支持的文件格式文档,并查看本指南末尾的文本示例。
本指南介绍如何使用 File API 上传媒体文件,并将其包含在对 Gemini API 的 GenerateContent 调用中。有关更多信息,请参阅代码示例。
注意: 本笔记本使用 Interactions API,这是与 Gemini 模型交互的最新方式。正在寻找 generateContent 版本?请查看 归档分支。
安装依赖
%pip install -U -q "google-genai>=2.9.0" # 1.57 for File API features # 2.0 is needed to use the interactions API
身份验证
重要提示: File API 使用 API 密钥进行身份验证和访问。上传的文件与 API 密钥的云项目关联。您的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab Secret 中。
设置你的 API 密钥
要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果你还没有 API 密钥,或者不确定如何创建 Colab 密钥,请参阅 [身份验证]
](../quickstarts/Authentication.ipynb) 查看演练。
from google import genai
from google.colab import userdata
GEMINI_API_KEY = userdata.get("GEMINI_API_KEY")
client = genai.Client(api_key=GEMINI_API_KEY)
上传文件
文件 API 允许你上传多种多模态 MIME 类型,包括图像和音频格式。文件 API 处理可用于通过 client.interactions.create(或 client.models.generate_content)生成内容的输入。
文件 API 接受小于 2GB 的文件,每个项目最多可存储 20GB 的文件。文件保留 2 天,且无法从 API 下载。
首先,你需要准备一张示例图片上传到 API。
注意:你也可以上传自己的文件来使用。
from IPython.display import Image, display
import urllib.request
urllib.request.urlretrieve(
"https://storage.googleapis.com/generativeai-downloads/images/jetpack.jpg",
"image.jpg"
)
display(Image(filename="image.jpg"))
接下来,您需要将该文件上传到 File API。
sample_file = client.files.upload(file="image.jpg")
print(f"Uploaded file '{sample_file.name}' as: {sample_file.uri}")
response 显示 File API 为上传的文件存储了指定的 display_name,以及一个 uri,用于在 Gemini API 调用中引用该文件。使用 response 来跟踪上传文件如何映射到 URI。
根据你的用例,你可以将 URI 存储在诸如 dict 或数据库之类的结构中。
获取文件
上传文件后,你可以通过调用 files.get 来验证 API 是否成功接收了文件。
此操作允许你获取已上传到 File API 的文件元数据,这些文件与你的 API 密钥所属的 Cloud 项目相关联。只有 name(以及由此衍生的 uri)是唯一的。如果你自行管理唯一性,则仅使用 displayName 来标识文件。
file = client.files.get(name=sample_file.name)
print(f"Retrieved file '{file.name}' as: {sample_file.uri}")
生成内容
上传文件后,您可以发出引用 File API URI 的 interactions.create 请求。
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=[
{"type": "text", "text": "Describe the image with a creative description."},
{"type": "document", "uri": sample_file.uri},
],
)
print(interaction.steps[-1].content[0].text)
多文件上传
你经常需要一次上传多个文件。下面是一个快速示例,展示如何实现:
!git clone -q --depth 1 https://github.com/googleapis/python-genai
import pathlib
files = []
for p in pathlib.Path("python-genai").rglob('*.py'):
if 'test' in str(p):
continue
f = client.files.upload(file=p, config={'display_name': str(p)})
# The API doesn't see the file name, so add those to the list of parts.
files.append(f"<<<File: {str(p)}>>>")
files.append(f)
print('.', end='')
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "text", "text": "Hi, could you give me a summary of this code base?"},
] + [{"type": "document", "uri": f.uri} for f in files],
)
print(interaction.steps[-1].content[0].text)
使用 Google Cloud Storage 中的文件
Gemini API 支持访问存储在 Google Cloud Storage (GCS) 中的对象。由于 GCS 对象与 Gemini API 的安全模型不同,你需要先注册文件才能使用它们。
要在 File API 中注册 GCS 对象,你需要使用具有 Storage Object Viewer 权限的身份进行身份验证,并启用相应的 OAuth 范围。具体机制因环境而异,例如,你可以下载服务账号凭据在你自己的基础设施上使用,或者在配置了服务账号的 Compute Engine 实例上运行。
对于本笔记本,你将通过 gcloud 配置用户凭据。
# Use the same project ID you're using for the Gemini API project
PROJECT_ID = "your-project-id" # @param {type: "string"}
!gcloud config set project {PROJECT_ID}
!gcloud auth application-default login --no-launch-browser --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only"
现在获取你的凭据并注册你的对象。
注意:如果你要单独注册文件(与生成代码分开),你需要创建一个用 API 密钥初始化的 genai.Client 对象。此方法不使用 API 密钥,但仍需要它来确保客户端未连接到 Vertex AI 后端。
将文件上传到你正在使用的项目中的存储桶:https://docs.cloud.google.com/storage/docs/uploading-objects。然后获取 URI 并注册文件:
import google.auth
credentials, project_id = google.auth.default()
registered_gcs_files = client.files.register_files(
auth=credentials,
uris=["gs://your-bucket/some-file.pdf"]
)
register_files 端点会返回与所提供的 URI 关联的文件。然后,您可以直接在提示中使用这些文件,配合 generate_content 使用,或者存储这些 name 以便稍后使用。
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "text", "text": "What are these documents about?"},
] + [{"type": "document", "uri": f.uri} for f in registered_gcs_files.files],
)
print(interaction.steps[-1].content[0].text)
删除文件
文件会在2天后自动删除,或者你也可以使用 files.delete() 手动删除它们。
client.files.delete(name=sample_file.name)
print(f"Deleted {sample_file.name}.")
支持的文本类型
除了支持媒体上传外,File API 还可用于将文本文件(如 Python 代码或 Markdown 文件)嵌入到提示中。
以下示例展示了如何使用 File API 将 Markdown 文件加载到提示中。
# Download a markdown file and ask a question.
from IPython.display import Markdown, display
import urllib.request
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/google-gemini/cookbook/main/CONTRIBUTING.md",
"contrib.md"
)
md_file = client.files.upload(
file="contrib.md",
config={
"display_name": "CONTRIBUTING.md",
},
)
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "document", "uri": md_file.uri},
{"type": "text", "text": "Summarize this document in a few sentences."},
],
)
display(Markdown(interaction.steps[-1].content[0].text))
一些常见的文本格式会被自动检测,例如 text/x-python、text/html 和 text/markdown。如果你使用的文件已知是文本,但 API 未能自动检测为文本,你可以显式指定 MIME 类型为 text/plain。
# Download some C++ code and force the MIME as text when uploading.
import urllib.request
from IPython.display import Markdown, display
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/google/gemma.cpp/main/examples/hello_world/run.cc",
"gemma.cpp"
)
cpp_file = client.files.upload(
file="gemma.cpp",
config={
"display_name":"gemma.cpp",
"mime_type":"text/plain"
}
)
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "document", "uri": cpp_file.uri},
{"type": "text", "text": "Explain this code and identify any potential bugs."},
],
)
display(Markdown(interaction.steps[-1].content[0].text))
外部文件和 URL
除了 File API 之外,您还可以直接向 Gemini API 提供一些 URL,包括公共 HTTPS URL 以及云存储平台上内容的签名 URL。
直接 HTTPS URL
只要 URL 是公开的、没有付费墙,并且包含支持的文件类型,你就可以将它们添加到提示中,API 在处理提示时会下载内容。
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=[
{"type": "text", "text": "Describe the image with a creative description."},
{"type": "image", "uri": "https://storage.googleapis.com/generativeai-downloads/images/jetpack.jpg"},
],
)
print(interaction.steps[-1].content[0].text)
签名 URL
如果您的数据存储在私有云存储系统中,例如 S3 或 Azure Blob Storage,您可以生成一个签名 URL 并将其传递给 Gemini API 直接使用,从而避免从您自己的存储中下载文件并在另一个平台上管理其生命周期。
这些 URL 在每次使用时都会被请求,因此在宿主平台上撤销访问权限将确保内容无法通过未缓存的 Gemini API 请求获得。
以下代码演示了如何对 S3 对象进行签名。请参阅您的特定提供商的文档,了解如何对您的特定对象进行签名。
# pip install boto3
import boto3
s3 = boto3.client('s3')
signed_url = s3.generate_presigned_url(
'get_object',
Params={
# Set your bucket name here.
'Bucket': 'my-bucket-name',
# And the path to the object here.
'Key': 'document.pdf'
},
ExpiresIn=3600 # In seconds
)
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}
# Obtain the signed URL from your provider, or see the S3
# example code above.
signed_url = "https://..." # @param {type: "string"}
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "text", "text": "Summarise this document."},
{"type": "document", "uri": signed_url},
],
)
print(interaction.steps[-1].content[0].text)
后续步骤
有用的 API 参考:
有关 File API 的更多信息,请查看其 API 参考。您还可以在此文件夹中找到更多代码示例。
相关示例
查看这些使用 File API 的示例,让您更了解如何使用这一非常实用的功能:
* 与 Gemini API 分享语音备忘录并集思广益
继续探索 Gemini API
如果您还不熟悉,请了解如何计算 token。然后查看如何使用 File API 将音频或视频文件与 Gemini API 结合使用。
常见问题
常见错误:1) 文件过大或项目存储超限,需检查文件大小和项目配额。2) 认证失败,确保 API 密钥正确且具有权限。3) 文件未找到,检查 name 或 uri 是否正确。4) GCS 注册失败,需配置 Storage Object Viewer 权限和 OAuth 范围。排查方法:使用 files.get 验证上传状态,检查日志和错误信息。
企业应用扩展
生产环境优化:1) 使用异步上传和批量处理提高效率。2) 对频繁使用的文件缓存 URI,减少重复上传。3) 监控存储配额,及时删除过期文件。4) 对于敏感数据,使用签名 URL 控制访问。5) 结合模型能力,对文件进行预处理(如压缩、转码)以优化性能。
总结
本教程深入讲解 Gemini API 的 File API,用于上传和管理多模态文件(图像、音频、视频、文本等),以支持大文件提示。涵盖文件上传、获取、生成内容、多文件处理、Google Cloud Storage 集成、删除及外部 URL 使用。通过代码示例和架构分析,帮助开发者理解 File API 的设计原理、数据流和最佳实践,并解决常见问题。
- --
内容来源与验证
- 内容等级:PREMIUM_A
- 质量等级:A
- 难度:初级
- 验证等级:V1
- 原文作者:
- 原文日期:
- 来源许可:Apache-2.0
- 来源版本:
422fead72e7709b4130e9a46803e4db3ee7ea3d7 - 查看原文
站内还有更多完整实战教程
加入会员,解锁全部教程、完整代码与持续更新内容。
加入会员