影片解讀

如要瞭解如何生成影片,請參閱 Gemini Omni Flash 指南。

Gemini 模型可以處理影片,因此開發人員能實現許多前所未有的用途,這在過去需要使用特定領域的模型。Gemini 的部分影像功能包括:描述、區隔及擷取影片資訊、回答影片內容相關問題,以及參照影片中的特定時間戳記。

你可以透過下列方式將影片提供給 Gemini:

輸入法 大小上限 建議用途
File API 20 GB (付費) / 2 GB (免費) 大型檔案 (100 MB 以上)、長影片 (10 分鐘以上)、可重複使用的檔案。
Cloud Storage 註冊 2 GB (每個檔案,無儲存空間限制) 大型檔案 (100 MB 以上)、長影片 (10 分鐘以上)、可重複使用的檔案。
內嵌資料 < 100MB 小型檔案 (小於 100 MB)、短時間 (小於 1 分鐘)、一次性輸入。
YouTube 網址 不適用 公開的 YouTube 影片。

注意:建議在大多數情況下使用 File API,尤其是檔案大小超過 100 MB,或是您想在多個要求中重複使用檔案時。

如要瞭解其他檔案輸入方法,例如使用外部網址或儲存在 Google Cloud 中的檔案,請參閱檔案輸入方法指南。

上傳影片檔案

下列程式碼會下載影片樣本、使用 Files API 上傳影片、等待處理完成,然後使用上傳的檔案參照來總結影片內容。

Python

from google import genai
import time

client = genai.Client()

myfile = client.files.upload(file="path/to/sample.mp4")

while not myfile.state or myfile.state.name != "ACTIVE":
    print("Processing video...")
    time.sleep(5)
    myfile = client.files.get(name=myfile.name)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "video", "uri": myfile.uri, "mime_type": myfile.mime_type},
        {"type": "text", "text": "Summarize this video. Then create a quiz with an answer key based on the information in this video."}
    ]
)

print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const myfile = await ai.files.upload({
    file: "path/to/sample.mp4",
    config: { mimeType: "video/mp4" },
  });

  let getFile = await ai.files.get({ name: myfile.name });
  while (getFile.state === 'PROCESSING') {
      getFile = await ai.files.get({ name: myfile.name });
      console.log(`current file status: ${getFile.state}`);
      console.log('File is still processing, retrying in 5 seconds');

      await new Promise((resolve) => {
          setTimeout(resolve, 5000);
      });
  }
  if (getFile.state === 'FAILED') {
      throw new Error('File processing failed.');
  }

  const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: [
      { type: "video", uri: myfile.uri, mime_type: myfile.mimeType },
      { type: "text", text: "Summarize this video. Then create a quiz with an answer key based on the information in this video." }
    ],
  });
  console.log(interaction.output_text);
}

await main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent = TextContent.builder().text("Summarize the key events in this video.").build();
Content videoContent =
    VideoContent.builder()
        .uri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

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" \
  -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}"

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)
file_name=$(jq -r ".file.name" file_info.json)
echo file_uri=$file_uri

echo "File uploaded successfully. File URI: ${file_uri}"

# Polling loop
echo "Waiting for file to be processed..."
while true; do
  curl -s "https://generativelanguage.googleapis.com/v1beta/${file_name}" \
    -H "x-goog-api-key: $GEMINI_API_KEY" > file_status.json
  state=$(jq -r ".state" file_status.json)
  echo "Current state: $state"
  if [ "$state" == "ACTIVE" ]; then
    break
  elif [ "$state" == "FAILED" ]; then
    echo "File processing failed."
    exit 1
  fi
  sleep 5
done

