درک ویدیو

برای آشنایی با تولید ویدیو، راهنمای Gemini Omni Flash را ببینید.

مدل‌های Gemini می‌توانند ویدیوها را پردازش کنند و امکان استفاده از موارد کاربرد توسعه‌دهندگان پیشرو را فراهم کنند که در گذشته نیازمند مدل‌های خاص دامنه بودند. برخی‌از قابلیت‌های دیداری Gemini عبارت‌اند از: توانایی توصیف، بخش‌بندی، و استخراج اطلاعات از ویدیوها، پاسخ به سؤالات درباره محتوای ویدیو، و ارجاع به مُهرهای زمانی خاص در یک ویدیو.

می‌توانید به روش‌های زیر ویدیو را به‌عنوان ورودی به Gemini ارائه دهید:

روش ورودی حداکثر اندازه مورد استفاده توصیه‌شده
File API ‫۲۰ گیگابایت (پولی) / ۲ گیگابایت (رایگان) فایل‌های بزرگ (۱۰۰ مگابایت+)، ویدیوهای طولانی (۱۰ دقیقه+)، فایل‌های قابل استفاده مجدد.
ثبت Cloud Storage ‫۲ گیگابایت (برای هر فایل، بدون محدودیت فضای ذخیره‌سازی) فایل‌های بزرگ (بیش‌از ۱۰۰ مگابایت)، ویدیوهای طولانی (بیش‌از ۱۰ دقیقه)، فایل‌های ماندگار و قابل‌استفاده مجدد.
داده‌های درون‌خطی ‫< ۱۰۰ مگابایت فایل‌های کوچک (<۱۰۰ مگابایت)، مدت کوتاه (<۱ دقیقه)، ورودی‌های یک‌باره.
نشانی‌های وب YouTube موجود نیست ویدیوهای عمومی YouTube.

توجه: File API برای اکثر موارد استفاده، به‌ویژه برای فایل‌های بزرگ‌تر از ۱۰۰ مگابایت یا زمانی که می‌خواهید از فایل در چندین درخواست استفاده مجدد کنید، توصیه می‌شود.

برای آشنایی با روش‌های دیگر ورودی فایل، مثل استفاده از نشانی‌های وب خارجی یا فایل‌های ذخیره‌شده در 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();

جاوا

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

رفتن

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

برای بهینه‌سازی کارایی و عملکرد نشان، از پردازش ویدیو عامل استفاده کنید.

همیشه وقتی اندازه کل درخواست (شامل فایل، پیام‌واره نوشتاری، دستورالعمل‌های سیستم، و غیره) بزرگ‌تر از ۲۰ مگابایت است، مدت ویدیو قابل‌توجه است، یا اگر قصد دارید از ویدیو یکسانی در پیام‌واره‌های متعددی استفاده کنید، از «میانای برنامه‌سازی کاربردی فایل‌ها» استفاده کنید. «میانای برنامه‌سازی کاربردی فایل» قالب‌های فایل ویدیویی را مستقیماً می‌پذیرد.

برای کسب اطلاعات بیشتر درباره کار با فایل‌های رسانه‌ای، Files API را ببینید.

انتقال داده‌های ویدیو به‌صورت درون‌خطی

به‌جای بارگذاری فایل ویدیو بااستفاده از «میانای برنامه‌سازی کاربردی فایل»، می‌توانید ویدیوهای کوچک‌تر را مستقیماً در درخواست ارسال کنید. این برای ویدیوهای کوتاه‌تر با اندازه کل درخواست کمتر از ۲۰ مگابایت مناسب است.

در اینجا نمونه‌ای از ارائه داده‌های ویدیو درون‌خطی آورده شده است:

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

جاوا

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

رفتن

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

جاوا

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

رفتن

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

محدودیت‌ها:

  • برای سطح رایگان، نمی‌توانید بیش از ۸ ساعت ویدیو YouTube در روز بارگذاری کنید.
  • برای سطح پولی، هیچ محدودیتی براساس طول ویدیو وجود ندارد.
  • برای مدل‌های قبل‌از Gemini 2.5، فقط می‌توانید ۱ ویدیو در هر درخواست بارگذاری کنید. برای Gemini 2.5 و مدل‌های جدیدتر، می‌توانید حداکثر ۱۰ ویدیو در هر درخواست بارگذاری کنید.
  • فقط می‌توانید ویدیوهای عمومی (نه ویدیوهای خصوصی یا فهرست‌نشده) را بارگذاری کنید.

