Как создавать видео с помощью Veo 3.1 в Gemini API

Подробнее о распознавании видео…

Veo 3.1 – это модель для создания 8-секундных видео (720p, 1080p или 4K) с нативно сгенерированным аудио. Вы можете получить доступ к этой модели программно с помощью Gemini API. Чтобы узнать больше о доступных вариантах модели Veo, ознакомьтесь с разделом Версии модели.

Veo 3.1 отлично справляется с широким спектром визуальных и кинематографических стилей и предлагает несколько новых возможностей:

  • Вертикальные видео. Выберите горизонтальные (16:9) или вертикальные (9:16) видео.
  • Расширение видео. Увеличивайте продолжительность видео, сгенерированных с помощью Veo.
  • Генерация по кадрам. Создавайте видео, указывая первый и последний кадры.
  • Изображения. Добавьте до трех референсных изображений, чтобы указать, что должно быть в видео.

Подробнее о том, как писать эффективные текстовые запросы для создания видео, рассказывается в руководстве по запросам для Veo.

Генерация видео по текстовому запросу

Ниже приведены примеры того, как можно создать видео с диалогом, кинематографичным реализмом или креативной анимацией.

Диалоги и звуковые эффекты

Python

import time
from google import genai
from google.genai import types

client = genai.Client()

prompt = """A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.
A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'"""

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="dialogue_example.mp4")
print("Generated video saved to dialogue_example.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = `A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.
A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'`;

let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: prompt,
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the generated video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "dialogue_example.mp4",
});
console.log(`Generated video saved to dialogue_example.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

    prompt := `A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.
    A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'`

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
        nil,
        nil,
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
    log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the generated video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "dialogue_example.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

Java

import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;

Client client = new Client();

String prompt =
    "A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.\n"
        + "A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'";

GenerateVideosOperation operation =
    client.models.generateVideos("veo-3.1-generate-preview", prompt, null, null);

// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
  System.out.println("Waiting for video generation to complete...");
  Thread.sleep(10000);
  operation = client.operations.getVideosOperation(operation, null);
}

// Download the generated video.
GeneratedVideo generatedVideo = operation.response().get().generatedVideos().get().get(0);
client.files.download(generatedVideo, "dialogue_example.mp4", null);
System.out.println("Generated video saved to dialogue_example.mp4");

REST

# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
        "prompt": "A close up of two people staring at a cryptic drawing on a wall, torchlight flickering. A man murmurs, \"This must be it. That'\''s the secret code.\" The woman looks at him and whispering excitedly, \"What did you find?\""
      }
    ]
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o dialogue_example.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 5 seconds before checking again.
  sleep 10
done

Кинематографический реализм

Python

import time
from google import genai
from google.genai import types

client = genai.Client()

prompt = """Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.
The convertible accelerates fast and the engine roars loudly."""

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="realism_example.mp4")
print("Generated video saved to realism_example.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = `Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.
The convertible accelerates fast and the engine roars loudly.`;

let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: prompt,
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the generated video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "realism_example.mp4",
});
console.log(`Generated video saved to realism_example.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

    prompt := `Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.
  The convertible accelerates fast and the engine roars loudly.`

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
        nil,
        nil,
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
    log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the generated video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "realism_example.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

Java

import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;

Client client = new Client();

String prompt =
    "Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.\n"
        + "The convertible accelerates fast and the engine roars loudly.";

GenerateVideosOperation operation =
    client.models.generateVideos("veo-3.1-generate-preview", prompt, null, null);

// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
  System.out.println("Waiting for video generation to complete...");
  Thread.sleep(10000);
  operation = client.operations.getVideosOperation(operation, null);
}

// Download the generated video.
GeneratedVideo generatedVideo = operation.response().get().generatedVideos().get().get(0);
client.files.download(generatedVideo, "realism_example.mp4", null);
System.out.println("Generated video saved to realism_example.mp4");

REST

# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
        "prompt": "Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below. The convertible accelerates fast and the engine roars loudly."
      }
    ]
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o realism_example.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 5 seconds before checking again.
  sleep 10
done

Творческая анимация

Python

import time
from google import genai

client = genai.Client()
prompt = "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet."

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="style_example.mp4")
print("Generated video saved to style_example.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet.";

let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: prompt,
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the generated video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "style_example.mp4",
});
console.log(`Generated video saved to style_example.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

    prompt := `A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet.`

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
        nil,
        nil,
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
    log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the generated video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "style_example.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

Java

import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;

Client client = new Client();

String prompt =
    "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet.";

GenerateVideosOperation operation =
    client.models.generateVideos("veo-3.1-generate-preview", prompt, null, null);

// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
  System.out.println("Waiting for video generation to complete...");
  Thread.sleep(10000);
  operation = client.operations.getVideosOperation(operation, null);
}

// Download the generated video.
GeneratedVideo generatedVideo = operation.response().get().generatedVideos().get().get(0);
client.files.download(generatedVideo, "style_example.mp4", null);
System.out.println("Generated video saved to style_example.mp4");

REST

# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
        "prompt": "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet."
      }
    ]
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o style_example.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 5 seconds before checking again.
  sleep 10
done

Как настроить соотношение сторон

Veo 3.1 позволяет создавать видео в горизонтальном (16:9, по умолчанию) или вертикальном (9:16) формате. Вы можете указать нужный вариант с помощью параметра aspect_ratio:

Python

import time
from google import genai
from google.genai import types

client = genai.Client()

prompt = """A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video."""

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
    config=types.GenerateVideosConfig(
      aspect_ratio="9:16",
    ),
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="pizza_making.mp4")
print("Generated video saved to pizza_making.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = `A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video.`;

let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: prompt,
    config: {
      aspectRatio: "9:16",
    },
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the generated video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "pizza_making.mp4",
});
console.log(`Generated video saved to pizza_making.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

    prompt := `A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video.`

  videoConfig := &genai.GenerateVideosConfig{
      AspectRatio: "9:16",
  }

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
        nil,
        videoConfig,
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
    log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the generated video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "pizza_making.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

REST

# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
        "prompt": "A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video."
      }
    ],
    "parameters": {
      "aspectRatio": "9:16"
    }
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o pizza_making.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 5 seconds before checking again.
  sleep 10