echo "Generating content from video..."
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "video", "uri": "'${file_uri}'", "mime_type": "'${MIME_TYPE}'"},
        {"type": "text", "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 ".steps[].content[0].text" response.json

如要提升詞元使用效率和效能,建議使用代理功能影片處理

如果要求總大小 (包括檔案、文字提示詞、系統指令等) 超過 20 MB、影片長度較長,或您打算在多個提示詞中使用相同影片,請一律使用 Files API。File API 可直接接受影片檔案格式。

如要進一步瞭解如何處理媒體檔案,請參閱 Files API

內嵌傳遞影片資料

您可以直接在要求中傳遞較小的影片,不必使用 File API 上傳影片檔案。這適合總要求大小小於 20 MB 的短片。

以下是提供內嵌影片資料的範例:

Python

from google import genai
import base64

video_file_name = "/path/to/your/video.mp4"
video_bytes = open(video_file_name, 'rb').read()

client = genai.Client()
interaction = client.interactions.create(
    model='gemini-3.8-flash',
    input=[
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
            "type": "video",
            "data": base64.b64encode(video_bytes).decode('utf-8'),
            "mime_type": "video/mp4"
        }
    ]
)
print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({});
const base64VideoFile = fs.readFileSync("path/to/small-sample.mp4", {
  encoding: "base64",
});

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    { type: "text", text: "Please summarize the video in 3 sentences." },
    {
      type: "video",
      data: base64VideoFile,
      mime_type: "video/mp4",
    }
  ],
});
console.log(interaction.output_text);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent = TextContent.builder().text("Summarize the key events in this video.").build();
Content videoContent =
    VideoContent.builder()
        .uri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

REST

VIDEO_PATH=/path/to/your/video.mp4

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
          "type": "video",
          "data": "'$(base64 $B64FLAGS $VIDEO_PATH)'",
          "mime_type": "video/mp4"
        }
      ]
    }' 2> /dev/null

傳送 YouTube 網址

你可以直接將 YouTube 網址傳送至 Gemini API,做為要求的一部分,如下所示:

Python

from google import genai

client = genai.Client()
interaction = client.interactions.create(
    model='gemini-3.8-flash',
    input=[
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
            "type": "video",
            "uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"
        }
    ]
)
print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    { type: "text", text: "Please summarize the video in 3 sentences." },
    {
      type: "video",
      uri: "https://www.youtube.com/watch?v=9hE5-98ZeCg",
    }
  ],
});
console.log(interaction.output_text);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent = TextContent.builder().text("Summarize the key events in this video.").build();
Content videoContent =
    VideoContent.builder()
        .uri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
          "type": "video",
          "uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"
        }
      ]
    }' 2> /dev/null

限制:

  • 免費方案每天最多只能上傳 8 小時的 YouTube 影片。
  • 付費方案則沒有影片長度限制。
  • 如果是 Gemini 2.5 之前的模型,每次要求只能上傳 1 部影片。如果是 Gemini 2.5 以上版本,每個要求最多可上傳 10 部影片。
  • 你只能上傳公開影片,無法上傳私人或不公開影片。

代理式影片解讀

影片輸入內容預設會使用靜態處理方式 (以每秒 1 個影格的速度擷取影格)。Gemini 3.8 Flash、3.7 Flash、3.6 Flash 和 3.5 Flash Lite 模型也支援代理式影片理解,模型會動態探索影片時間軸、選擇性檢查轉錄稿,並根據提示即時調整影格速率和解析度。

眾數 說明 支援的機型
靜態 (預設) 以固定速率 (1 FPS) 擷取影格,並在單一階段中將影格放入內容。適合短片。 所有 Gemini 模型
代理功能 模型會根據提示動態瀏覽影片時間軸,只載入所需的內容。在長篇內容方面,權杖效率最多可提升 88%,品質則可提升約 7%。 Gemini 3.8 Flash、3.7 Flash、3.6 Flash、3.5 Flash Lite

選擇處理模式

一般而言,建議先從代理模式開始,特別是在提升回覆品質或權杖效率時。

  • 代理:長篇影片或針對特定時刻的查詢。模型會動態瀏覽時間軸,找出與脈絡相關的資訊,不必填滿脈絡視窗。
  • 靜態:對短片 (5 分鐘以內) 執行延遲時間敏感型查詢,或需要整個短片達到影格層級精確度的情況。

注意:如果是長篇影片或複雜提示,代理程式處理需要較長時間,請使用串流 (stream=True) 或背景執行 (background=True)。這樣一來,連線會保持有效、顯示中間推理步驟,並避免連線或驗證逾時。

設定處理模式

Python

import time
from google import genai

client = genai.Client()

# Upload a long video
video_file = client.files.upload(file="path/to/lecture.mp4")

while video_file.state.name == "PROCESSING":
    time.sleep(2)
    video_file = client.files.get(name=video_file.name)