درک عامل‌گرایانه ویدیو

به‌طور پیش‌فرض، ورودی‌های ویدیو از پردازش ایستا (استخراج قاب‌ها با نرخ ۱ فریم در ثانیه) استفاده می‌کنند. مدل‌های Gemini 3.8 Flash،‏ 3.6 Flash، و 3.5 Flash Lite نیز از درک ویدیویی عامل‌محور پشتیبانی می‌کنند، که در آن مدل به‌صورت پویا جدول زمانی ویدیو را کاوش می‌کند، ترانویسی‌ها را به‌صورت انتخابی بازرسی می‌کند، و نرخ فریم و وضوح را براساس پیام‌واره به‌صورت تطبیقی تنظیم می‌کند.

حالت شرح مدل‌های پشتیبانی‌شده
ایستا (پیش‌فرض) قاب‌ها را با نرخ ثابت (۱ قاب در ثانیه) استخراج می‌کند و آن‌ها را در یک گذر در بافت قرار می‌دهد. برای کلیپ‌های کوتاه خوب کار می‌کند. همه مدل‌های Gemini
Agentic این مدل به‌صورت پویا در خط زمان ویدیو پیمایش می‌کند و فقط محتوایی را که براساس پیام‌واره نیاز دارد بار می‌کند. تا ۸۸٪ کارآمدتر ازنظر تعداد نشان و ~۷٪ کیفیت بالاتر در محتوای بلند. Gemini 3.8 Flash،‏ 3.6 Flash،‏ 3.5 Flash Lite

انتخاب حالت پردازش

به‌عنوان یک دستورالعمل کلی، با حالت عامل‌گرا شروع کنید، به‌ویژه هنگام بهینه‌سازی برای کیفیت پاسخ یا کارایی داده‌واحد (توکن).

  • عامل‌دار: ویدیوهای طولانی یا پُرسمان‌هایی که لحظات خاصی را هدف‌یابی می‌کنند. این مدل به‌صورت پویا در جدول زمانی پیمایش می‌کند تا اطلاعات مرتبط با بافت را بدون پر کردن پنجره زمینه‌ای هدف‌یابی کند.
  • ایستا: پُرسمان‌های حساس به تأخیر در کلیپ‌های کوتاه (زیر ۵ دقیقه)، یا مواردی که دقت سطح قاب در کل کلیپ موردنیاز است.

توجه: برای ویدیوهای طولانی یا پیام‌واره‌های پیچیده که پردازش عامل‌محور زمان بیشتری می‌برد، از جاری‌سازی (stream=True) یا اجرای پس‌زمینه (background=True) استفاده کنید. این کار اتصال را فعال نگه می‌دارد، مراحل استدلال میانی را نشان می‌دهد، و از اتمام زمان اتصال یا اصالت‌سنجی جلوگیری می‌کند.

حالت پردازش را تنظیم کنید

برای استفاده از درک ویدیو عامل‌دار، "processing": "agentic" را در بخش ویدیو در آرایه input تنظیم کنید.

پردازش ویدیو با عامل هوش مصنوعی در ویدیوهای طولانی ممکن است بیشتر طول بکشد زیرا مدل چندین گذر بازرسی را برای پیمایش در خط زمان انجام می‌دهد. برای جلوگیری از ازدست رفتن پیشرفت درصورت قطع اتصال شبکه، این مثال از 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 قرار می‌گیرند. از آن‌ها می‌توان برای نمایش رد پیشرفت در واسط کاربر استفاده کرد اما نیازی به پاسخ ندارند.

مثال زیر بار پاسخ را با مراحل پردازش درهم‌تنیده نشان می‌دهد:

{
  "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?";

جاوا

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

رفتن

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 با پردازش اطلاعات از هر دو جاری‌سازی صوتی و تصویری، قابلیت‌های قدرتمندی برای درک محتوای ویدیو ارائه می‌دهند. این ویژگی به شما امکان می‌دهد مجموعه کاملی از جزئیات را استخراج کنید، ازجمله تولید شرحی از آنچه در ویدیو اتفاق می‌افتد و پاسخ دادن به سؤالات درباره محتوای آن.

برای شرح‌های تصویری، مدل ویدیو را با نرخ ۱ فریم در ثانیه (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.";

جاوا

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

رفتن

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" پشتیبانی می‌شوند.

تنظیم فواصل برش

می‌توانید با مشخص کردن start_offset و end_offset در شیء پیکربندی processing، ویدیو را برش دهید.

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

تنظیم نرخ فریم سفارشی

می‌توانید با ارسال آرگومان fps در شیء پیکربندی processing، نمونه‌برداری نرخ فریم سفارشی تنظیم کنید.

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 می‌توانند داده‌های ویدیو را پردازش کنند.
    • مدل‌های دارای پنجره بافت ۱ میلیون داده‌واحدی می‌توانند ویدیوهای حداکثر ۳ ساعته را به‌طور پیش‌فرض (با وضوح پایین رسانه) یا ویدیوهای حداکثر ۱ ساعته را با وضوح بالای رسانه پردازش کنند.
  • حالت‌های پردازش: Gemini 3.8 Flash،‏ 3.6 Flash،‏ 3.5 Flash Lite، و مدل‌های جدیدتر از دو حالت پردازش ویدیو پشتیبانی می‌کنند:
    • ایستا: قاب‌ها با نرخ ۱ فریم در ثانیه استخراج می‌شوند و در بافت قرار می‌گیرند (پیش‌فرض برای همه مدل‌ها). صدا با سرعت ۱ کیلوبیت در ثانیه (تک‌کاناله) پردازش می‌شود. مُهرهای زمان هر ثانیه اضافه می‌شوند. بهترین برای کلیپ‌های کوتاه یا زمانی که هر قاب اهمیت دارد (مانند بازرسی قاب‌به‌قاب). توجه داشته باشید که توالی‌های کنش سریع ممکن است به‌دلیل نرخ نمونه‌برداری ۱ فریم در ثانیه جزئیات را ازدست بدهند.
    • عامل‌محور: مدل به‌صورت پویا در ویدیو پیمایش می‌کند و ترانویسی و/یا قاب‌ها و/یا صدا را به‌درخواست بار می‌کند. این مدل برای محتوای طولانی تا ۸۸٪ کمتر از نشان‌ها استفاده می‌کند، هرچند ممکن است به‌دلیل استدلال داخلی و رفت‌وبرگشت‌های ابزار قبل‌از شروع تولید، پیمایش در کلیپ‌های کوتاه (<۵ دقیقه) کمی «زمان تا اولین نشان» (TTFT) را افزایش دهد. بهترین برای ویدیوهای طولانی برای بهینه‌سازی هزینه‌های داده‌واحد و کیفیت پاسخ. در Gemini 3.8 Flash،‏ 3.6 Flash، و 3.5 Flash Lite پشتیبانی می‌شود. برای جزئیات بیشتر، به درک ویدیو عامل مراجعه کنید.
  • محاسبه نشان (حالت ایستا): هر ثانیه از ویدیو به‌صورت زیر نشان‌گذاری می‌شود:
    • فریم‌های تکی (نمونه‌برداری‌شده در ۱ فریم در ثانیه):
      • اگر media_resolution روی پایین تنظیم شده باشد، فریم‌ها با نرخ ۶۶ توکن در هر فریم نشانه‌گذاری می‌شوند.
      • درغیراین‌صورت، فریم‌ها با نرخ ۲۵۸ کد در هر فریم کدبندی می‌شوند.
    • صوت: ۳۲ واحد اطلاعات در ثانیه.
    • فراداده نیز گنجانده شده است.
    • مجموع: تقریباً ۱۰۰ توکن در ثانیه ویدیو با وضوح رسانه پیش‌فرض (پایین)، یا تقریباً ۳۰۰ توکن در ثانیه ویدیو با وضوح رسانه بالا.
  • محاسبه نشان (حالت عامل): استفاده از نشان براساس پیچیدگی محتوا و استراتژی پیمایش مدل متفاوت است. نشانه‌های استدلال ناوبری تولیدشده درطول کاوش ویدیو به‌عنوان نشانه‌های فکری (total_thought_tokens) درنظر گرفته می‌شوند، درحالی‌که قاب‌ها، صدا، و ترانویسی بارگذاری‌شده براساس تقاضا به‌عنوان نشانه‌های استفاده از ابزار (total_tool_use_tokens) درنظر گرفته می‌شوند. پردازش عامل معمولاً تا ۸۸٪ کمتر از پردازش ایستا برای محتوای طولانی از کل نشانه‌ها استفاده می‌کند، زیرا مدل فقط ترانویسی و/یا قاب‌ها و/یا صدایی را که برای پاسخ دادن به پیام‌واره نیاز دارد بار می‌کند (راهنمای نشانه‌ها را ببینید).
  • وضوح رسانه: Gemini 3 با پارامتر media_resolution کنترل دقیق‌تری بر پردازش دید چندوجهی ارائه می‌دهد. پارامتر media_resolution حداکثر تعداد نشانه‌های اختصاص‌داده‌شده به هر تصویر ورودی یا قاب ویدیو را تعیین می‌کند. وضوح بالاتر توانایی مدل را در خواندن نوشتار ریز یا شناسایی جزئیات کوچک بهبود می‌بخشد، اما استفاده از نشان و تأخیر را افزایش می‌دهد. پارامترهای media_resolution و processing مستقل هستند: می‌توانید هر دو را روی یک ورودی ویدیو تنظیم کنید.

برای جزئیات بیشتر درباره محاسبات کد، به راهنمای کدها مراجعه کنید.

  • قالب مُهر زمان: هنگام اشاره به لحظات خاص در یک ویدیو در پیام‌واره خود، از قالب MM:SS (مثلاً 01:15 برای ۱ دقیقه و ۱۵ ثانیه) استفاده کنید.
  • جای‌گذاری پیام‌واره: اگر نوشتار و یک ویدیو را ترکیب می‌کنید، پیام‌واره نوشتاری را بعداز بخش ویدیویی در آرایه input قرار دهید.
  • مهلت‌های زمانی برای درخواست‌های طولانی: برای ویدیوهایی که به زمان پردازش طولانی یا استدلال چندمرحله‌ای پیچیده نیاز دارند، از جاری‌سازی (stream=True) یا اجرای پس‌زمینه‌ای (background=True) استفاده کنید. درخواست‌های هم‌زمان و غیرجاری‌سازی که در شرایط تقاضای بالا با تلاش مجدد زیرساخت مواجه می‌شوند ممکن است از بازه‌های اعتبار اتصال یا رمز اصالت‌سنجی فراتر روند، که می‌تواند به‌صورت خطاهای غیرمنتظره 401 Unauthorized یا مهلت زمانی ظاهر شود. جاری‌سازی اتصال را فعال نگه می‌دارد و استدلال واسطه‌ای و پیشرفت فراخوانی ابزار را نشان می‌دهد.

قدم بعدی چیست

  • وضوح رسانه: وضوح قاب‌های ویدیو را کنترل کنید تا بین کیفیت و استفاده از نشان تعادل برقرار کنید.
  • نشان‌ها: درک نحوه نشان‌گذاری محتوای ویدیو در هر دو حالت پردازش ایستا و عامل.
  • اجرای پس‌زمینه: برای جلوگیری از اتمام زمان اتصال، وظایف درک ویدیو طولانی‌مدت را به‌صورت ناهمزمان اجرا کنید.
  • دستورالعمل‌های سیستم: دستورالعمل‌های سیستم به شما امکان می‌دهد رفتار مدل را براساس نیازهای خاص و موارد استفاده خود هدایت کنید.
  • Files API: درباره بارگذاری و مدیریت فایل‌ها برای استفاده با Gemini بیشتر بدانید.
  • استراتژی‌های پیام‌واره فایل: Gemini API از پیام‌واره با داده‌های نوشتاری، تصویری، صوتی، و ویدیویی پشتیبانی می‌کند که به آن پیام‌واره چندوجهی نیز گفته می‌شود.
  • راهنمایی ایمنی: گاهی‌اوقات مدل‌های هوش مصنوعی زایا بروندادهای غیرمنتظره‌ای تولید می‌کنند، مثلاً بروندادهای نادرست، جانبدارانه، یا توهین‌آمیز. پردازش پسینی و ارزیابی انسانی برای محدود کردن خطر آسیب ناشی از چنین بروندادهایی ضروری است.