done

Управление разрешением

Veo 3.1 также может напрямую генерировать видео в разрешении 720p, 1080p или 4K (4K недоступно для Veo 3.1 Lite).

Чем выше разрешение, тем больше задержка. Кроме того, видео в формате 4K стоят дороже (см. цены).

Расширение Video также ограничено разрешением 720p.

Python

import time
from google import genai
from google.genai import types

client = genai.Client()

prompt = """A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon."""

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
    config=types.GenerateVideosConfig(
      resolution="4k",
    ),
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="4k_grand_canyon.mp4")
print("Generated video saved to 4k_grand_canyon.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = `A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon.`;

let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: prompt,
    config: {
      resolution: "4k",
    },
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the generated video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "4k_grand_canyon.mp4",
});
console.log(`Generated video saved to 4k_grand_canyon.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

    prompt := `A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon.`

  videoConfig := &genai.GenerateVideosConfig{
      Resolution: "4k",
  }

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
        nil,
        videoConfig,
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
    log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the generated video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "4k_grand_canyon.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

REST

# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
        "prompt": "A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon'\''s colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon."
      }
    ],
    "parameters": {
      "resolution": "4k"
    }
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o 4k_grand_canyon.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 5 seconds before checking again.
  sleep 10
done

Генерация видео из изображения

В коде ниже показано, как создать изображение с помощью Gemini 3.1 Flash Image (Nano Banana 2), а затем использовать его в качестве начального кадра для создания видео с помощью Veo 3.1.

Python

import time
from google import genai

client = genai.Client()

prompt = "Panning wide shot of a calico kitten sleeping in the sunshine"

# Step 1: Generate an image with Nano Banana 2.
image = client.models.generate_content(
    model="gemini-3.1-flash-image-preview",
    contents=prompt,
    config={"response_modalities":['IMAGE']}
)

# Step 2: Generate video with Veo 3.1 using the image.
operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
    image=image.parts[0].as_image(),
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3_with_image_input.mp4")
print("Generated video saved to veo3_with_image_input.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = "Panning wide shot of a calico kitten sleeping in the sunshine";

// Step 1: Generate an image with Nano Banana 2.
const imageResponse = await ai.models.generateContent({
  model: "gemini-3.1-flash-image-preview",
  prompt: prompt,
});

// Step 2: Generate video with Veo 3.1 using the image.
let operation = await ai.models.generateVideos({
  model: "veo-3.1-generate-preview",
  prompt: prompt,
  image: {
    imageBytes: imageResponse.generatedImages[0].image.imageBytes,
    mimeType: "image/png",
  },
});

// Poll the operation status until the video is ready.
while (!operation.done) {
  console.log("Waiting for video generation to complete...")
  await new Promise((resolve) => setTimeout(resolve, 10000));
  operation = await ai.operations.getVideosOperation({
    operation: operation,
  });
}

// Download the video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "veo3_with_image_input.mp4",
});
console.log(`Generated video saved to veo3_with_image_input.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

    prompt := "Panning wide shot of a calico kitten sleeping in the sunshine"

    // Step 1: Generate an image with Nano Banana 2.
    imageResponse, err := client.Models.GenerateContent(
        ctx,
        "gemini-3.1-flash-image-preview",
        prompt,
        nil, // GenerateImagesConfig
    )
    if err != nil {
        log.Fatal(err)
    }

    // Step 2: Generate video with Veo 3.1 using the image.
    operation, err := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
        imageResponse.GeneratedImages[0].Image,
        nil, // GenerateVideosConfig
    )
    if err != nil {
        log.Fatal(err)
    }

    // Poll the operation status until the video is ready.
    for !operation.Done {
        log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "veo3_with_image_input.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

Java

import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;
import com.google.genai.types.Image;

Client client = new Client();

String prompt = "Panning wide shot of a calico kitten sleeping in the sunshine";

// Step 1: Generate an image with Nano Banana 2.
GenerateContentResponse imageResponse =
    client.models.generateContent(
        "gemini-3.1-flash-image-preview",
        prompt,
        GenerateContentConfig.builder().responseModalities("IMAGE").build());

Blob inlineData = imageResponse.parts().get(0).inlineData().get();
Image image =
    Image.builder()
        .imageBytes(inlineData.data().get())
        .mimeType(inlineData.mimeType().orElse("image/png"))
        .build();

// Step 2: Generate video with Veo 3.1 using the image.
GenerateVideosOperation operation =
    client.models.generateVideos("veo-3.1-generate-preview", prompt, image, null);

// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
  System.out.println("Waiting for video generation to complete...");
  Thread.sleep(10000);
  operation = client.operations.getVideosOperation(operation, null);
}

// Download the video.
GeneratedVideo video = operation.response().get().generatedVideos().get().get(0);
client.files.download(video, "veo3_with_image_input.mp4", null);
System.out.println("Generated video saved to veo3_with_image_input.mp4");

Как использовать референсные изображения

Теперь Veo 3.1 принимает до трех референсных изображений, чтобы направлять контент сгенерированного видео. Предоставьте изображения человека, персонажа или товара, чтобы сохранить внешний вид объекта в выходном видео.

Например, если использовать эти три изображения, созданные с помощью Nano Banana, в качестве референсов и составить хороший запрос, получится следующее видео:

`dress_image` `woman_image` `glasses_image`
Платье от кутюр в стиле фламинго с розовыми и малиновыми перьями Красивая женщина с темными волосами и теплыми карими глазами Причудливые розовые солнцезащитные очки в форме сердца

Python

import time
from google import genai

client = genai.Client()

prompt = "The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress's long train glides and floats gracefully on the water's surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy."

dress_reference = types.VideoGenerationReferenceImage(
  image=dress_image, # Generated separately with Nano Banana
  reference_type="asset"
)

sunglasses_reference = types.VideoGenerationReferenceImage(
  image=glasses_image, # Generated separately with Nano Banana
  reference_type="asset"
)

woman_reference = types.VideoGenerationReferenceImage(
  image=woman_image, # Generated separately with Nano Banana
  reference_type="asset"
)

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
    config=types.GenerateVideosConfig(
      reference_images=[dress_reference, glasses_reference, woman_reference],
    ),
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3.1_with_reference_images.mp4")
print("Generated video saved to veo3.1_with_reference_images.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = "The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress's long train glides and floats gracefully on the water's surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy.";

// dressImage, glassesImage, womanImage generated separately with Nano Banana
// and available as objects like { imageBytes: "...", mimeType: "image/png" }
const dressReference = {
  image: dressImage,
  referenceType: "asset",
};
const sunglassesReference = {
  image: glassesImage,
  referenceType: "asset",
};
const womanReference = {
  image: womanImage,
  referenceType: "asset",
};

let operation = await ai.models.generateVideos({
  model: "veo-3.1-generate-preview",
  prompt: prompt,
  config: {
    referenceImages: [
      dressReference,
      sunglassesReference,
      womanReference,
    ],
  },
});

// Poll the operation status until the video is ready.
while (!operation.done) {
  console.log("Waiting for video generation to complete...");
  await new Promise((resolve) => setTimeout(resolve, 10000));
  operation = await ai.operations.getVideosOperation({
    operation: operation,
  });
}

// Download the video.
ai.files.download({
  file: operation.response.generatedVideos[0].video,
  downloadPath: "veo3.1_with_reference_images.mp4",
});
console.log(`Generated video saved to veo3.1_with_reference_images.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

  prompt := `The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress's long train glides and floats gracefully on the water's surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy.`

  // dressImage, glassesImage, womanImage generated separately with Nano Banana
  // and available as *genai.Image objects.
  var dressImage, glassesImage, womanImage *genai.Image

  dressReference := &genai.VideoGenerationReferenceImage{
    Image: dressImage,
    ReferenceType: "asset",
  }
  sunglassesReference := &genai.VideoGenerationReferenceImage{
    Image: glassesImage,
    ReferenceType: "asset",
  }
  womanReference := &genai.VideoGenerationReferenceImage{
    Image: womanImage,
    ReferenceType: "asset",
  }

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
    nil, // image
        &genai.GenerateVideosConfig{
      ReferenceImages: []*genai.VideoGenerationReferenceImage{
        dressReference,
        sunglassesReference,
        womanReference,
      },
    },
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
        log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "veo3.1_with_reference_images.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

REST

# Note: This script uses jq to parse the JSON response.
# It assumes dress_image_base64, glasses_image_base64, and woman_image_base64
# contain base64-encoded image data.

# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
      "prompt": "The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress'\''s long train glides and floats gracefully on the water'\''s surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy.",
      "referenceImages": [
        {
          "image": {"inlineData": {"mimeType": "image/png", "data": "'"$dress_image_base64"'"}},
          "referenceType": "asset"
        },
        {
          "image": {"inlineData": {"mimeType": "image/png", "data": "'"$glasses_image_base64"'"}},
          "referenceType": "asset"
        },
        {
          "image": {"inlineData": {"mimeType": "image/png", "data": "'"$woman_image_base64"'"}},
          "referenceType": "asset"
        }
      ]
    }],
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o veo3.1_with_reference_images.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 10 seconds before checking again.
  sleep 10
done

Используются первый и последний кадры

Veo 3.1 позволяет создавать видео с помощью интерполяции или указания первого и последнего кадров. О том, как писать эффективные текстовые запросы для создания видео, читайте в руководстве по запросам для Veo.

Python

import time
from google import genai

client = genai.Client()

prompt = "A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence."

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
    image=first_image, # The starting frame is passed as a primary input
    config=types.GenerateVideosConfig(
      last_frame=last_image # The ending frame is passed as a generation constraint in the config
    ),
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3.1_with_interpolation.mp4")
print("Generated video saved to veo3.1_with_interpolation.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = "A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence.";

// firstImage and lastImage generated separately with Nano Banana
// and available as objects like { imageBytes: "...", mimeType: "image/png" }
let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: prompt,
    image: firstImage, // The starting frame is passed as a primary input
    config: {
      lastFrame: lastImage, // The ending frame is passed as a generation constraint in the config
    },
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "veo3.1_with_interpolation.mp4",
});
console.log(`Generated video saved to veo3.1_with_interpolation.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

  prompt := `A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence.`

  // firstImage and lastImage generated separately with Nano Banana
  // and available as *genai.Image objects.
  var firstImage, lastImage *genai.Image

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
    firstImage, // The starting frame is passed as a primary input
        &genai.GenerateVideosConfig{
      LastFrame: lastImage, // The ending frame is passed as a generation constraint in the config
    },
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
        log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "veo3.1_with_interpolation.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

REST

# Note: This script uses jq to parse the JSON response.
# It assumes first_image_base64 and last_image_base64
# contain base64-encoded image data.

# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
# The starting frame is passed as a primary input
# The ending frame is passed as a generation constraint in the config
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
      "prompt": "A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence.",
      "image": {"inlineData": {"mimeType": "image/png", "data": "'"$first_image_base64"'"}},
      "lastFrame": {"inlineData": {"mimeType": "image/png", "data": "'"$last_image_base64"'"}}
    }],
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o veo3.1_with_interpolation.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 10 seconds before checking again.
  sleep 10
