Gemini モデルのトークンと課金対象文字数をカウントする

生成モデルは、データをトークンという単位に分割して処理します。各モデルには、プロンプトとレスポンスで処理できるトークンの最大数があります。

このページでは、Count Tokens API を使用して、Gemini モデルへのリクエストのトークン数と課金対象文字数の見積もりを取得する方法について説明します。レスポンス内のトークンの見積もりを取得するための API はありません。

Count Tokens API は Imagen モデルでは使用できません。

カウントにはどのような情報が表示されますか?

トークンと課金対象文字数のカウントについては、次の点に注意してください。

  • トークンの合計数をカウントする

    • このカウントは、リクエストが許容されるコンテキスト ウィンドウを超えないようにするのに役立ちます。

    • トークン数は、リクエスト入力の一部として提供されるすべてのファイル(画像など)のサイズを反映します。画像数や動画の秒数はカウントされません。

    • すべての Gemini モデルの場合、1 個のトークンは約 4 文字に相当します。100 個のトークンは、約 60 ~ 80 ワード(英語)です。

  • 課金対象文字数の合計をカウントする

    • Vertex AI では文字数が料金計算の一部であるため、このカウントは費用の把握と管理に役立ちます。

    • 課金対象の文字数は、リクエスト入力の一部として提供される text の文字数を反映します。

古い Gemini モデルの場合、トークンは料金計算の対象外ですが、Gemini 2.0 モデルと Gemini 2.5 モデルの場合、トークンは料金計算に使用されます。モデルごとのトークン上限モデルごとの料金の詳細を確認する。

トークンと課金対象文字数のカウントの料金と割り当て

CountTokens API の使用に料金や割り当ての制限はありません。CountTokens API の最大割り当ては、1 分あたり 3,000 リクエスト(RPM)です。

コードサンプル

テキストのみの入力

Swift

let response = try await model.countTokens("Write a story about a magic backpack.")
print("Total Tokens: \(response.totalTokens)")
print("Total Billable Characters: \(response.totalBillableCharacters)")

Kotlin

val response = generativeModel.countTokens("Write a story about a magic backpack.")
println("Total Tokens: ${response.totalTokens}")
println("Total Billable Characters: ${response.totalBillableCharacters}")

Java

Content prompt = new Content.Builder()
        .addText("Write a story about a magic backpack.")
        .build();

GenerativeModelFutures modelFutures = GenerativeModelFutures.from(model);
ListenableFuture countTokensResponse =
        modelFutures.countTokens(prompt);

Futures.addCallback(countTokensResponse, new FutureCallback() {
    @Override
    public void onSuccess(CountTokensResponse response) {
        System.out.println("Total Tokens = " + response.getTotalTokens());
        System.out.println("Total Billable Characters: = " +
                response.getTotalBillableCharacters());
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

const { totalTokens, totalBillableCharacters } = await model.countTokens("Write a story about a magic backpack.");
console.log(`Total tokens: ${totalTokens}, total billable characters: ${totalBillableCharacters}`);

Dart

final tokenCount = await model.countTokens(Content.text("Write a story about a magic backpack."));
print('Token count: ${tokenCount.totalTokens}, billable characters: ${tokenCount.totalBillableCharacters}');

Unity

var response = await model.CountTokensAsync("Write a story about a magic backpack.");
UnityEngine.Debug.Log($"Total Tokens: {response.TotalTokens}");
UnityEngine.Debug.Log($"Total Billable Characters: {response.TotalBillableCharacters}");

マルチモーダル入力

Swift

let response = try await model.countTokens(image, "What's in this picture?")
print("Total Tokens: \(response.totalTokens)")
print("Total Billable Characters: \(response.totalBillableCharacters)")

Kotlin

val prompt = content {
  image(bitmap)
  text("What's in this picture?")
}
val response = generativeModel.countTokens(prompt)
println("Total Tokens: ${response.totalTokens}")
println("Total Billable Characters: ${response.totalBillableCharacters}")

Java

Content prompt = new Content.Builder()
        .addImage(bitmap)
        .addText("What's in this picture?")
        .build();

GenerativeModelFutures modelFutures = GenerativeModelFutures.from(model);
ListenableFuture countTokensResponse =
        modelFutures.countTokens(prompt);

Futures.addCallback(countTokensResponse, new FutureCallback() {
    @Override
    public void onSuccess(CountTokensResponse response) {
        System.out.println("Total Tokens = " + response.getTotalTokens());
        System.out.println("Total Billable Characters: = " +
                response.getTotalBillableCharacters());
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

const prompt = "What's in this picture?";
const imagePart = { inlineData: { mimeType: 'image/jpeg', data: imageAsBase64 }};

const { totalTokens, totalBillableCharacters } = await model.countTokens([prompt, imagePart]);
console.log(`Total tokens: ${totalTokens}, total billable characters: ${totalBillableCharacters}`);

Dart

final prompt = TextPart("What's in the picture?");
final tokenCount = await model.countTokens([
  Content.multi([prompt, imagePart])
]);
print('Token count: ${tokenCount.totalTokens}, billable characters: ${tokenCount.totalBillableCharacters}');

Unity

var response = await model.CountTokensAsync(new [] {
  ModelContent.Text("What's in this picture?"),
  ModelContent.InlineData("image/png", imageData)
});
UnityEngine.Debug.Log($"Total Tokens: {response.TotalTokens}");
UnityEngine.Debug.Log($"Total Billable Characters: {response.TotalBillableCharacters}");