影片解讀

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

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

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

輸入法 大小上限 建議用途
檔案 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 com.google.genai.types.File;
import com.google.genai.types.FileState;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

File myfile =
    client.files.upload(
        "path/to/sample.mp4", UploadFileConfig.builder().mimeType("video/mp4").build());

while (!myfile.state().isPresent()
    || myfile.state().get().knownEnum() != FileState.Known.ACTIVE) {
  System.out.println("Processing video...");
  Thread.sleep(5000);
  myfile = client.files.get(myfile.name().get(), null);
}

Content videoContent =
    VideoContent.builder()
        .uri(myfile.uri().get())
        .mimeType(VideoContentMimeType.of(myfile.mimeType().get()))
        .build();
Content textContent =
    TextContent.builder()
        .text(
            "Summarize this video. Then create a quiz with an answer key based on the information in this video.")
        .build();

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

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(""));

Go

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    myfile, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp4", &genai.UploadFileConfig{
        MIMEType: "video/mp4",
    })
    if err != nil {
        log.Fatal(err)
    }

    for myfile.State != genai.FileStateActive {
        fmt.Println("Processing video...")
        time.Sleep(5 * time.Second)
        myfile, err = client.Files.Get(ctx, myfile.Name, nil)
        if err != nil {
            log.Fatal(err)
        }
    }

    contents := []interactions.Content{
        interactions.NewContent(interactions.VideoContent{
            URI:      genai.Ptr(myfile.URI),
            MimeType: interactions.VideoContentMimeType(myfile.MIMEType).ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: "Summarize this video. Then create a quiz with an answer key based on the information in this video.",
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

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.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

String videoFileName = "/path/to/your/video.mp4";
byte[] videoBytes = Files.readAllBytes(Paths.get(videoFileName));
String base64Video = Base64.getEncoder().encodeToString(videoBytes);

Client client = new Client();

Content textContent =
    TextContent.builder().text("Please summarize the video in 3 sentences.").build();
Content videoContent =
    VideoContent.builder()
        .data(base64Video)
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List 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(""));

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    videoFileName := "/path/to/your/video.mp4"
    videoBytes, err := os.ReadFile(videoFileName)
    if err != nil {
        log.Fatal(err)
    }
    base64Video := base64.StdEncoding.EncodeToString(videoBytes)

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: "Please summarize the video in 3 sentences.",
        }),
        interactions.NewContent(interactions.VideoContent{
            Data:     genai.Ptr(base64Video),
            MimeType: interactions.VideoContentMimeTypeVideoMp4.ToPointer(),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

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.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent =
    TextContent.builder().text("Please summarize the video in 3 sentences.").build();
Content videoContent =
    VideoContent.builder()
        .uri("https://www.youtube.com/watch?v=9hE5-98ZeCg")
        .build();

List 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(""));

Go

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: "Please summarize the video in 3 sentences.",
        }),
        interactions.NewContent(interactions.VideoContent{
            URI: genai.Ptr("https://www.youtube.com/watch?v=9hE5-98ZeCg"),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

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)。 這樣一來,連線就會保持有效、顯示中間的推理步驟,並避免連線或驗證逾時。

設定處理模式

如要使用代理式影片解讀功能,請在 input 陣列中,將影片部分的 "processing": "agentic" 設為。

如果影片較長,代理式影片處理作業可能需要較長時間,因為模型會執行多次檢查,以瀏覽時間軸。為避免網路連線中斷時遺失進度,這個範例會使用 background=True 在伺服器上以非同步方式執行工作。您也可以省略 background 參數,以同步方式執行要求,而不需在背景執行,這很適合較短的影片。

如要進一步瞭解輪詢、擷取結果及管理背景工作,請參閱背景執行指南。

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 with background execution
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?"}
    ],
    background=True,
)

while interaction.status == "in_progress":
    time.sleep(5)
    interaction = client.interactions.get(interaction.id)

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 with background execution
let 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?" }
  ],
  background: true,
});

while (interaction.status === "in_progress") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  interaction = await ai.interactions.get(interaction.id);
}

console.log(interaction.output_text);

REST

# 1. Start the interaction in the background
interaction=$(curl -s -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?"}
    ],
    "background": true
  }')

id=$(echo "$interaction" | jq -r '.id')

# 2. Poll until the interaction finishes
while [ "$(echo "$interaction" | jq -r '.status')" = "in_progress" ]; do
  sleep 5
  interaction=$(curl -s "https://generativelanguage.googleapis.com/v1beta/interactions/$id" \
    -H "x-goog-api-key: $GEMINI_API_KEY")
done

echo "$interaction" | jq '.'

注意:如要確認是否使用代理程式處理,請檢查 interaction.steps。如果出現 processing_call 和 processing_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

import time
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")

# Use agentic processing with background execution
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."}
    ],
    background=True,
)

while interaction.status == "in_progress":
    time.sleep(5)
    interaction = client.interactions.get(interaction.id)

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" }
});

// Use agentic processing with background execution
let 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." }
  ],
  background: true,
});

while (interaction.status === "in_progress") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  interaction = await ai.interactions.get(interaction.id);
}

console.log(interaction.output_text);

REST

# 1. Start the interaction in the background
interaction=$(curl -s -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."}
    ],
    "background": true
  }')

id=$(echo "$interaction" | jq -r '.id')

# 2. Poll until the interaction finishes
while [ "$(echo "$interaction" | jq -r '.status')" = "in_progress" ]; do
  sleep 5
  interaction=$(curl -s "https://generativelanguage.googleapis.com/v1beta/interactions/$id" \
    -H "x-goog-api-key: $GEMINI_API_KEY")
done

echo "$interaction" | jq '.'

多輪影片對話

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

  • 有狀態模式 (使用 previous_interaction_id):伺服器會保留影片內容。無須採取其他行動。
  • 無狀態模式 (使用 step_list):在無狀態模式下,回應會包含 processing_call 和 processing_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

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

Go

prompt := "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 個影格 (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

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

Go

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

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_offset 和 end_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 FPS 擷取影格並放入脈絡 (所有模型預設)。音訊處理速度為 1 Kbps (單一聲道)。 系統每秒都會新增時間戳記。最適合短片,或需要檢查每個影格時 (例如逐格檢查)。請注意,由於取樣率為每秒 1 格,快速動作序列可能會遺失細節。
    • 代理:模型會動態瀏覽影片,並視需要載入轉錄稿和/或影格和/或音訊。這項功能可減少長篇內容的詞元用量,最多可減少 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_resolution 和 processing 參數彼此獨立,因此您可以在同一個影片輸入中設定這兩者。

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

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

後續步驟

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