# Use agentic processing
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": video_file.uri,
            "mime_type": video_file.mime_type,
            "processing": "agentic"
        },
        {"type": "text", "text": "What are the three main arguments presented?"}
    ]
)
print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

// Upload a long video
let videoFile = await ai.files.upload({
  file: "path/to/lecture.mp4",
  config: { mimeType: "video/mp4" }
});

while (videoFile.state === "PROCESSING") {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  videoFile = await ai.files.get({ name: videoFile.name });
}

// Use agentic processing
const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: videoFile.uri,
      mime_type: videoFile.mimeType,
      processing: "agentic"
    },
    { type: "text", text: "What are the three main arguments presented?" }
  ]
});
console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${file_uri}'",
        "mime_type": "video/mp4",
        "processing": "agentic"
      },
      {"type": "text", "text": "What are the three main arguments presented?"}
    ]
  }' 2> /dev/null

注意:如要確認是否使用代理程式處理,請檢查 interaction.steps。如果出現 processing_callprocessing_result,表示模型動態瀏覽了影片。

回應步驟

代理處理會在 steps 陣列中新增兩種步驟類型:

  • processing_call:模型要求影片片段或音訊轉錄稿,以 id 識別。
  • processing_result:該負載的結果,由 call_id 連結。

這些步驟會與 thought 步驟交錯顯示 (啟用摘要時),並在最後的 model_output 步驟之前顯示。可用於在 UI 中顯示進度追蹤記錄,但不需要回應。

以下範例顯示回應酬載,其中包含交錯的處理步驟:

{
  "steps": [
    {
      "type": "thought",
      "signature": "sig_thought_1",
      "summary": [
        {
          "type": "text",
          "text": "Inspecting transcript for key discussion topics..."
        }
      ]
    },
    {
      "type": "processing_call",
      "id": "call_01",
      "signature": "sig_call_01"
    },
    {
      "type": "processing_result",
      "call_id": "call_01",
      "signature": "sig_result_01"
    },
    {
      "type": "thought",
      "signature": "sig_thought_2",
      "summary": [
        {
          "type": "text",
          "text": "Loading visual frames to verify slide content..."
        }
      ]
    },
    {
      "type": "processing_call",
      "id": "call_02",
      "signature": "sig_call_02"
    },
    {
      "type": "processing_result",
      "call_id": "call_02",
      "signature": "sig_result_02"
    },
    {
      "type": "thought",
      "signature": "sig_thought_3",
      "summary": [
        {
          "type": "text",
          "text": "Synthesizing answer from gathered evidence..."
        }
      ]
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "The three main arguments presented in the lecture are..."
        }
      ]
    }
  ]
}

在不同影片之間混合使用處理模式

您可以在同一項要求中,為每部影片設定不同的處理模式:

Python

from google import genai

client = genai.Client()

lecture = client.files.upload(file="path/to/long-lecture.mp4")
experiment = client.files.upload(file="path/to/short-experiment.mp4")

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": lecture.uri,
            "mime_type": lecture.mime_type,
            "processing": "agentic"  # Use agentic video understanding
        },
        {
            "type": "video",
            "uri": experiment.uri,
            "mime_type": experiment.mime_type,
            "processing": "static"  # Use static processing
        },
        {"type": "text", "text": "Compare the lecture content with the experiment results."}
    ]
)
print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const lecture = await ai.files.upload({
  file: "path/to/long-lecture.mp4",
  config: { mimeType: "video/mp4" }
});
const experiment = await ai.files.upload({
  file: "path/to/short-experiment.mp4",
  config: { mimeType: "video/mp4" }
});

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: lecture.uri,
      mime_type: lecture.mimeType,
      processing: "agentic" // Use agentic video understanding
    },
    {
      type: "video",
      uri: experiment.uri,
      mime_type: experiment.mimeType,
      processing: "static" // Use static processing
    },
    { type: "text", text: "Compare the lecture content with the experiment results." }
  ]
});
console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${lecture_uri}'",
        "mime_type": "video/mp4",
        "processing": "agentic"
      },
      {
        "type": "video",
        "uri": "'${experiment_uri}'",
        "mime_type": "video/mp4",
        "processing": "static"
      },
      {"type": "text", "text": "Compare the lecture content with the experiment results."}
    ]
  }' 2> /dev/null

