Usar a API Count Tokens

Nesta página, mostramos como receber a contagem de tokens e o número de caracteres faturáveis de um comando usando a API countTokens.

Modelos compatíveis

Os modelos multimodais a seguir são compatíveis com a estimativa da contagem de tokens de solicitação:

Para saber mais sobre versões de modelo, consulte Versões do modelo Genmini e ciclo de vida.

Receber a contagem de tokens de um comando

É possível receber a contagem estimada de tokens e o número de caracteres faturáveis de um comando usando a API do Vertex AI.

Console

Para conferir a contagem de tokens de um comando usando o Vertex AI Studio no consoleGoogle Cloud , siga estas etapas:

  1. Na seção "Vertex AI" do console Google Cloud , acesse a página do Vertex AI Studio.

    Acessar o Vertex AI Studio

  2. Clique em Abrir em formato livre ou Abrir chat.
  3. O número de tokens é calculado e exibido conforme você digita no painel Comando. Ele inclui o número de tokens em qualquer arquivo de entrada.
  4. Para conferir mais detalhes, clique em <count> tokens para abrir o Tokenizer de comando.
    • Para ver os tokens no comando de texto destacados com cores diferentes marcando o limite de cada ID de token, clique em ID do token para texto. Tokens de mídia não são aceitos.
    • Para acessar os IDs de token, clique em ID do token.

      Para fechar o painel da ferramenta tokenizadora, clique em X ou clique fora do painel.

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 da 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.count_tokens(
    model="gemini-2.0-flash-001",
    contents="What's the highest mountain in Africa?",
)
print(response)
# Example output:
# total_tokens=10
# cached_content_token_count=None

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 da 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"
)

// countWithTxt shows how to count tokens with text input.
func countWithTxt(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's the highest mountain in Africa?"},
		}},
	}

	resp, err := client.Models.CountTokens(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	fmt.Fprintf(w, "Total: %d\nCached: %d\n", resp.TotalTokens, resp.CachedContentTokenCount)

	// Example response:
	// Total: 9
	// Cached: 0

	return nil
}
const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function countTokens(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-2.0-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const req = {
    contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}],
  };

  // Prompt tokens count
  const countTokensResp = await generativeModel.countTokens(req);
  console.log('Prompt tokens count: ', countTokensResp);

  // Send text to gemini
  const result = await generativeModel.generateContent(req);

  // Response tokens count
  const usageMetadata = result.response.usageMetadata;
  console.log('Response tokens count: ', usageMetadata);
}
import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.CountTokensResponse;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import java.io.IOException;

public class GetTokenCount {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-2.0-flash-001";

    getTokenCount(projectId, location, modelName);
  }

  // Gets the number of tokens for the prompt and the model's response.
  public static int getTokenCount(String projectId, String location, String modelName)
      throws IOException {
    // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) {
      GenerativeModel model = new GenerativeModel(modelName, vertexAI);

      String textPrompt = "Why is the sky blue?";
      CountTokensResponse response = model.countTokens(textPrompt);

      int promptTokenCount = response.getTotalTokens();
      int promptCharCount = response.getTotalBillableCharacters();

      System.out.println("Prompt token Count: " + promptTokenCount);
      System.out.println("Prompt billable character count: " + promptCharCount);

      GenerateContentResponse contentResponse = model.generateContent(textPrompt);

      int tokenCount = contentResponse.getUsageMetadata().getPromptTokenCount();
      int candidateTokenCount = contentResponse.getUsageMetadata().getCandidatesTokenCount();
      int totalTokenCount = contentResponse.getUsageMetadata().getTotalTokenCount();

      System.out.println("Prompt token Count: " + tokenCount);
      System.out.println("Candidate Token Count: " + candidateTokenCount);
      System.out.println("Total token Count: " + totalTokenCount);

      return promptTokenCount;
    }
  }
}

REST

Para conferir a contagem de tokens e o número de caracteres faturáveis de um comando usando a API do Vertex AI, envie uma solicitação POST para o endpoint do modelo do editor.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • LOCATION: a região para processar a solicitação. As opções disponíveis incluem:

    Clicar para abrir uma lista parcial das regiões disponíveis

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: o ID do projeto.
  • MODEL_ID: o ID do modelo multimodal que você quer usar.
  • ROLE: o papel em uma conversa associada ao conteúdo. É necessário especificar um papel mesmo em casos de uso de turno único. Os valores aceitáveis são os seguintes:
    • USER: especifica o conteúdo que é enviado por você.
  • TEXT: as instruções de texto a serem incluídas no comando.

Método HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:countTokens

Corpo JSON da solicitação:

{
  "contents": [{
    "role": "ROLE",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:countTokens"

PowerShell

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:countTokens" | Select-Object -Expand Content

Você receberá uma resposta JSON semelhante a seguinte.

Exemplo de texto com imagem ou vídeo:

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 da 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"))

contents = [
    Part.from_uri(
        file_uri="gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
        mime_type="video/mp4",
    ),
    "Provide a description of the video.",
]

response = client.models.count_tokens(
    model="gemini-2.0-flash-001",
    contents=contents,
)
print(response)
# Example output:
# total_tokens=16252 cached_content_token_count=None

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 da 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"
)

// countWithTxtAndVid shows how to count tokens with text and video inputs.
func countWithTxtAndVid(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: "Provide a description of the video."},
			{FileData: &genai.FileData{
				FileURI:  "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
				MIMEType: "video/mp4",
			}},
		}},
	}

	resp, err := client.Models.CountTokens(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	fmt.Fprintf(w, "Total: %d\nCached: %d\n", resp.TotalTokens, resp.CachedContentTokenCount)

	// Example response:
	// Total: 16252
	// Cached: 0

	return nil
}
const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function countTokens(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-2.0-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const req = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            file_data: {
              file_uri:
                'gs://cloud-samples-data/generative-ai/video/pixel8.mp4',
              mime_type: 'video/mp4',
            },
          },
          {text: 'Provide a description of the video.'},
        ],
      },
    ],
  };

  const countTokensResp = await generativeModel.countTokens(req);
  console.log('Prompt Token Count:', countTokensResp.totalTokens);
  console.log(
    'Prompt Character Count:',
    countTokensResp.totalBillableCharacters
  );

  // Sent text to Gemini
  const result = await generativeModel.generateContent(req);
  const usageMetadata = result.response.usageMetadata;

  console.log('Prompt Token Count:', usageMetadata.promptTokenCount);
  console.log('Candidates Token Count:', usageMetadata.candidatesTokenCount);
  console.log('Total Token Count:', usageMetadata.totalTokenCount);
}
import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Content;
import com.google.cloud.vertexai.api.CountTokensResponse;
import com.google.cloud.vertexai.generativeai.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import java.io.IOException;

public class GetMediaTokenCount {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-2.0-flash-001";

    getMediaTokenCount(projectId, location, modelName);
  }

  // Gets the number of tokens for the prompt with text and video and the model's response.
  public static int getMediaTokenCount(String projectId, String location, String modelName)
      throws IOException {
    // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) {
      GenerativeModel model = new GenerativeModel(modelName, vertexAI);

      Content content = ContentMaker.fromMultiModalData(
          "Provide a description of the video.",
          PartMaker.fromMimeTypeAndData(
              "video/mp4", "gs://cloud-samples-data/generative-ai/video/pixel8.mp4")
      );

      CountTokensResponse response = model.countTokens(content);

      int tokenCount = response.getTotalTokens();
      System.out.println("Token count: " + tokenCount);

      return tokenCount;
    }
  }
}

REST

Para conferir a contagem de tokens e o número de caracteres faturáveis de um comando usando a API do Vertex AI, envie uma solicitação POST para o endpoint do modelo do editor.

MODEL_ID="gemini-2.0-flash-001"
PROJECT_ID="my-project"
TEXT="Provide a summary with about two sentences for the following article."
REGION="us-central1"

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:countTokens -d \
$'{
    "contents": [{
      "role": "user",
      "parts": [
        {
          "file_data": {
            "file_uri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4",
            "mime_type": "video/mp4"
          }
        },
        {
          "text": "'"$TEXT"'"
        }]
    }]
 }'

Preços e cotas

Não há cobrança ou restrição de cota para usar a API CountTokens. A cota máxima para a API CountTokens é de 3.000 solicitações por minuto.

A seguir