CountTokens API

CountTokens API は、Gemini API にリクエストを送信する前に入力トークンの数を計算します。

CountTokens API を使用して、リクエストがモデルのコンテキスト ウィンドウを超えないようにし、課金対象の文字に基づいて潜在的な費用を見積もります。

CountTokens API では、Gemini API 推論リクエストと同じ contents パラメータを使用できます。

サポートされているモデル:

モデル コード
Gemini 1.5 Flash gemini-1.5-flash-002
gemini-1.5-flash-001
gemini-1.5-flash-preview-0514
Gemini 1.5 Pro gemini-1.5-pro-002
gemini-1.5-pro-001
gemini-1.5-pro-preview-0514
Gemini 1.0 Pro Vision gemini-1.0-pro-vision
gemini-1.0-pro-vision-001
Gemini 1.0 Pro gemini-1.0-pro
gemini-1.0-pro-001
gemini-1.0-pro-002
Gemini Experimental gemini-experimental

制限事項:

gemini-1.0-pro-vision-001gemini-1.0-ultra-vision-001 は、動画入力に固定数のトークンを使用します。

構文の例

トークン数を計算するリクエストを送信する構文。

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \

https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:countTokens \
-d '{
  "contents": [{
    ...
  }],
  "system_instruction": {
  "role": "...",
  "parts": [{
      ...
    }],
  "tools": [{
      "function_declarations": [{
        ...
      }]
    }],
  }
}'

Python

gemini_model = GenerativeModel(MODEL_ID)
model_response = gemini_model.count_tokens([...])

パラメータ リスト

このクラスは、roleparts という 2 つの主要なプロパティで構成されています。role プロパティはコンテンツを生成している個人を表し、parts プロパティには複数の要素が含まれます。各要素はメッセージ内のデータ セグメントを表します。

パラメータ

role

省略可: string

メッセージを作成するエンティティの ID。文字列を次のいずれかに設定します。

  • user: メッセージが実際のユーザーから送信されたことを示します。たとえば、ユーザーが生成したメッセージなどです。
  • model: メッセージがモデルによって生成されたことを示します。

model 値は、マルチターンの会話中にモデルからのメッセージを会話に挿入するために使用されます。

マルチターンではない会話の場合、このフィールドは空白のままにするか、未設定のままにできます。

parts

part

1 つのメッセージを構成する順序付きのパーツのリスト。パーツによって IANA MIME タイプが異なる場合があります。

Part

マルチパート Content メッセージの一部であるメディアを含むデータ型。

パラメータ

text

省略可: string

テキスト プロンプトまたはコード スニペット。

inline_data

省略可: Blob

未加工バイトのデータがインラインに含まれます。

file_data

省略可: FileData

ファイルに保存されたデータ。

Blob

コンテンツ blob。可能であれば、元のバイトではなくテキストとして送信します。

パラメータ

mime_type

string

データの IANA MIME タイプ

data

bytes

元のバイト。

FileData

URI ベースのデータ。

パラメータ

mime_type

string

データの IANA MIME タイプ

file_uri

string

データを格納するファイルの Cloud Storage URI。

system_instruction

このフィールドは、ユーザーが指定した system_instructions 用です。contents と同じですが、サポートされるコンテンツ タイプが限定されています。

パラメータ

role

string

データの IANA MIME タイプ。このフィールドは内部では無視されます。

parts

Part

テキストのみ。ユーザーがモデルに渡す指示。

FunctionDeclaration

OpenAPI 3.0 仕様で定義されている関数宣言の構造化表現。モデルが JSON 入力を生成できる関数を表します。

パラメータ

name

string

呼び出す関数の名前。

description

省略可: string

関数の説明と目的。

parameters

省略可: Schema

関数のパラメータを OpenAPI JSON スキーマ オブジェクト形式(OpenAPI 3.0 仕様)で記述します。

response

省略可: Schema

関数からの出力を OpenAPI JSON スキーマ オブジェクト形式(OpenAPI 3.0 仕様)で記述します。

テキスト プロンプトからトークン数を取得する