多輪影片對話

對話期間,系統會保留影片情境。使用代理處理時:

  • 有狀態模式 (使用 previous_interaction_id):伺服器會保留影片背景資訊。不需要額外處理。
  • 無狀態模式 (使用 step_list):在無狀態模式中,回應會包含 processing_callprocessing_result 步驟,用於編碼影片內容。請務必在下一個要求中加入回覆中的所有步驟,以保留影片脈絡。step_list雖然目前省略這些參數不會傳回 API 錯誤,但系統會遺失影片脈絡,大幅降低後續問題的回覆品質。請注意,後續要求中傳送的傳回步驟會計入輸入權杖數。

參考內容中的時間戳記

你可以使用 MM:SS 格式的時間戳記,詢問影片中特定時間點的問題。

Python

prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?"

JavaScript

const prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?";

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent = TextContent.builder().text("Summarize the key events in this video.").build();
Content videoContent =
    VideoContent.builder()
        .uri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

REST

PROMPT="What are the examples given at 00:05 and 00:10 supposed to show us?"

從影片擷取詳細洞察資料

Gemini 模型可處理音訊和影像串流中的資訊,深入瞭解影片內容。這項功能可讓你擷取豐富的詳細資料,包括生成影片內容的說明,以及回答相關問題。

如果是視覺描述,模型會以 每秒 1 個影格 (FPS) 的速率對影片取樣。這個預設取樣率適用於大多數內容,但請注意,如果影片的動作快速或場景快速變化,可能就會錯過細節。

Python

prompt = "Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments."

JavaScript

const prompt = "Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments.";

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent = TextContent.builder().text("Summarize the key events in this video.").build();
Content videoContent =
    VideoContent.builder()
        .uri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

REST

PROMPT="Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments."

自訂影片處理方式

您可以設定剪輯間隔或提供自訂影格速率取樣,在 Gemini API 中自訂影片處理作業。只有在 "static" 模式下處理影片時,才能使用這些自訂選項。

設定剪輯間隔

您可以在 processing 設定物件中指定 start_offsetend_offset,剪輯影片。

Python

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": video_file.uri,
            "mime_type": video_file.mime_type,
            "processing": {
                "type": "static",
                "start_offset": 1200,
                "end_offset": 1500,
            },
        },
        {"type": "text", "text": "Summarize this section of the video."},
    ],
)
print(interaction.output_text)

JavaScript

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: videoFile.uri,
      mime_type: videoFile.mimeType,
      processing: {
        type: "static",
        start_offset: 1200,
        end_offset: 1500,
      },
    },
    { type: "text", text: "Summarize this section of the video." },
  ],
});
console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${file_uri}'",
        "mime_type": "video/mp4",
        "processing": {
          "type": "static",
          "start_offset": 1200,
          "end_offset": 1500
        }
      },
      {"type": "text", "text": "Summarize this section of the video."}
    ]
  }' 2> /dev/null

設定自訂影格率

您可以在 processing 設定物件中傳遞 fps 引數,設定自訂影格率取樣。

Python

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": video_file.uri,
            "mime_type": video_file.mime_type,
            "processing": {
                "type": "static",
                "fps": 0.5,  # Sample 1 frame every 2 seconds
            },
        },
        {"type": "text", "text": "Describe the scene changes in this video."},
    ],
)
print(interaction.output_text)

JavaScript

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: videoFile.uri,
      mime_type: videoFile.mimeType,
      processing: {
        type: "static",
        fps: 0.5, // Sample 1 frame every 2 seconds
      },
    },
    { type: "text", text: "Describe the scene changes in this video." },
  ],
});
console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${file_uri}'",
        "mime_type": "video/mp4",
        "processing": {
          "type": "static",
          "fps": 0.5
        }
      },
      {"type": "text", "text": "Describe the scene changes in this video."}
    ]
  }' 2> /dev/null

支援的影片格式

Gemini 支援下列影片格式 MIME 類型:

  • video/mp4
  • video/mpeg
  • video/mov
  • video/avi
  • video/x-flv
  • video/mpg
  • video/webm
  • video/wmv
  • video/3gpp

影片技術詳細資料

  • 支援的模型和脈絡:所有 Gemini 模型都能處理影片資料。
    • 如果模型具有 100 萬個詞元脈絡窗口,預設可處理長達 3 小時的影片 (媒體解析度較低),或長達 1 小時的影片 (媒體解析度較高)。
  • 處理模式:Gemini 3.8 Flash、3.7 Flash、3.6 Flash、3.5 Flash Lite 和後續模型支援兩種影片處理模式:
    • 靜態:以每秒 1 個影格的速度擷取影格,並放入脈絡 (所有模型的預設值)。音訊處理速度為 1 Kbps (單一聲道)。系統每秒都會新增時間戳記。最適合短片或需要逐格檢查的影片。請注意,由於取樣率為 1 FPS,快速動作序列可能會遺失細節。
    • 代理:模型會動態瀏覽影片,並視需要載入轉錄稿和/或影格和/或音訊。這項功能可減少長篇內容的詞元用量,最多可減少 88%,但由於生成內容前需要進行內部推論和工具往返,短片 (少於 5 分鐘) 的首次詞元時間 (TTFT) 可能會稍微增加。最適合長篇影片,可盡量降低權杖成本並提升回覆品質。支援 Gemini 3.8 Flash、3.7 Flash、3.6 Flash 和 3.5 Flash Lite。 詳情請參閱「代理式影片解讀」。
  • 符記計算 (靜態模式):每秒影片會依下列方式轉換為符記:
    • 個別影格 (以 1 FPS 取樣):
      • 如果將 media_resolution 設為「低」,每個影格會產生 66 個權杖。
      • 否則,每個影格會以 258 個權杖進行權杖化。
    • 音訊:每秒 32 個權杖。
    • 也包含中繼資料。
    • 總計:預設 (低) 媒體解析度下,每秒影片約 100 個權杖;高媒體解析度下,每秒影片約 300 個權杖。
  • 權杖計算 (代理模式):權杖用量取決於內容複雜度和模型的導覽策略。影片探索期間產生的導覽推論詞元會計為思考詞元 (total_thought_tokens),而根據需求載入的影格、音訊和轉錄稿則會計為工具使用詞元 (total_tool_use_tokens)。代理功能處理通常比靜態處理長篇內容時,使用的詞元總數少 88% 以上,因為模型只會載入回答提示詞所需的轉錄稿和/或影格和/或音訊 (請參閱詞元指南)。
  • 媒體解析度:Gemini 3 導入了精細控制項,可透過 media_resolution 參數精準控制多模態視覺處理程序。media_resolution 參數會決定每個輸入圖片或影片影格分配的詞元數量上限。解析度越高,模型就越能讀取細小文字或辨識細節,但也會增加權杖用量和延遲時間。media_resolutionprocessing 參數彼此獨立,因此您可以在同一個影片輸入中設定這兩者。

如要進一步瞭解如何計算權杖,請參閱權杖指南。

  • 時間戳記格式:在提示中提及影片的特定時間點時,請使用 MM:SS 格式 (例如 01:15 代表 1 分 15 秒)。
  • 文字提示詞位置:如果結合文字和單一影片,請將文字提示詞放在 input 陣列的影片部分之後
  • 長時間要求的逾時問題:如果影片需要較長的處理時間或複雜的多步驟推論,請使用串流 (stream=True) 或背景執行 (background=True)。 在高需求下,同步非串流要求可能會發生後端重試,進而超出連線或驗證權杖有效時間,導致出現非預期的 401 Unauthorized 或逾時錯誤。串流會保持連線有效,並顯示中間的推論和工具呼叫進度。

後續步驟

  • 媒體解析度:控制影片影格的解析度,以兼顧畫質和權杖用量。
  • 權杖:瞭解如何在靜態和代理處理模式中,將影片內容權杖化。
  • 系統指令: 系統指令可根據特定需求和用途,引導模型行為。
  • Files API:進一步瞭解如何上傳及管理檔案,以供 Gemini 使用。
  • 檔案提示策略:Gemini API 支援使用文字、圖片、音訊和影片資料提示,也稱為多模態提示。
  • 安全指引:有時生成式 AI 模型會產生出乎意料的輸出內容,例如不準確、有偏見或令人反感的內容。後續處理和人工評估是不可或缺的步驟,有助於降低這類輸出內容造成危害的風險。