トークンを理解してカウントする

Gemini やその他の生成 AI モデルは、入力と出力をトークンという粒度で処理します。

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

トークンについて

トークンは、z などの単一の文字、cat などの単語全体にすることができます。長い単語は複数のトークンに分割されます。モデルで使用されるすべてのトークンのセットを語彙と呼び、テキストをトークンに分割するプロセスをトークン化と呼びます。

課金が有効になっている場合、Gemini API の呼び出しの費用は 入力トークンと出力トークンの数によって決まります。そのため、トークンの カウント方法を知っておくと便利です。

トークンをカウントする

Gemini API とのすべての入出力は、テキスト、画像ファイル、その他のテキスト以外のモダリティを含めてトークン化されます。

トークンは次の方法でカウントできます。

  • リクエストの入力で count_tokens を呼び出します。入力のみのトークンの合計数を返します。 リクエストのサイズを確認するには、入力を送信する前にこの呼び出しを行います。

  • インタラクション レスポンスで usage を使用します。入力(total_input_tokens)、出力(total_output_tokens)、思考(total_thought_tokens)、キャッシュされたコンテンツ(total_cached_tokens)、ツール使用(total_tool_use_tokens)、合計(total_tokens)のトークン数を返します。

テキスト トークンをカウントする

Python

# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()
prompt = "The quick brown fox jumps over the lazy dog."

# Count tokens before sending
total_tokens = client.models.count_tokens(
    model="gemini-3.6-flash",
    contents=prompt
)
print("total_tokens:", total_tokens.total_tokens)

# Get usage from interaction
interaction = client.interactions.create(
    model="gemini-3.6-flash",
    input=prompt
)
print(interaction.usage)

JavaScript

// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});
const prompt = "The quick brown fox jumps over the lazy dog.";

// Count tokens before sending
const countResponse = await client.models.countTokens({
    model: "gemini-3.6-flash",
    contents: prompt,
});
console.log(countResponse.totalTokens);

// Get usage from interaction
const interaction = await client.interactions