文件输入方式
本指南介绍了在向 Gemini API 发出请求时包含图像、音频、视频和文档等媒体文件的不同方式。所有 Gemini API 端点都支持新方法,包括 Batch、Interactions 和 Live API。选择正确的方法取决于文件的大小、数据当前存储的位置以及您计划使用该文件的频率。
将文件作为输入包含的最简单方法是读取本地文件并将其包含在提示中。以下示例演示如何读取本地 PDF 文件。对于此方法,PDF 的大小限制为 50MB。请参阅 输入法对照表 有关文件输入类型和限制的完整列表。
from google import genai
from google.genai import types
import pathlib
client = genai.Client()
filepath = pathlib.Path('my_local_file.pdf')
prompt = "Summarize this document"
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
types.Part.from_bytes(
data=filepath.read_bytes(),
mime_type='application/pdf',
),
prompt
]
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
# Encode the local file to base64
B64_CONTENT=$(base64 -w 0 my_local_file.pdf)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"contents": [
{
"parts": [
{"text": "Summarize this document"}
]
},
{
"parts": [
{
"inlineData": {
"mimeType": "application/pdf",
"data": "'"${B64_CONTENT}"'"
}
}
]
}
]
}'
输入法比较 #
下表比较了每种输入方法的文件限制和最佳用例。请注意,文件大小限制可能会有所不同,具体取决于文件类型和用于处理文件的模型/标记器。
方法 | 最适合 | 最大文件大小 | 坚持 |
|---|---|---|---|
内联数据 | 快速测试、小文件、实时应用。 | 100 MB 每个请求/有效负载 (50 MB 用于 PDF) | 无(随每个请求一起发送) |
文件API上传 | 大文件,多次使用的文件。 | 2 每个文件 GB,每个项目最多 20 GB | 48 小时 |
文件 API GCS URI 注册 | Google Cloud 存储中已有大文件,文件被多次使用。 | 2 每个文件 GB,没有总体存储限制 | 无(根据请求获取)。一次注册最多可授予 30 天的访问权限。 |
外部网址 | 公共数据或云存储桶(AWS、Azure、GCS)中的数据,无需重新上传。 | 15 每个文件 MB | 无(根据请求获取) |
内联数据 #
对于较小的文件(小于 100MB,PDF 小于 50MB),您可以直接在请求负载中传递数据。这是快速测试或处理实时瞬态数据的应用程序的最简单方法。您可以以 Base64 编码字符串的形式提供数据,也可以直接读取本地文件来提供数据。
有关从本地文件读取的示例,请参阅本页开头的示例。
从 URL 获取 #
您还可以从 URL 获取文件,将其转换为字节,并将其包含在输入中。
from google import genai
from google.genai import types
import httpx
client = genai.Client()
doc_url = "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
doc_data = httpx.get(doc_url).content
prompt = "Summarize this document"
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[
types.Part.from_bytes(
data=doc_data,
mime_type='application/pdf',
),
prompt
]
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const docUrl = 'https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf';
const prompt = "Summarize this document";
async function main() {
const pdfResp = await fetch(docUrl)
.then((response) => response.arrayBuffer());
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: Buffer.from(pdfResp).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
DOC_URL="https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
PROMPT="Summarize this document"
DISPLAY_NAME="base64_pdf"
# Download the PDF
wget -O "${DISPLAY_NAME}.pdf" "${DOC_URL}"
# Check for FreeBSD base64 and set flags accordingly
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
B64FLAGS="--input"
else
B64FLAGS="-w0"
fi
# Base64 encode the PDF
ENCODED_PDF=$(base64 $B64FLAGS "${DISPLAY_NAME}.pdf")
# Generate content using the base64 encoded PDF
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"inline_data": {"mime_type": "application/pdf", "data": "'"$ENCODED_PDF"'"}},
{"text": "'$PROMPT'"}
]
}]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".candidates[].content.parts[].text" response.json
Gemini File API #
文件 API 专为较大文件(最多 2GB)或打算在多个请求中使用的文件而设计。
标准文件上传 #
将本地文件上传到Gemini API。通过这种方式上传的文件将被临时存储(48 小时)并进行处理,以便模型进行有效检索。
from google import genai
client = genai.Client()
# Upload the file
audio_file = client.files.upload(file="path/to/your/sample.mp3")
prompt = "Describe this audio clip"
# Use the uploaded file in a prompt
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=[prompt, audio_file]
)
print(response.text)
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = "Describe this audio clip";
async function main() {
const filePath = "path/to/your/sample.mp3"; // Adjust path as needed
const myfile = await ai.files.upload({
file: filePath,
config: { mimeType: "audio/mpeg" },
});
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: createUserContent([
prompt,
createPartFromUri(myfile.uri, myfile.mimeType),
]),
});
console.log(response.text);
}
await main();
AUDIO_PATH="path/to/sample.mp3"
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO
tmp_header_file=upload-header.tmp
# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-D "${tmp_header_file}" \
-H "X-Goog-Upload-Protocol: resumable" \
-H "X-Goog-Upload-Command: start" \
-H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
-H "Content-Type: application/json" \
-d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null
upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"
# Upload the actual bytes.
curl "${upload_url}" \
-H "Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Offset: 0" \
-H "X-Goog-Upload-Command: upload, finalize" \
--data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri
# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"text": "Describe this audio clip"},
{"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
}]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".candidates[].content.parts[].text" response.json
注册Google Cloud存储文件 #
如果您的数据已在 Google Cloud 存储中,则无需下载并重新上传。您可以直接使用文件 API 进行注册。
格兰特 服务智能体 访问每个存储桶
在 Google Cloud 项目中启用 Gemini API。
创建服务智能体:
gcloud beta services identity create --service=generativelanguage.googleapis.com --project=<your_project>
- 授予Gemini API服务智能体权限 读取您的存储桶。
用户需要分配 Storage Object Viewer IAM 角色 他们打算使用的特定存储桶上的此服务智能体。
默认情况下,此访问权限不会过期,但可以随时更改。您还可以使用 Google Cloud 存储 IAM SDK 授予权限的命令。
- 验证您的服务
前提条件
- 启用 API
- 创建具有适当权限的服务帐户/智能体。
您首先需要验证为具有存储对象查看器权限的服务。如何发生这种情况取决于文件管理代码运行的环境。
Google Cloud 之外
如果您的代码在 Google Cloud 外部(例如您的桌面)运行,请按照以下步骤从 Google Cloud 控制台下载帐户凭据:
- 浏览至 服务帐户控制台
- 选择相关服务帐号
- 选择 按键 选项卡并选择 添加密钥、创建新密钥
- 选择 JSON 密钥类型,并记下文件下载到您计算机上的位置。
有关更多详细信息,请参阅 Google Cloud 官方文档 服务帐户密钥管理.
然后使用以下命令进行身份验证。这些命令假设您的服务帐户文件位于当前目录中,名为 service-account.json.
from google.oauth2.service_account import Credentials
GCS_READ_SCOPES = [
'https://www.googleapis.com/auth/devstorage.read_only',
'https://www.googleapis.com/auth/cloud-platform'
]
SERVICE_ACCOUNT_FILE = 'service-account.json'
credentials = Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,
scopes=GCS_READ_SCOPES
)
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
关于Google Cloud
如果您直接在 Google Cloud 中运行,例如使用 云运行功能 或一个 计算引擎实例,您将拥有隐式凭据,但需要重新进行身份验证才能授予适当的范围。
此代码期望该服务在以下环境中运行 应用程序默认凭据 可以自动获取,例如Cloud Run或Compute Engine。
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
此代码期望该服务在以下环境中运行 应用程序默认凭据 可以自动获取,例如Cloud Run或Compute Engine。
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
这是一个交互式命令。对于像 Compute Engine 这样的服务,您可以在配置级别将范围附加到正在运行的服务。请参阅 用户管理的服务文档 举个例子。
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
- 文件注册(Files API)
使用Files API注册文件并生成可直接在Gemini API中使用的Files API路径。
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
外部 HTTP/签名 URL #
您可以传递可公开访问的 HTTPS URL 或预签名 URL(与 S3 预签名 URL 和 Azure SAS)直接在您的生成请求中。 Gemini API 将在处理过程中安全地获取内容。这对于您不想重新上传的文件来说是理想的选择。每个文件最大可达 15 MB。对于较大的文件,请使用 文件 API.
您可以使用公共或签名 URL 作为输入,方法是使用 file_uri 场。
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
import { GoogleGenAI } from "@google/genai";
import * as fs from 'node:fs';
const ai = new GoogleGenAI({});
const prompt = "Summarize this document";
async function main() {
const filePath = path.join('content', 'my_local_file.pdf'); // Adjust path as needed
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: 'application/pdf',
data: fs.readFileSync(filePath).toString("base64")
}
}
];
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: contents
});
console.log(response.text);
}
await main();
无障碍 #
验证您提供的网址不会指向需要登录或位于付费专区后面的页面。对于私有数据库,请确保您创建具有正确访问权限和到期时间的签名 URL。
安全检查 #
系统对 URL 执行内容审核检查,以确认它们符合安全和政策标准(例如非选择退出和付费内容)。如果您提供的 URL 未通过此检查,您将得到一个 url_retrieval_status 的 URL_RETRIEVAL_STATUS_UNSAFE.
支持的内容类型 #
此支持的文件类型和限制列表旨在作为初步指导,并不全面。支持的有效类型集可能会发生变化,并且可能会根据所使用的特定模型和分词器版本而有所不同。不支持的类型将导致错误。此外,这些文件类型的内容检索当前仅支持可公开访问的 URL。
文本文件类型 #
text/htmltext/csstext/plaintext/xmltext/csvtext/rtftext/javascript
应用程序文件类型 #
application/jsonapplication/pdf
图像文件类型 #
image/bmpimage/jpegimage/pngimage/webp
音频文件类型 #
audio/wavaudio/mp3audio/aiffaudio/aacaudio/oggaudio/flacaudio/mpegaudio/m4aaudio/l16audio/opusaudio/alawaudio/mulawaudio/webm
视频文件类型 #
video/mp4video/mpegvideo/quicktimevideo/avivideo/x-flvvideo/mpgvideo/webmvideo/wmvvideo/3gpp
最佳实践 #
选择正确的方法: 对小型瞬态文件使用内联数据。对于较大或经常使用的文件,请使用文件 API。对已在线托管的数据使用外部 URL。
指定 MIME 类型: 始终为文件数据提供正确的 MIME 类型,以确保正确处理。
处理错误: 在代码中实施错误处理,以管理网络故障、文件访问问题或 API 错误等潜在问题。
管理 GCS 权限: 使用 GCS 注册时,仅向 Gemini API 服务智能体授予必要的权限
Storage Object Viewer在特定存储桶上的角色。签名 URL 安全性: 确保签名 URL 具有适当的过期时间和有限的权限。
限制 #
文件大小限制因方法而异(请参阅 对照表)和文件类型。
内联数据会增加请求负载大小。
文件 API 上传是临时的,在 48 小时后过期。
每个文件的外部 URL 获取限制为 15 MB,并支持特定内容类型。
Google Cloud 存储注册需要正确的 IAM 设置和 OAuth token 管理。
后续步骤 #
尝试使用以下命令编写您自己的多模态提示 Google AI Studio.
有关提示设计的更多指导,例如调整采样参数,请参阅 即时策略 指导。