done
`first_image` `last_image` veo3.1_with_interpolation.mp4
Призрачная женщина с длинными белыми волосами и в струящемся платье мягко качается на веревочных качелях. Призрак женщины исчезает с качелей. Кинематографичное, пугающее видео, на котором жуткая женщина исчезает с качелей в тумане

Как увеличить продолжительность видео, созданного с помощью Veo

С помощью Veo 3.1 можно продлевать видео, созданные в Veo, на 7 секунд до 20 раз.

Ограничения для входных видео:

  • Продолжительность видео, созданных в Veo, не должна превышать 141 секунду.
  • Gemini API поддерживает расширения только для видео, созданных в Veo.
  • Видео должно быть снято на камеру предыдущего поколения, например operation.response.generated_videos[0].video
  • Видео хранятся 2 дня, но если видео используется для расширения, таймер хранения сбрасывается. Вы можете продлевать только видео, которые были сгенерированы или использованы в качестве референса в последние два дня.
  • Входные видео должны иметь определенную длину, соотношение сторон и размеры:
    • Соотношение сторон: 9:16 или 16:9.
    • Разрешение: 720p.
    • Длительность видео: не более 141 секунды.

В результате вы получите одно видео, в котором объединены исходный ролик и сгенерированное продолжение. Максимальная длительность – 148 секунд.

В этом примере мы берем видео, сгенерированное Veo, и расширяем его с помощью параметра video и нового запроса.

Запрос Выходные данные: butterfly_video
Бабочка-оригами машет крыльями и вылетает через французские двери в сад. Бабочка-оригами машет крыльями и вылетает через французские двери в сад.

Python

import time
from google import genai

client = genai.Client()

prompt = "Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower."

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    video=operation.response.generated_videos[0].video, # This must be a video from a previous generation
    prompt=prompt,
    config=types.GenerateVideosConfig(
        number_of_videos=1,
        resolution="720p"
    ),
)

# Poll the operation status until the video is ready.
while not operation.done:
    print("Waiting for video generation to complete...")
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3.1_extension.mp4")
print("Generated video saved to veo3.1_extension.mp4")

JavaScript

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

const ai = new GoogleGenAI({});

const prompt = "Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower.";

// butterflyVideo must be a video from a previous generation
// available as an object like { videoBytes: "...", mimeType: "video/mp4" }
let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    video: butterflyVideo,
    prompt: prompt,
    config: {
        numberOfVideos: 1,
        resolution: "720p",
    },
});

// Poll the operation status until the video is ready.
while (!operation.done) {
    console.log("Waiting for video generation to complete...")
    await new Promise((resolve) => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({
        operation: operation,
    });
}

// Download the video.
ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "veo3.1_extension.mp4",
});
console.log(`Generated video saved to veo3.1_extension.mp4`);

Проложить маршрут

package main

import (
    "context"
    "log"
    "os"
    "time"

    "google.golang.org/genai"
)

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

  prompt := `Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower.`

  // butterflyVideo must be a video from a previous generation
  // available as a *genai.Video object.
  var butterflyVideo *genai.Video

    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        prompt,
    nil, // image
    butterflyVideo,
        &genai.GenerateVideosConfig{
      NumberOfVideos: 1,
      Resolution: "720p",
    },
    )

    // Poll the operation status until the video is ready.
    for !operation.Done {
        log.Println("Waiting for video generation to complete...")
        time.Sleep(10 * time.Second)
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Download the video.
    video := operation.Response.GeneratedVideos[0]
    client.Files.Download(ctx, video.Video, nil)
    fname := "veo3.1_extension.mp4"
    _ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
    log.Printf("Generated video saved to %s\n", fname)
}

REST

# Note: This script uses jq to parse the JSON response.
# It assumes butterfly_video_base64 contains base64-encoded
# video data from a previous generation.

# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
      "prompt": "Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower.",
      "video": {"inlineData": {"mimeType": "video/mp4", "data": "'"$butterfly_video_base64"'"}}
    }],
    "parameters": {
      "numberOfVideos": 1,
      "resolution": "720p"
    }
  }' | jq -r .name)

# Poll the operation status until the video is ready
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Extract the download URI from the final response.
    video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
    echo "Downloading video from: ${video_uri}"

    # Download the video using the URI and API key and follow redirects.
    curl -L -o veo3.1_extension.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
    break
  fi
  # Wait for 10 seconds before checking again.
  sleep 10
done

О том, как писать эффективные текстовые запросы для создания видео, читайте в руководстве по запросам Veo.

Обработка асинхронных операций

Генерация видео требует больших вычислительных мощностей. Когда вы отправляете запрос к API, запускается длительное задание и сразу же возвращается объект operation. Затем вам нужно будет отправлять запросы, пока видео не будет готово. Об этом будет свидетельствовать статус done со значением true.

Основная часть этого процесса – цикл опроса, который периодически проверяет статус задания.

Python

import time
from google import genai
from google.genai import types

client = genai.Client()

# After starting the job, you get an operation object.
operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt="A cinematic shot of a majestic lion in the savannah.",
)

# Alternatively, you can use operation.name to get the operation.
operation = types.GenerateVideosOperation(name=operation.name)

# This loop checks the job status every 10 seconds.
while not operation.done:
    time.sleep(10)
    # Refresh the operation object to get the latest status.
    operation = client.operations.get(operation)

# Once done, the result is in operation.response.
# ... process and download your video ...

JavaScript

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

const ai = new GoogleGenAI({});

// After starting the job, you get an operation object.
let operation = await ai.models.generateVideos({
  model: "veo-3.1-generate-preview",
  prompt: "A cinematic shot of a majestic lion in the savannah.",
});

// Alternatively, you can use operation.name to get the operation.
// operation = types.GenerateVideosOperation(name=operation.name)

// This loop checks the job status every 10 seconds.
while (!operation.done) {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // Refresh the operation object to get the latest status.
    operation = await ai.operations.getVideosOperation({ operation });
}

// Once done, the result is in operation.response.
// ... process and download your video ...

Проложить маршрут

package main

import (
    "context"
    "log"
    "time"

    "google.golang.org/genai"
)

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

    // After starting the job, you get an operation object.
    operation, _ := client.Models.GenerateVideos(
        ctx,
        "veo-3.1-generate-preview",
        "A cinematic shot of a majestic lion in the savannah.",
        nil,
        nil,
    )

    // This loop checks the job status every 10 seconds.
    for !operation.Done {
        time.Sleep(10 * time.Second)
        // Refresh the operation object to get the latest status.
        operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
    }

    // Once done, the result is in operation.Response.
    // ... process and download your video ...
}

Java

import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;

Client client = new Client();

// After starting the job, you get an operation object.
GenerateVideosOperation operation =
    client.models.generateVideos(
        "veo-3.1-generate-preview",
        "A cinematic shot of a majestic lion in the savannah.",
        null,
        null);

// Alternatively, you can use operation.name to construct the operation.
operation = GenerateVideosOperation.builder().name(operation.name().get()).build();

// This loop checks the job status every 10 seconds.
while (!operation.done().orElse(false)) {
  Thread.sleep(10000);
  // Refresh the operation object to get the latest status.
  operation = client.operations.getVideosOperation(operation, null);
}

// Once done, the result is in operation.response().
// ... process and download your video ...

REST

# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"

# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -X "POST" \
  -d '{
    "instances": [{
        "prompt": "A cinematic shot of a majestic lion in the savannah."
      }
    ]
  }' | jq -r .name)

# This loop checks the job status every 10 seconds.
while true; do
  # Get the full JSON status and store it in a variable.
  status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")

  # Check the "done" field from the JSON stored in the variable.
  is_done=$(echo "${status_response}" | jq .done)

  if [ "${is_done}" = "true" ]; then
    # Once done, the result is in status_response.
    # ... process and download your video ...
    echo "Video generation complete."
    break
  fi
  # Wait for 10 seconds before checking again.
  echo "Waiting for video generation to complete..."
  sleep 10
done

Параметры и спецификации Veo API

Эти параметры можно задать в запросе к API, чтобы управлять процессом создания видео.

Параметр Veo 3.1 и Veo 3.1 Fast Veo 3.1 Lite Veo 3 и Veo 3 Fast
Экземпляры
prompt
Текстовое описание видео. Поддерживает аудиоподсказки.
string string string
image:
исходное изображение для анимации.
Объект Image Объект Image Объект Image
lastFrame:
Последнее изображение для перехода в видео с интерполяцией. Используется вместе с параметром image.
Объект Image Объект Image Объект Image
referenceImages:
До трех изображений, которые будут использоваться в качестве референсов по стилю и контенту.
Объект VideoGenerationReferenceImage Объект n/a –
video:
Видео, которое будет использоваться для видеорасширения.
Video объект предыдущего поколения – –
Параметры
aspectRatio:
соотношение сторон видео.
"16:9" (по умолчанию),
"9:16"

"16:9" (по умолчанию),
"9:16"
"16:9" (по умолчанию),
"9:16"
durationSeconds:
Длительность сгенерированного видео.
"4", "6", "8".

При использовании расширения, референсных изображений или разрешений 1080p и 4K должно быть указано значение 8.
"4", "6", "8".

Если используются референсные изображения или разрешение 1080p, значение должно быть равно 8.
"4", "6", "8".

При использовании расширения, референсных изображений или разрешений 1080p и 4K должно быть указано значение 8.
personGeneration:
Управляет генерацией людей. (см. Ограничения).
Генерация видео по текстовому запросу и расширение видео:только
"allow_all".

Генерация видео по изображению, интерполяция и референсные изображения:только
"allow_adult".
Генерация видео из текста:
только "allow_all"

Генерация видео из картинки, интерполяция и референсные изображения:
только "allow_adult"
Видео из текста:
только "allow_all"

Видео из картинки:
только "allow_adult"
resolution:
Разрешение видео.
"720p" (по умолчанию),
"1080p" (поддерживается только длительность 8 с),
"4k" (поддерживается только длительность 8 с)

"720p" только для расширения
"720p" (по умолчанию),
"1080p" (поддерживается только продолжительность 8 секунд)
"720p" (по умолчанию),
"1080p" (поддерживается только длительность 8 с),
"4k" (поддерживается только длительность 8 с)

"720p" только для расширения

Обратите внимание, что параметр seed также доступен для моделей Veo 3. Это не гарантирует детерминированность, но немного улучшает ее.

Функции модели

Функция Veo 3.1 и Veo 3.1 Fast Veo 3.1 Lite Veo 3 и Veo 3 Fast
Аудио.
Генерирует аудио вместе с видео.
✔️ Всегда включено ✔️ Всегда включено ✔️ Всегда включено
Модальности входных данных.
Тип входных данных, используемых для генерации.
Видео из текста, видео из картинки, видео из видео Видео из текста и видео из изображения Видео из текста и видео из изображения
Разрешение.
Разрешение видео.
720p, 1080p (только 8 сек.), 4k (только 8 сек.)

720p только при использовании расширения видео.
720p, 1080p (только 8 секунд)
720p и 1080p (только 16:9)
Частота кадров.
Частота кадров в видео.
24 кадра в секунду 24 кадра в секунду 24 кадра в секунду
Длина видео.
Продолжительность сгенерированного видео.
8, 6 или 4 секунды.