この例では、単一のテキスト プロンプトのトークンをカウントします。

REST

Vertex AI API を使用して、プロンプトのトークン数と請求対象文字数を取得するには、パブリッシャー モデル エンドポイントに POST リクエストを送信します。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION: リクエストを処理するリージョン。使用できる選択肢は以下のとおりです。

    クリックして、利用可能なリージョンの一部を開く

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: 実際のプロジェクト ID
  • MODEL_ID: 使用するマルチモーダル モデルのモデル ID。
  • ROLE: コンテンツに関連付けられた会話におけるロール。単一ターンのユースケースでも、ロールの指定が必要です。指定できる値は以下のとおりです。
    • USER: 送信するコンテンツを指定します。
  • TEXT: プロンプトに含める指示のテキスト。
  • NAME: 呼び出す関数の名前。
  • DESCRIPTION: 関数の説明と目的。

HTTP メソッドと URL:

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

リクエストの本文(JSON):

{
  "contents": [{
    "role": "ROLE",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "system_instruction": {
    "role": "ROLE",
    "parts": [{
      "text": "TEXT"
    }]
  }
  "tools": [{
    "function_declarations": [
      {
        "name": "NAME",
        "description": "DESCRIPTION",
        "parameters": {
          "type": "OBJECT",
          "properties": {
            "location": {
              "type": "TYPE",
              "description": "DESCRIPTION"
            }
          },
          "required": [
            "location"
          ]
        }
      }
    ]
  }]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$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

次のような JSON レスポンスが返されます。

Python

import vertexai
from vertexai.generative_models import GenerativeModel

# TODO (developer): update project_id
vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel("gemini-1.5-flash-002")

prompt = "Why is the sky blue?"
# Prompt tokens count
response = model.count_tokens(prompt)
print(f"Prompt Token Count: {response.total_tokens}")
print(f"Prompt Character Count: {response.total_billable_characters}")

# Send text to Gemini
response = model.generate_content(prompt)

# Response tokens count
usage_metadata = response.usage_metadata
print(f"Prompt Token Count: {usage_metadata.prompt_token_count}")
print(f"Candidates Token Count: {usage_metadata.candidates_token_count}")
print(f"Total Token Count: {usage_metadata.total_token_count}")

NodeJS

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

Java

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-1.5-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;
    }
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// countTokens returns the number of tokens for this prompt.
func countTokens(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-flash-001"

	ctx := context.Background()
	prompt := genai.Text("Why is the sky blue?")

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	resp, err := model.CountTokens(ctx, prompt)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Number of tokens for the prompt: %d\n", resp.TotalTokens)

	resp2, err := model.GenerateContent(ctx, prompt)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Number of tokens for the prompt: %d\n", resp2.UsageMetadata.PromptTokenCount)
	fmt.Fprintf(w, "Number of tokens for the candidates: %d\n", resp2.UsageMetadata.CandidatesTokenCount)
	fmt.Fprintf(w, "Total number of tokens: %d\n", resp2.UsageMetadata.TotalTokenCount)

	return nil
}

メディア プロンプトからトークン数を取得する

この例では、さまざまなメディアタイプを使用するプロンプトのトークンをカウントします。

REST

Vertex AI API を使用して、プロンプトのトークン数と請求対象文字数を取得するには、パブリッシャー モデル エンドポイントに POST リクエストを送信します。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION: リクエストを処理するリージョン。使用できる選択肢は以下のとおりです。

    クリックして、利用可能なリージョンの一部を開く

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: 実際のプロジェクト ID
  • MODEL_ID: 使用するマルチモーダル モデルのモデル ID。
  • ROLE: コンテンツに関連付けられた会話におけるロール。単一ターンのユースケースでも、ロールの指定が必要です。指定できる値は以下のとおりです。
    • USER: 送信するコンテンツを指定します。
  • TEXT: プロンプトに含める指示のテキスト。
  • FILE_URI: プロンプトに含めるファイルの URI または URL。指定できる値は以下のとおりです。
    • Cloud Storage バケット URI: オブジェクトは一般公開されているか、リクエストを送信するプロジェクトと同じ Google Cloud プロジェクトに存在している必要があります。
    • HTTP URL: ファイルの URL は一般公開されている必要があります。リクエストごとに 1 つの動画ファイルと最大 10 個の画像ファイルを指定できます。音声ファイルとドキュメントのサイズは 15 MB 以下にする必要があります。
    • YouTube 動画の URL: YouTube 動画は、Google Cloud コンソールのログインに使用したアカウントが所有しているか、公開されている必要があります。リクエストごとにサポートされる YouTube 動画の URL は 1 つだけです。

    fileURI を指定する場合は、ファイルのメディアタイプ(mimeType)も指定する必要があります。

  • MIME_TYPE: data フィールドまたは fileUri フィールドで指定されたファイルのメディアタイプ。指定できる値は次のとおりです。

    クリックして MIME タイプを開く

    • application/pdf
    • audio/mpeg
    • audio/mp3
    • audio/wav
    • image/png
    • image/jpeg
    • image/webp
    • text/plain
    • video/mov
    • video/mpeg
    • video/mp4
    • video/mpg
    • video/avi
    • video/wmv
    • video/mpegps
    • video/flv

HTTP メソッドと URL:

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

リクエストの本文(JSON):

{
  "contents": [{
    "role": "ROLE",
    "parts": [
      {
        "file_data": {
          "file_uri": "FILE_URI",
          "mime_type": "MIME_TYPE"
        }
      },
      {
        "text": "TEXT
      }
    ]
  }]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$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

次のような JSON レスポンスが返されます。

Python

import vertexai
from vertexai.generative_models import GenerativeModel, Part

# TODO (developer): update project_id
vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel("gemini-1.5-flash-002")

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

# Prompt tokens count
response = model.count_tokens(contents)
print(f"Prompt Token Count: {response.total_tokens}")
print(f"Prompt Character Count: {response.total_billable_characters}")

# Send text to Gemini
response = model.generate_content(contents)
usage_metadata = response.usage_metadata

# Response tokens count
print(f"Prompt Token Count: {usage_metadata.prompt_token_count}")
print(f"Candidates Token Count: {usage_metadata.candidates_token_count}")
print(f"Total Token Count: {usage_metadata.total_token_count}")

NodeJS

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

Java

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-1.5-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;
    }
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"mime"
	"path/filepath"

	"cloud.google.com/go/vertexai/genai"
)

// countTokensMultimodal finds the number of tokens for a multimodal prompt (video+text), and writes to w. Then,
// it calls the model with the multimodal prompt and writes token counts from the response metadata to w.
//
// video is a Google Cloud Storage path starting with "gs://"
func countTokensMultimodal(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-flash-001"
	prompt := "Provide a description of the video."
	video := "gs://cloud-samples-data/generative-ai/video/pixel8.mp4"

	ctx := context.Background()

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	part1 := genai.Text(prompt)

	// Given a video file URL, prepare video file as genai.Part
	part2 := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext(video)),
		FileURI:  video,
	}

	// Finds the total number of tokens for the 2 parts (text, video) of the multimodal prompt,
	// before actually calling the model for inference.
	resp, err := model.CountTokens(ctx, part1, part2)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Number of tokens for the multimodal video prompt: %d\n", resp.TotalTokens)

	res, err := model.GenerateContent(ctx, part1, part2)
	if err != nil {
		return fmt.Errorf("unable to generate contents: %w", err)
	}

	// The token counts are also provided in the model response metadata, after inference.
	fmt.Fprintln(w, "\nModel response")
	md := res.UsageMetadata
	fmt.Fprintf(w, "Prompt Token Count: %d\n", md.PromptTokenCount)
	fmt.Fprintf(w, "Candidates Token Count: %d\n", md.CandidatesTokenCount)
	fmt.Fprintf(w, "Total Token Count: %d\n", md.TotalTokenCount)

	return nil
}

次のステップ

  • 詳細については、Gemini API をご覧ください。