影片解讀

如要瞭解如何生成影片,請參閱 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 網址 N/A 公開的 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 FPS 提取幀)。 Gemini 3.8 Flash、3.7 Flash、3.6 Flash 和 3.5 Flash Lite 型號還支援 智慧視訊理解,其中模型動態地探索視訊時間線,選擇性地檢查轉錄文本,並根據提示動態地自適應地調整幀速率和分辨率。

眾數 說明 支援的型號
靜態 (預設) 以固定速率(1 FPS)提取幀,並在一次處理中將它們放入上下文中。適用於短視頻片段。 所有 Gemini 型號
代理功能 該模型能夠動態瀏覽視訊時間線,並根據提示僅載入所需的內容。長篇內容的代幣效率提高高達 88%,品質提高約 7%。 Gemini 3.8 閃光燈、3.7 閃光燈、3.6 閃光燈、3.5 閃光燈 Lite

選擇處理模式

一般而言,應從 agentic 模式開始,尤其是在最佳化回應品質或令牌效率時。

  • 代理: 針對特定時刻的長影片或查詢。該模型能夠動態地瀏覽時間線,以獲取與上下文相關的信息,而不會填充上下文視窗。
  • 靜態: 對短片段(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.stepsprocessing_callprocessing_result 的存在表示模型動態地瀏覽了影片。

應對步驟

代理處理為 steps 陣列新增了兩種新的步驟類型:

  • processing_call: 此模型請求了一段視訊片段或一段音訊轉錄文本,由 id 標識。
  • processing_result:此負載的結果,由 call_id 連接。

這些步驟與 thought 步驟交錯顯示(啟用摘要時),並且位於最終的 model_output 步驟之前。它們可用於在用戶介面中顯示進度跟踪,但不需要響應。

以下範例展示了包含交錯處理步驟的回應有效載荷:

{
  "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 閃光燈、3.7 閃光燈、3.6 閃光燈和 3.5 閃光燈 Lite。 詳情請參閱Agent 影片理解
  • 符記計算 (靜態模式):每秒影片會依下列方式轉換為符記:
    • 個別影格 (以 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 或逾時錯誤。 串流保持連接活躍,並顯示中間推理和工具呼叫進度。

後續步驟

  • 媒體分辨率: 控制視訊幀的分辨率,以平衡品質和代幣使用。
  • Tokens: 瞭解影片內容在靜態和代理處理模式下是如何被標記化的。
  • 系統指令: 系統指令可根據特定需求和用途,引導模型行為。
  • 檔案 API: 瞭解更多關於上傳和管理檔案以供 Gemini 使用的資訊。
  • 檔案提示策略: Gemini API 支援使用文字、圖像、音訊和視訊資料進行提示,也稱為多模態提示。
  • 安全指引:有時生成式 AI 模型會產生出乎意料的輸出內容,例如不準確、有偏見或令人反感的內容。後期處理和人工評估對於限制此類輸出造成的危害風險至關重要。