8 секунд – только если выбрано разрешение 1080p или 4K или используются референсные изображения.
8, 6 или 4 секунды

8 секунд – только если выбрано разрешение 1080p или используются референсные изображения.
8 секунд
Видео на запрос.
Количество видео, создаваемых по одному запросу.
1 1 1
Статус:
Доступность модели
Предпросмотр Предпросмотр Стабильная

Ограничения

  • Запросы с несколькими видео. Ссылки на несколько видео и рассуждения о них пока не поддерживаются. Попытка использовать несколько видео в запросе может привести к снижению производительности модели или неожиданным результатам.
  • Поддержка языков. Полностью поддерживается английский язык. Другие языки не тестировались, поэтому результаты могут быть разными.
  • Задержка запроса. Минимум: 11 секунд. Максимум: 6 минут (в пиковые часы).
  • Региональные ограничения. В ЕС, Великобритании, Швейцарии, странах Ближнего Востока и Северной Африки для атрибута personGeneration разрешено только значение allow_adult.
  • Хранение видео. Сгенерированные видео хранятся на сервере в течение двух дней, а затем удаляются. Чтобы сохранить локальную копию, скачайте видео в течение двух дней после создания. Продолженные видео считаются новыми.
  • Водяные знаки. В видео, созданные Veo, добавляются водяные знаки SynthID. Это наш инструмент для добавления водяных знаков и идентификации контента, созданного ИИ. Видео можно проверить на платформе SynthID.
  • Безопасность. Сгенерированные видео проходят через фильтры безопасности и проверку на запоминание, которые помогают снизить риски, связанные с конфиденциальностью, авторскими правами и предвзятостью.
  • Ошибка аудио. Иногда Veo 3.1 блокирует генерацию видео из-за фильтров безопасности или других проблем с обработкой аудио. Если видео не будет создано, плата не взимается.

Руководство по запросам для Veo

В этом разделе приведены примеры видео, которые можно создать с помощью Veo, и показано, как изменять запросы, чтобы получать разные результаты.

Фильтры безопасности

Veo применяет фильтры безопасности в Gemini, чтобы в сгенерированных видео и загруженных фотографиях не было оскорбительного контента. Запросы, нарушающие наши условия и правила, блокируются.

Основы написания запросов

Хорошие запросы должны быть описательными и понятными. Чтобы получить наилучший результат, начните с определения основной идеи, уточните ее, добавив ключевые слова и модификаторы, и включите в запросы терминологию, относящуюся к видео.

В запрос следует включить следующие элементы:

  • Объект. Предмет, человек, животное или пейзаж, который вы хотите видеть в видео, например городской пейзаж, природа, транспортные средства или щенки.
  • Действие. Что делает объект, например идет, бежит или поворачивает голову.
  • Стиль. Укажите творческое направление, используя ключевые слова, например научная фантастика, фильм ужасов, нуар или мультфильм.
  • Положение и движение камеры (необязательно). Управляйте положением и движением камеры, используя такие термины, как вид с воздуха, на уровне глаз, съемка сверху вниз, съемка с тележки или съемка снизу вверх.
  • Композиция (необязательно). Положение камеры относительно субъекта, например общий план, крупный план, один человек в кадре или два человека в кадре.
  • Фокус и эффекты объектива. Чтобы добиться определенных визуальных эффектов, используйте такие термины, как малая глубина резкости, большая глубина резкости, мягкий фокус, макрообъектив и широкоугольный объектив.
  • Атмосфера (необязательно) – как цвет и свет влияют на сцену, например синие тона, ночь или теплые тона.

Дополнительные советы по написанию запросов

  • Используйте описательный язык. Добавляйте прилагательные и наречия, чтобы Veo было проще понять, что вы хотите получить.
  • Улучшить детали лица. Укажите, что нужно сделать акцент на лице, например добавьте в запрос слово портрет.

Более подробные стратегии составления запросов можно найти в статье Введение в разработку запросов.

Запрос на аудио

Вы можете указать Veo, какие звуковые эффекты, окружающий шум и диалоги нужно добавить. Модель улавливает нюансы этих сигналов, чтобы сгенерировать синхронизированную звуковую дорожку.

  • Диалоги. Используйте кавычки для прямой речи. Пример: "Это, должно быть, ключ", – пробормотал он.
  • Звуковые эффекты. Описывайте звуки. (Пример: громкий визг шин, рев двигателя.)
  • Окружающий шум. Опишите звуковой ландшафт. Пример: "На фоне слышен тихий, жутковатый гул".

В этих видео показано, как Veo 3 генерирует аудио по запросам с разным уровнем детализации.

Запрос Сгенерированные выходные данные
Больше деталей (диалог и атмосфера)
Общий план туманного леса на северо-западе США. Два уставших туриста, мужчина и женщина, пробираются сквозь папоротники. Мужчина резко останавливается и смотрит на дерево. Крупный план: на коре дерева видны свежие глубокие следы когтей. Мужчина (держит руку на охотничьем ноже): "Это не обычный медведь". Женщина (испуганно, оглядывая лес): "Тогда что это?" Грубый лай, треск веток, шаги по влажной земле. Щебечет одинокая птица.
Два человека в лесу находят следы медведя.
Меньше деталей (диалог)
Бумажная анимация. Новый библиотекарь: "Где у вас хранятся запрещенные книги?" Старый куратор: "Никак. Они нас держат".
Анимированные библиотекари обсуждают запрещенные книги

Попробуйте эти запросы, чтобы послушать аудио. Попробовать Veo

Запросы с референсными изображениями

Вы можете использовать одно или несколько изображений в качестве входных данных для создания видео с помощью функции Преобразование изображения в видео в Veo. Veo использует входное изображение в качестве начального кадра. Выберите изображение, которое лучше всего подходит для первой сцены вашего видео, чтобы анимировать повседневные объекты, оживить рисунки и картины, а также добавить движение и звук в сцены природы.

Запрос Сгенерированные выходные данные
Исходное изображение (сгенерировано Nano Banana)
Гиперреалистичная макрофотография крошечных серферов, катающихся на океанских волнах в каменной раковине в деревенском стиле. Из винтажного латунного крана течет вода, создавая бесконечный прибой. Сюрреалистичный, причудливый, яркое естественное освещение.
Крошечные миниатюрные серферы катаются на океанских волнах в каменной раковине в деревенском стиле.
Сгенерированное видео (Veo 3.1)
Сюрреалистичное кинематографичное макровидео. Крошечные серферы катаются на бесконечных волнах в каменной раковине. Бесконечный прибой генерируется старинным латунным краном. Камера медленно панорамирует причудливую, залитую солнцем сцену, пока миниатюрные фигурки умело рассекают бирюзовую воду.
Крошечные серферы катаются на волнах в раковине.

Veo 3.1 позволяет использовать референсные изображения или ингредиенты, чтобы направлять генерацию видео. Добавьте до трех изображений одного человека, персонажа или товара. Veo сохраняет внешний вид объекта в выходном видео.

Запрос Сгенерированные выходные данные
Референсное изображение (создано Nano Banana)
Глубоководный морской черт скрывается в темной воде, обнажив зубы и светящуюся приманку.
Темный и светящийся удильщик
Референсное изображение (создано Nano Banana)
Розовый детский костюм принцессы с волшебной палочкой и тиарой на простом фоне.
Детский розовый костюм принцессы
Выходное видео (создано Veo 3.1)
Создай забавную мультяшную версию рыбы в костюме, которая плавает и размахивает палочкой.
Рыба-удильщик в костюме принцессы

С помощью Veo 3.1 вы также можете создавать видео, указав первый и последний кадры.

Запрос Сгенерированные выходные данные
Первое изображение (создано Nano Banana)
Высококачественное фотореалистичное изображение рыжего кота, который едет в красном гоночном кабриолете по побережью Французской Ривьеры.
Рыжий кот за рулем красного гоночного кабриолета
Последнее изображение (создано Nano Banana)
Покажи, что происходит, когда машина взлетает с обрыва.
Рыжий кот за рулем красного кабриолета падает с обрыва
Выходное видео (создано Veo 3.1)
Необязательно
Кот съезжает со скалы и взлетает

Эта функция позволяет точно контролировать композицию кадра, определяя начальный и конечный кадры. Загрузите изображение или используйте кадр из предыдущего видео, чтобы сцена начиналась и заканчивалась именно так, как вы задумали.

Запрос на расширение

Чтобы продлить видео, созданное с помощью Veo, используйте Veo 3.1 (недоступно для Veo 3.1 Lite). В качестве входных данных укажите видео и, если хотите, текстовый запрос. Функция "Продлить" берет за основу последнюю секунду или 24 кадра видео и продолжает действие.

Обратите внимание, что голос не получится продлить, если он отсутствует в последней секунде видео.

Запрос Сгенерированные выходные данные
Исходное видео (создано Veo 3.1)
Парапланерист взлетает с вершины горы и начинает спускаться вниз, любуясь долинами, покрытыми цветами.
Парапланерист взлетает с вершины горы
Сгенерированное видео (Veo 3.1)
Продли это видео, чтобы параплан медленно спускался.
Парапланерист взлетает с вершины горы, а затем медленно спускается

Примеры запросов и результатов

В этом разделе представлено несколько запросов, подчеркивающих, как описательные детали могут улучшить результат каждого видео.

Сосульки

В этом видео показано, как использовать элементы основ написания запросов в вашем запросе.

Запрос Сгенерированные выходные данные
Крупный план (композиция) тающих сосулек (объект) на замерзшей каменной стене (контекст) в холодных синих тонах (атмосфера), приближение (движение камеры) с сохранением деталей капель воды (действие). Тающие сосульки на синем фоне.

Мужчина говорит по телефону

Эти видео показывают, как можно изменять запрос, добавляя в него все больше деталей, чтобы Veo создавал видео, которые вам нравятся.

Запрос Сгенерированные выходные данные
Меньше деталей
Камера приближается, чтобы показать крупным планом отчаявшегося мужчину в зеленом плаще. Он звонит по настенному телефону с дисковым набором, на фоне зеленые неоновые лампы. Похоже на сцену из фильма.
Мужчина говорит по телефону.
Больше деталей.
Кинематографичный кадр крупным планом: отчаявшийся мужчина в поношенном зеленом плаще набирает номер на дисковом телефоне, закрепленном на грязной кирпичной стене, в жутковатом свете зеленой неоновой вывески. Камера приближается, показывая напряжение в его челюсти и отчаяние, запечатленное на его лице, когда он пытается сделать звонок. Небольшая глубина резкости фокусирует внимание на его нахмуренных бровях и черном дисковом телефоне, размывая фон в море неоновых цветов и неясных теней, создавая ощущение срочности и изоляции.
Мужчина говорит по телефону

Снежный барс

Запрос Сгенерированные выходные данные
Простой запрос:
Милое существо с мехом, как у снежного барса, гуляет по зимнему лесу, 3D-мультфильм.
Снежный барс вялый.
Подробный запрос:
Создай короткую 3D-анимацию в стиле веселого мультфильма. Милое существо с шерстью, как у снежного барса, большими выразительными глазами и дружелюбной округлой формой радостно скачет по причудливому зимнему лесу. На изображении должны быть заснеженные деревья с округлыми кронами, падающие снежинки и теплый солнечный свет, пробивающийся сквозь ветви. Прыгучие движения существа и широкая улыбка должны передавать чистый восторг. Стремитесь к оптимистичному, трогательному тону с яркими, жизнерадостными цветами и игривой анимацией.
Снежный барс бежит быстрее.

