Gemini 模型可以处理视频,从而支持许多先进的开发者用例,而这些用例在过去需要使用特定领域的模型。Gemini 的部分视觉功能包括:
- 对时长最长 90 分钟的视频进行描述、细分和信息提取
- 回答与视频内容相关的问题
- 提及视频中的特定时间戳
Gemini 从一开始就具有多模态特性,我们将继续突破可能的边界。本指南介绍了如何使用 Gemini API 根据视频输入生成文本回答。
准备工作
在调用 Gemini API 之前,请确保您已安装所选的 SDK,并已配置好 Gemini API 密钥,可以使用。
视频输入
您可以通过以下方式将视频作为输入提供给 Gemini:
- 使用 File API 上传视频文件,然后向
generateContent
发出请求。对于大于 20MB 的文件、时长超过大约 1 分钟的视频,或者您想在多个请求中重复使用文件时,请使用此方法。 - 将请求中的内嵌视频数据传递给
generateContent
。适用于文件较小(小于 20 MB)且时长较短的视频。 - 直接在问题中添加 YouTube 网址。
上传视频文件
您可以使用 Files API 上传视频文件。如果请求总大小(包括文件、文本提示、系统说明等)超过 20 MB、视频时长较长,或者您打算在多个提示中使用同一视频,请始终使用 Files API。
File API 直接接受视频文件格式。此示例使用了 “木星的大红斑缩小和变大”这部短片。图片来源:戈达德太空飞行中心 (GSFC)/David Ladd(2018 年)。
“Jupiter's Great Red Spot Shrinks and Grows”(木星的大红斑缩小和扩大)属于公共领域,且未显示可识别身份的人物。(NASA 图片和媒体使用指南。)
以下代码会下载示例视频,使用 File API 上传该视频,等待处理完成,然后在 generateContent
请求中使用文件引用。
Python
from google import genai
client = genai.Client(api_key="GOOGLE_API_KEY")
myfile = client.files.upload(file="path/to/sample.mp4")
response = client.models.generate_content(
model="gemini-2.0-flash", contents=[myfile, "Summarize this video. Then create a quiz with an answer key based on the information in this video."]
)
print(response.text)
JavaScript
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
async function main() {
const myfile = await ai.files.upload({
file: "path/to/sample.mp4",
config: { mimeType: "video/mp4" },
});
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: createUserContent([
createPartFromUri(myfile.uri, myfile.mimeType),
"Summarize this video. Then create a quiz with an answer key based on the information in this video.",
]),
});
console.log(response.text);
}
await main();
Go
file, err := client.UploadFileFromPath(ctx, "path/to/sample.mp4", nil)
if err != nil {
log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
genai.FileData{URI: file.URI},
genai.Text("Summarize this video. Then create a quiz with an answer key based on the information in this video."))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
REST
VIDEO_PATH="path/to/sample.mp4"
MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO
tmp_header_file=upload-header.tmp
echo "Starting file upload..."
curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GOOGLE_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}"
echo "Uploading video data..."
curl "${upload_url}" \
-H "Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Offset: 0" \
-H "X-Goog-Upload-Command: upload, finalize" \
--data-binary "@${VIDEO_PATH}" 2> /dev/null > file_info.json
file_uri=$(jq -r ".file.uri" file_info.json)
echo file_uri=$file_uri
echo "File uploaded successfully. File URI: ${file_uri}"
# --- 3. Generate content using the uploaded video file ---
echo "Generating content from video..."
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"file_data":{"mime_type": "'"${MIME_TYPE}"'", "file_uri": "'"${file_uri}"'"}},
{"text": "Summarize this video. Then create a quiz with an answer key based on the information in this video."}]
}]
}' 2> /dev/null > response.json
jq -r ".candidates[].content.parts[].text" response.json
如需详细了解如何处理媒体文件,请参阅 Files API。
以内嵌方式传递视频数据
您可以直接在请求中将较小的视频传递给 generateContent
,而无需使用 File API 上传视频文件。这适用于总请求大小小于 20MB 的较短视频。
下面是一个提供内嵌视频数据的示例:
Python
# Only for videos of size <20Mb
video_file_name = "/path/to/your/video.mp4"
video_bytes = open(video_file_name, 'rb').read()
response = client.models.generate_content(
model='models/gemini-2.0-flash',
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(data=video_bytes, mime_type='video/mp4')
),
types.Part(text='Please summarize the video in 3 sentences.')
]
)
)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const base64VideoFile = fs.readFileSync("path/to/small-sample.mp4", {
encoding: "base64",
});
const contents = [
{
inlineData: {
mimeType: "video/mp4",
data: base64VideoFile,
},
},
{ text: "Please summarize the video in 3 sentences." }
];
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: contents,
});
console.log(response.text);
REST
VIDEO_PATH=/path/to/your/video.mp4
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
B64FLAGS="--input"
else
B64FLAGS="-w0"
fi
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{
"inline_data": {
"mime_type":"video/mp4",
"data": "'$(base64 $B64FLAGS $VIDEO_PATH)'"
}
},
{"text": "Please summarize the video in 3 sentences."}
]
}]
}' 2> /dev/null
添加 YouTube 网址
Gemini API 和 AI Studio 支持将 YouTube 网址作为文件数据 Part
。您可以添加 YouTube 网址,并附上提示,要求模型总结、翻译或以其他方式与视频内容互动。
限制:
- 您每天上传的 YouTube 视频时长不得超过 8 小时。
- 每次申请只能上传 1 个视频。
- 您只能上传公开视频(而非私享视频或不公开列出的视频)。
以下示例展示了如何在提示中添加 YouTube 网址:
Python
response = client.models.generate_content(
model='models/gemini-2.0-flash',
contents=types.Content(
parts=[
types.Part(
file_data=types.FileData(file_uri='https://www.youtube.com/watch?v=9hE5-98ZeCg')
),
types.Part(text='Please summarize the video in 3 sentences.')
]
)
)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });
const result = await model.generateContent([
"Please summarize the video in 3 sentences.",
{
fileData: {
fileUri: "https://www.youtube.com/watch?v=9hE5-98ZeCg",
},
},
]);
console.log(result.response.text());
Go
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GOOGLE_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
genai.FileData{URI: "https://www.youtube.com/watch?v=9hE5-98ZeCg"},
genai.Text("Please summarize the video in 3 sentences."))
if err != nil {
log.Fatal(err)
}
// Handle the response of generated text.
for _, c := range resp.Candidates {
if c.Content != nil {
fmt.Println(*c.Content)
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"text": "Please summarize the video in 3 sentences."},
{
"file_data": {
"file_uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"
}
}
]
}]
}' 2> /dev/null
提及内容中的时间戳
您可以使用格式为 MM:SS
的时间戳,询问视频中特定时间点的内容。
Python
prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?" # Adjusted timestamps for the NASA video
JavaScript
const prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?";
Go
prompt := []genai.Part{
genai.FileData{URI: currentVideoFile.URI, MIMEType: currentVideoFile.MIMEType},
// Adjusted timestamps for the NASA video
genai.Text("What are the examples given at 00:05 and " +
"00:10 supposed to show us?"),
}
REST
PROMPT="What are the examples given at 00:05 and 00:10 supposed to show us?"
转写视频并提供视觉描述
Gemini 模型可以同时处理音轨和视频帧,从而为视频内容转写并提供视觉描述。对于视频描述,模型以 1 帧/秒 的速率对视频进行采样。此采样率可能会影响说明的详细程度,尤其是对于画面快速变化的视频。
Python
prompt = "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."
JavaScript
const prompt = "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions.";
Go
prompt := []genai.Part{
genai.FileData{URI: currentVideoFile.URI, MIMEType: currentVideoFile.MIMEType},
genai.Text("Transcribe the audio from this video, giving timestamps for salient events in the video. Also " +
"provide visual descriptions."),
}
REST
PROMPT="Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."
支持的视频格式
Gemini 支持以下视频格式 MIME 类型:
video/mp4
video/mpeg
video/mov
video/avi
video/x-flv
video/mpg
video/webm
video/wmv
video/3gpp
视频的技术详情
- 支持的模型和上下文:所有 Gemini 2.0 和 2.5 模型都可以处理视频数据。
- 上下文窗口为 200 万个词元的模型可以处理长达 2 小时的视频,上下文窗口为 100 万个词元的模型可以处理长达 1 小时的视频。
- File API 处理:使用 File API 时,系统会以每秒 1 帧 (FPS) 的速率对视频进行采样,并以 1 Kbps(单声道)的速率处理音频。系统每秒都会添加时间戳。
- 这些费率将来可能会发生变化,以便改进推理功能。
- 令牌计算:系统会按如下方式对视频的每一秒进行令牌化:
- 单个帧(以 1 FPS 的速率采样):每个帧 258 个令牌。
- 音频:每秒 32 个令牌。
- 还包含元数据。
- 总计:每秒视频约 300 个令牌。
- 时间戳格式:在问题中提及视频中的特定时间点时,请使用
MM:SS
格式(例如,01:15
表示 1 分 15 秒)。 - 最佳实践:
- 每个问题请求仅使用一个视频,以获得最佳结果。
- 如果将文本与单个视频组合使用,请将文本提示放在
contents
数组中的视频部分后面。 - 请注意,由于采样率为 1 FPS,因此快速动作序列可能会丢失细节。如有必要,请考虑放慢此类剪辑的速度。
后续步骤
本指南介绍了如何上传视频文件,以及如何根据视频输入生成文本输出。如需了解详情,请参阅以下资源: