Guia de início rápido: gerar texto usando a API Gemini na Vertex AI

Neste guia de início rápido, você envia as seguintes solicitações multimodais para a API Gemini na Vertex AI e confere as respostas:

  • Um comando de texto
  • Um comando e uma imagem
  • Um comando e um arquivo de vídeo (com uma faixa de áudio)

É possível concluir este guia de início rápido usando um SDK de linguagem de programação no seu ambiente local ou a API REST.

Pré-requisitos

Para concluir este guia de início rápido, você precisa:

  • Configurar um projeto Google Cloud e ativar a API Vertex AI
  • Na sua máquina local:
    • Instalar, inicializar e autenticar com a Google Cloud CLI
    • Instalar o SDK da sua linguagem

Configurar um projeto do Google Cloud

Configure seu projeto Google Cloud e ative a API Vertex AI.

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. Make sure that you have the following role or roles on the project: Vertex AI Platform Express User

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Acessar o IAM
    2. Selecionar um projeto.
    3. Clique em CONCEDER ACESSO.
    4. No campo Novos principais, insira seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.

    5. Na lista Selecionar um papel, escolha um.
    6. Para conceder outros papéis, clique em Adicionar outro papel e adicione cada papel adicional.
    7. Clique em Salvar.
  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  7. Make sure that billing is enabled for your Google Cloud project.

  8. Enable the Vertex AI API.

    Enable the API

  9. Make sure that you have the following role or roles on the project: Vertex AI Platform Express User

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Acessar o IAM
    2. Selecionar um projeto.
    3. Clique em CONCEDER ACESSO.
    4. No campo Novos principais, insira seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.

    5. Na lista Selecionar um papel, escolha um.
    6. Para conceder outros papéis, clique em Adicionar outro papel e adicione cada papel adicional.
    7. Clique em Salvar.

    Instalar e autenticar com a Google Cloud CLI

    Para usar a API Gemini na Vertex AI, configure e autentique a Google Cloud CLI na sua máquina local. Ao contrário da API Gemini no Google AI Studio, que usa chaves de API, a API Gemini na Vertex AI gerencia o acesso com o Identity and Access Management.

    1. Instale e inicialize a Google Cloud CLI.

    2. Se você já instalou a CLI gcloud, execute este comando para garantir que os componentes gcloud estejam atualizados.

      gcloud components update
    3. Para autenticar com a CLI gcloud, gere um arquivo local de Application Default Credentials (ADC) executando este comando. O fluxo da Web iniciado pelo comando é usado para fornecer suas credenciais de usuário.

      gcloud auth application-default login

      Para mais informações, consulte Configurar o Application Default Credentials.

    Configurar o SDK para sua linguagem de programação

    Na máquina local, clique em uma das seguintes guias para instalar o SDK da linguagem de programação.

    SDK da IA generativa para Python

    Instale e atualize o SDK de IA generativa para Python executando este comando.

    pip install --upgrade google-genai

    SDK de IA generativa para Go

    Instale e atualize o SDK da IA generativa para Go executando este comando.

    go get google.golang.org/genai

    SDK da IA generativa para Node.js

    Instale e atualize o SDK da IA generativa para Node.js executando este comando.

    npm install @google/genai

    SDK de IA generativa para Java

    Instale e atualize o SDK da IA generativa para Java:

    Maven

    Adicione o seguinte ao seu pom.xml:

    <dependencies>
      <dependency>
        <groupId>com.google.genai</groupId>
        <artifactId>google-genai</artifactId>
        <version>0.7.0</version>
      </dependency>
    </dependencies>
    

    C#

    Instale o pacote Google.Cloud.AIPlatform.V1 pelo NuGet. Use seu método preferido para adicionar pacotes ao projeto. Por exemplo, clique com o botão direito do mouse no projeto no Visual Studio e escolha Gerenciar pacotes NuGet....

    REST

    1. Insira o comando abaixo para configurar as variáveis de ambiente. Substitua PROJECT_ID pelo ID do seu Google Cloud projeto.

      MODEL_ID="gemini-2.0-flash-001"
      PROJECT_ID="PROJECT_ID"
    2. Use a Google Cloud CLI para provisionar o endpoint executando este comando.

      gcloud beta services identity create --service=aiplatform.googleapis.com --project=${PROJECT_ID}

    Enviar um comando para a API Gemini na Vertex AI

    Use o código a seguir para enviar um comando à API Gemini na Vertex AI. Este exemplo retorna uma lista de possíveis nomes para uma floricultura especializada.

    É possível executar o código na linha de comando, usando um ambiente de desenvolvimento integrado ou incluindo o código no aplicativo.

    Gen AI SDK for Python

    Instalar

    pip install --upgrade google-genai

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import HttpOptions
    
    client = genai.Client(http_options=HttpOptions(api_version="v1"))
    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents="How does AI work?",
    )
    print(response.text)
    # Example response:
    # Okay, let's break down how AI works. It's a broad field, so I'll focus on the ...
    #
    # Here's a simplified overview:
    # ...

    Gen AI SDK for Go

    Saiba como instalar ou atualizar o Gen AI SDK for Go.

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"google.golang.org/genai"
    )
    
    // generateWithText shows how to generate text using a text prompt.
    func generateWithText(w io.Writer) error {
    	ctx := context.Background()
    
    	client, err := genai.NewClient(ctx, &genai.ClientConfig{
    		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
    	})
    	if err != nil {
    		return fmt.Errorf("failed to create genai client: %w", err)
    	}
    
    	resp, err := client.Models.GenerateContent(ctx,
    		"gemini-2.0-flash-001",
    		genai.Text("How does AI work?"),
    		nil,
    	)
    	if err != nil {
    		return fmt.Errorf("failed to generate content: %w", err)
    	}
    
    	respText, err := resp.Text()
    	if err != nil {
    		return fmt.Errorf("failed to convert model response to text: %w", err)
    	}
    	fmt.Fprintln(w, respText)
    	// Example response:
    	// That's a great question! Understanding how AI works can feel like ...
    	// ...
    	// **1. The Foundation: Data and Algorithms**
    	// ...
    
    	return nil
    }
    

    Gen AI SDK for Node.js

    Instalar

    npm install @google/genai

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    const {GoogleGenAI} = require('@google/genai');
    
    const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
    const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
    
    async function generateContent(
      projectId = GOOGLE_CLOUD_PROJECT,
      location = GOOGLE_CLOUD_LOCATION
    ) {
      const ai = new GoogleGenAI({
        vertexai: true,
        project: projectId,
        location: location,
      });
    
      const response = await ai.models.generateContent({
        model: 'gemini-2.0-flash',
        contents: 'How does AI work?',
      });
    
      console.log(response.text);
    
      return response.text;
    }

    Gen AI SDK for Java

    Saiba como instalar ou atualizar o Gen AI SDK for Java.

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    
    import com.google.genai.Client;
    import com.google.genai.types.Content;
    import com.google.genai.types.GenerateContentResponse;
    import com.google.genai.types.HttpOptions;
    import com.google.genai.types.Part;
    
    public class GenerateContentWithText {
    
      public static void main(String[] args) {
        // TODO(developer): Replace these variables before running the sample.
        String modelId = "gemini-2.0-flash";
        generateContent(modelId);
      }
    
      public static String generateContent(String modelId) {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (Client client = Client.builder()
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {
    
          GenerateContentResponse response =
              client.models.generateContent(modelId, Content.fromParts(
                      Part.fromText("How does AI work?")),
                  null);
    
          System.out.print(response.text());
          // Example response:
          // Okay, let's break down how AI works. It's a broad field, so I'll focus on the ...
          //
          // Here's a simplified overview:
          // ...
          return response.text();
        }
      }
    }

    C#

    Para enviar uma solicitação de prompt, crie um arquivo C# (.cs) e copie o código a seguir no arquivo. Defina your-project-id como o ID do projeto Google Cloud . Depois de atualizar os valores, execute o código.

    
    using Google.Cloud.AIPlatform.V1;
    using System;
    using System.Threading.Tasks;
    
    public class TextInputSample
    {
        public async Task<string> TextInput(
            string projectId = "your-project-id",
            string location = "us-central1",
            string publisher = "google",
            string model = "gemini-2.0-flash-001")
        {
    
            var predictionServiceClient = new PredictionServiceClientBuilder
            {
                Endpoint = $"{location}-aiplatform.googleapis.com"
            }.Build();
            string prompt = @"What's a good name for a flower shop that specializes in selling bouquets of dried flowers?";
    
            var generateContentRequest = new GenerateContentRequest
            {
                Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
                Contents =
                {
                    new Content
                    {
                        Role = "USER",
                        Parts =
                        {
                            new Part { Text = prompt }
                        }
                    }
                }
            };
    
            GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);
    
            string responseText = response.Candidates[0].Content.Parts[0].Text;
            Console.WriteLine(responseText);
    
            return responseText;
        }
    }
    

    REST

    Para enviar essa solicitação de comando, execute o comando curl na linha de comando ou inclua a chamada REST no seu aplicativo.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/publishers/google/models/${MODEL_ID}:generateContent -d \
    $'{
      "contents": {
        "role": "user",
        "parts": [
          {
            "text": "What\'s a good name for a flower shop that specializes in selling bouquets of dried flowers?"
          }
        ]
      }
    }'

    O modelo retorna uma resposta. A resposta é gerada em seções, e cada uma delas é avaliada separadamente quanto à segurança.

    Enviar um comando e uma imagem para a API Gemini na Vertex AI

    Use o código a seguir para enviar um comando que inclua texto e uma imagem para a API Gemini na Vertex AI. Este exemplo retorna uma descrição da imagem fornecida (imagem para amostra Java).

    Gen AI SDK for Python

    Instalar

    pip install --upgrade google-genai

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import HttpOptions, Part
    
    client = genai.Client(http_options=HttpOptions(api_version="v1"))
    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=[
            "What is shown in this image?",
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/image/scones.jpg",
                mime_type="image/jpeg",
            ),
        ],
    )
    print(response.text)
    # Example response:
    # The image shows a flat lay of blueberry scones arranged on parchment paper. There are ...

    Gen AI SDK for Go

    Saiba como instalar ou atualizar o Gen AI SDK for Go.

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    import (
    	"context"
    	"fmt"
    	"io"
    
    	genai "google.golang.org/genai"
    )
    
    // generateWithTextImage shows how to generate text using both text and image input
    func generateWithTextImage(w io.Writer) error {
    	ctx := context.Background()
    
    	client, err := genai.NewClient(ctx, &genai.ClientConfig{
    		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
    	})
    	if err != nil {
    		return fmt.Errorf("failed to create genai client: %w", err)
    	}
    
    	modelName := "gemini-2.0-flash-001"
    	contents := []*genai.Content{
    		{Parts: []*genai.Part{
    			{Text: "What is shown in this image?"},
    			{FileData: &genai.FileData{
    				// Image source: https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg
    				FileURI:  "gs://cloud-samples-data/generative-ai/image/scones.jpg",
    				MIMEType: "image/jpeg",
    			}},
    		}},
    	}
    
    	resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
    	if err != nil {
    		return fmt.Errorf("failed to generate content: %w", err)
    	}
    
    	respText, err := resp.Text()
    	if err != nil {
    		return fmt.Errorf("failed to convert model response to text: %w", err)
    	}
    	fmt.Fprintln(w, respText)
    
    	// Example response:
    	// The image shows an overhead shot of a rustic, artistic arrangement on a surface that ...
    
    	return nil
    }
    

    Gen AI SDK for Node.js

    Instalar

    npm install @google/genai

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    const {GoogleGenAI} = require('@google/genai');
    
    const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
    const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
    
    async function generateContent(
      projectId = GOOGLE_CLOUD_PROJECT,
      location = GOOGLE_CLOUD_LOCATION
    ) {
      const ai = new GoogleGenAI({
        vertexai: true,
        project: projectId,
        location: location,
      });
    
      const image = {
        fileData: {
          fileUri: 'gs://cloud-samples-data/generative-ai/image/scones.jpg',
          mimeType: 'image/jpeg',
        },
      };
    
      const response = await ai.models.generateContent({
        model: 'gemini-2.0-flash',
        contents: [image, 'What is shown in this image?'],
      });
    
      console.log(response.text);
    
      return response.text;
    }

    Gen AI SDK for Java

    Saiba como instalar ou atualizar o Gen AI SDK for Java.

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    
    import com.google.genai.Client;
    import com.google.genai.types.Content;
    import com.google.genai.types.GenerateContentResponse;
    import com.google.genai.types.HttpOptions;
    import com.google.genai.types.Part;
    
    public class GenerateContentWithTextAndImage {
    
      public static void main(String[] args) {
        // TODO(developer): Replace these variables before running the sample.
        String modelId = "gemini-2.0-flash";
        generateContent(modelId);
      }
    
      public static String generateContent(String modelId) {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (Client client = Client.builder()
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {
    
          GenerateContentResponse response =
              client.models.generateContent(modelId, Content.fromParts(
                      Part.fromText("What is shown in this image?"),
                      Part.fromUri("gs://cloud-samples-data/generative-ai/image/scones.jpg", "image/jpeg")),
                  null);
    
          System.out.print(response.text());
          // Example response:
          // The image shows a flat lay of blueberry scones arranged on parchment paper. There are ...
          return response.text();
        }
      }
    }

    C#

    Para enviar uma solicitação de prompt, crie um arquivo C# (.cs) e copie o código a seguir no arquivo. Defina your-project-id como o ID do projeto Google Cloud . Depois de atualizar os valores, execute o código.

    
    using Google.Api.Gax.Grpc;
    using Google.Cloud.AIPlatform.V1;
    using System.Text;
    using System.Threading.Tasks;
    
    public class GeminiQuickstart
    {
        public async Task<string> GenerateContent(
            string projectId = "your-project-id",
            string location = "us-central1",
            string publisher = "google",
            string model = "gemini-2.0-flash-001"
        )
        {
            // Create client
            var predictionServiceClient = new PredictionServiceClientBuilder
            {
                Endpoint = $"{location}-aiplatform.googleapis.com"
            }.Build();
    
            // Initialize content request
            var generateContentRequest = new GenerateContentRequest
            {
                Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
                GenerationConfig = new GenerationConfig
                {
                    Temperature = 0.4f,
                    TopP = 1,
                    TopK = 32,
                    MaxOutputTokens = 2048
                },
                Contents =
                {
                    new Content
                    {
                        Role = "USER",
                        Parts =
                        {
                            new Part { Text = "What's in this photo?" },
                            new Part { FileData = new() { MimeType = "image/png", FileUri = "gs://generativeai-downloads/images/scones.jpg" } }
                        }
                    }
                }
            };
    
            // Make the request, returning a streaming response
            using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);
    
            StringBuilder fullText = new();
    
            // Read streaming responses from server until complete
            AsyncResponseStream<GenerateContentResponse> responseStream = response.GetResponseStream();
            await foreach (GenerateContentResponse responseItem in responseStream)
            {
                fullText.Append(responseItem.Candidates[0].Content.Parts[0].Text);
            }
    
            return fullText.ToString();
        }
    }
    

    REST

    É possível enviar essa solicitação de prompt do seu ambiente de desenvolvimento integrado ou incorporar a chamada REST ao aplicativo quando apropriado.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/publishers/google/models/${MODEL_ID}:generateContent -d \
    $'{
      "contents": {
        "role": "user",
        "parts": [
          {
          "fileData": {
            "mimeType": "image/jpeg",
            "fileUri": "gs://generativeai-downloads/images/scones.jpg"
            }
          },
          {
            "text": "Describe this picture."
          }
        ]
      }
    }'

    O modelo retorna uma resposta. A resposta é gerada em seções, e cada uma delas é avaliada separadamente quanto à segurança.

    Enviar um comando e um vídeo para a API Gemini na Vertex AI

    Use o código a seguir para enviar um comando que inclua texto, áudio e vídeo para a API Gemini na Vertex AI. Essa amostra retorna uma descrição do vídeo fornecido, incluindo qualquer coisa importante da faixa de áudio.

    É possível enviar essa solicitação de comando usando a linha de comando, o ambiente de desenvolvimento integrado ou incluindo a chamada REST no aplicativo.

    Gen AI SDK for Python

    Instalar

    pip install --upgrade google-genai

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import HttpOptions, Part
    
    client = genai.Client(http_options=HttpOptions(api_version="v1"))
    prompt = """
    Analyze the provided video file, including its audio.
    Summarize the main points of the video concisely.
    Create a chapter breakdown with timestamps for key sections or topics discussed.
    """
    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=[
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
                mime_type="video/mp4",
            ),
            prompt,
        ],
    )
    
    print(response.text)
    # Example response:
    # Here's a breakdown of the video:
    #
    # **Summary:**
    #
    # Saeka Shimada, a photographer in Tokyo, uses the Google Pixel 8 Pro's "Video Boost" feature to ...
    #
    # **Chapter Breakdown with Timestamps:**
    #
    # * **[00:00-00:12] Introduction & Tokyo at Night:** Saeka Shimada introduces herself ...
    # ...

    Gen AI SDK for Go

    Saiba como instalar ou atualizar o Gen AI SDK for Go.

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    import (
    	"context"
    	"fmt"
    	"io"
    
    	genai "google.golang.org/genai"
    )
    
    // generateWithVideo shows how to generate text using a video input.
    func generateWithVideo(w io.Writer) error {
    	ctx := context.Background()
    
    	client, err := genai.NewClient(ctx, &genai.ClientConfig{
    		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
    	})
    	if err != nil {
    		return fmt.Errorf("failed to create genai client: %w", err)
    	}
    
    	modelName := "gemini-2.0-flash-001"
    	contents := []*genai.Content{
    		{Parts: []*genai.Part{
    			{Text: `Analyze the provided video file, including its audio.
    Summarize the main points of the video concisely.
    Create a chapter breakdown with timestamps for key sections or topics discussed.`},
    			{FileData: &genai.FileData{
    				FileURI:  "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
    				MIMEType: "video/mp4",
    			}},
    		}},
    	}
    
    	resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
    	if err != nil {
    		return fmt.Errorf("failed to generate content: %w", err)
    	}
    
    	respText, err := resp.Text()
    	if err != nil {
    		return fmt.Errorf("failed to convert model response to text: %w", err)
    	}
    	fmt.Fprintln(w, respText)
    
    	// Example response:
    	// Here's an analysis of the provided video file:
    	//
    	// **Summary**
    	//
    	// The video features Saeka Shimada, a photographer in Tokyo, who uses the new Pixel phone ...
    	//
    	// **Chapter Breakdown**
    	//
    	// *   **0:00-0:05**: Introduction to Saeka Shimada and her work as a photographer in Tokyo.
    	// ...
    
    	return nil
    }
    

    Gen AI SDK for Node.js

    Instalar

    npm install @google/genai

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    const {GoogleGenAI} = require('@google/genai');
    
    const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
    const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
    
    async function generateContent(
      projectId = GOOGLE_CLOUD_PROJECT,
      location = GOOGLE_CLOUD_LOCATION
    ) {
      const ai = new GoogleGenAI({
        vertexai: true,
        project: projectId,
        location: location,
      });
    
      const prompt = `
      Analyze the provided video file, including its audio.
      Summarize the main points of the video concisely.
      Create a chapter breakdown with timestamps for key sections or topics discussed.
     `;
    
      const video = {
        fileData: {
          fileUri: 'gs://cloud-samples-data/generative-ai/video/pixel8.mp4',
          mimeType: 'video/mp4',
        },
      };
    
      const response = await ai.models.generateContent({
        model: 'gemini-2.0-flash',
        contents: [video, prompt],
      });
    
      console.log(response.text);
    
      return response.text;
    }

    Gen AI SDK for Java

    Saiba como instalar ou atualizar o Gen AI SDK for Java.

    Para saber mais, consulte a documentação de referência do SDK.

    Defina variáveis de ambiente para usar o SDK de IA generativa com a Vertex AI:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    
    import com.google.genai.Client;
    import com.google.genai.types.Content;
    import com.google.genai.types.GenerateContentResponse;
    import com.google.genai.types.HttpOptions;
    import com.google.genai.types.Part;
    
    public class GenerateContentWithVideo {
    
      public static void main(String[] args) {
        // TODO(developer): Replace these variables before running the sample.
        String modelId = "gemini-2.0-flash";
        String prompt = " Analyze the provided video file, including its audio.\n"
            + "    Summarize the main points of the video concisely.\n"
            + "    Create a chapter breakdown with timestamps for key sections or topics discussed.";
        generateContent(modelId, prompt);
      }
    
      public static String generateContent(String modelId, String prompt) {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (Client client = Client.builder()
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {
    
          GenerateContentResponse response =
              client.models.generateContent(modelId, Content.fromParts(
                      Part.fromText(prompt),
                      Part.fromUri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4", "video/mp4")),
                  null);
    
          System.out.print(response.text());
          // Example response:
          // Here's a breakdown of the video:
          //
          // **Summary:**
          //
          // Saeka Shimada, a photographer in Tokyo, uses the Google Pixel 8 Pro's "Video Boost" feature
          // to ...
          //
          // **Chapter Breakdown with Timestamps:**
          //
          // * **[00:00-00:12] Introduction & Tokyo at Night:** Saeka Shimada introduces herself ...
          return response.text();
        }
      }
    }

    C#

    Para enviar uma solicitação de prompt, crie um arquivo C# (.cs) e copie o código a seguir no arquivo. Defina your-project-id como o ID do projeto Google Cloud . Depois de atualizar os valores, execute o código.

    
    using Google.Cloud.AIPlatform.V1;
    using System;
    using System.Threading.Tasks;
    
    public class VideoInputWithAudio
    {
        public async Task<string> DescribeVideo(
            string projectId = "your-project-id",
            string location = "us-central1",
            string publisher = "google",
            string model = "gemini-2.0-flash-001")
        {
    
            var predictionServiceClient = new PredictionServiceClientBuilder
            {
                Endpoint = $"{location}-aiplatform.googleapis.com"
            }.Build();
    
            string prompt = @"Provide a description of the video.
    The description should also contain anything important which people say in the video.";
    
            var generateContentRequest = new GenerateContentRequest
            {
                Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
                Contents =
                {
                    new Content
                    {
                        Role = "USER",
                        Parts =
                        {
                            new Part { Text = prompt },
                            new Part { FileData = new() { MimeType = "video/mp4", FileUri = "gs://cloud-samples-data/generative-ai/video/pixel8.mp4" }}
                        }
                    }
                }
            };
    
            GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);
    
            string responseText = response.Candidates[0].Content.Parts[0].Text;
            Console.WriteLine(responseText);
    
            return responseText;
        }
    }
    

    REST

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/publishers/google/models/${MODEL_ID}:generateContent -d \
    $'{
      "contents": {
        "role": "user",
        "parts": [
          {
          "fileData": {
            "mimeType": "video/mp4",
            "fileUri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4"
            }
          },
          {
            "text": "Provide a description of the video. The description should also contain anything important which people say in the video."
          }
        ]
      }
    }'

    O modelo retorna uma resposta. A resposta é gerada em seções, e cada uma delas é avaliada separadamente quanto à segurança.

    A seguir