Примеры по элементам письма

В этих примерах показано, как уточнить запрос по каждому базовому элементу.

Тема и контекст

Укажите основной объект и фон или окружение (контекст).

Запрос Сгенерированные выходные данные
Архитектурная визуализация белого бетонного многоквартирного дома с плавными органическими формами, плавно сочетающимися с пышной зеленью и футуристическими элементами Плейсхолдер.
Спутник, летящий в космическом пространстве на фоне луны и звезд. Спутник, парящий в атмосфере.

Действие

Укажите, что делает объект (например, идет, бежит или поворачивает голову).

Запрос Сгенерированные выходные данные
Общий план: женщина идет по пляжу и смотрит на горизонт на закате. Она выглядит довольной и расслабленной. Закат абсолютно прекрасен.

Стиль

Добавьте ключевые слова, чтобы направить генерацию в сторону определенной эстетики (например, сюрреалистичной, винтажной, футуристичной, нуарной).

Запрос Сгенерированные выходные данные
Стиль нуар, мужчина и женщина идут по улице, загадочность, кинематографичность, черно-белое изображение. Стиль нуар – это очень красиво.

Движение камеры и композиция

Укажите, как движется камера (например, от первого лица, вид с воздуха или с дрона) и как кадрируется изображение (например, общий план, крупный план или снизу вверх).

Запрос Сгенерированные выходные данные
Кадр от первого лица из винтажного автомобиля, едущего под дождем, Канада, ночь, кинематографично. Закат абсолютно прекрасен.
Экстремально крупный план глаза, в котором отражается город. Закат абсолютно прекрасен.

Обстановка

Цветовая палитра и освещение влияют на настроение. Попробуйте использовать такие слова, как "приглушенный оранжевый", "теплые тона", "естественный свет", "восход солнца" или "холодные синие тона".

Запрос Сгенерированные выходные данные
Крупный план: девочка держит на руках очаровательного щенка золотистого ретривера в парке, солнечный свет. Девочка держит на руках щенка.
Кинематографичный крупный план грустной женщины, едущей в автобусе под дождем, холодные синие тона, грустное настроение. Грустная женщина едет в автобусе.

Соотношения сторон

В Veo можно указать соотношение сторон видео.

Запрос Сгенерированные выходные данные
Широкий экран (16:9)
Создай видео, снятое с дрона, на котором мужчина едет на красном кабриолете по Палм-Спрингс, 1970-е годы, теплый солнечный свет, длинные тени.
Мужчина за рулем красного кабриолета в Палм-Спрингс, стиль 1970-х годов.
Вертикальное (9:16)
Создай видео, в котором показано плавное движение воды в величественном гавайском водопаде посреди пышного тропического леса. Сделай акцент на реалистичном потоке воды, детализированной листве и естественном освещении, чтобы передать ощущение спокойствия. Запечатлейте бурлящую воду, туманную атмосферу и солнечные лучи, пробивающиеся сквозь густую крону деревьев. Используйте плавные, кинематографичные движения камеры, чтобы показать водопад и его окрестности. Стремитесь к спокойному, реалистичному тону, переносящему зрителя в безмятежную красоту гавайских тропических лесов.
Величественный гавайский водопад в пышном тропическом лесу.

Версии модели

Дополнительную информацию об использовании модели Veo можно найти на страницах Цены и Ограничения частоты запросов.

Предварительная версия Veo 3.1

Свойство Описание
Код модели

Gemini API

veo-3.1-generate-preview

Поддерживаемые типы данных

Ввод данных

Текст, изображение

Выходные данные

Видео со звуком

Ограничения

Текстовое поле

1024 токена

Выходное видео

1

Последнее обновление Январь 2026 г.

Предварительная версия Veo 3.1 Fast

Свойство Описание
Код модели

Gemini API

veo-3.1-fast-generate-preview

Поддерживаемые типы данных

Ввод данных

Текст, изображение

Выходные данные

Видео со звуком

Ограничения

Текстовое поле

1024 токена

Выходное видео

1

Последнее обновление Январь 2026 г.

Предварительная версия Veo 3.1 Lite

Свойство Описание
Код модели

Gemini API

veo-3.1-lite-generate-preview

Поддерживаемые типы данных

Ввод данных

Текст, изображение

Выходные данные

Видео со звуком

Ограничения

Текстовое поле

1024 токена

Выходное видео

1

Последнее обновление Март 2026 г.

Veo 3 (поддержка прекращена)

Свойство Описание
Код модели

Gemini API

veo-3.0-generate-001

Поддерживаемые типы данных

Ввод данных

Текст, изображение

Выходные данные

Видео со звуком

Ограничения

Текстовое поле

1024 токена

Выходное видео

1

Последнее обновление Июль 2025 г.

Veo 3 Fast (поддержка прекращена)

Свойство Описание
Код модели

Gemini API

veo-3.0-fast-generate-001

Поддерживаемые типы данных

Ввод данных

Текст, изображение

Выходные данные

Видео со звуком

Ограничения

Текстовое поле

1024 токена

Выходное видео

1

Последнее обновление Июль 2025 г.

Версии Veo Fast позволяют разработчикам создавать видео со звуком, сохраняя высокое качество и оптимизируя скорость и бизнес-сценарии. Они идеально подходят для бэкенд-сервисов, которые программно генерируют рекламу, инструментов для быстрого A/B-тестирования креативных концепций или приложений, которым необходимо быстро создавать контент для социальных сетей.

Дальнейшие действия