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


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

トークンについて

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

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

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

Colab でトークン数のカウントを試す

Colab を使用してトークン数を試すことができます。

ai.google.dev で表示 Colab ノートブックを試す GitHub でノートブックを表示

コンテキスト ウィンドウ

Gemini API で使用可能なモデルには、トークンで測定されるコンテキスト ウィンドウがあります。コンテキスト ウィンドウは、提供できる入力の量と、モデルが生成できる出力の量を定義します。コンテキスト ウィンドウのサイズは、getModels エンドポイントを呼び出すか、モデルのドキュメントで確認できます。

次の例では、gemini-1.5-flash モデルの入力上限が約 1,000,000 トークン、出力上限が約 8,000 トークンであることがわかります。つまり、コンテキスト ウィンドウは 1,000,000 トークンです。

from google import genai

client = genai.Client()
model_info = client.models.get(model="gemini-2.0-flash")
print(f"{model_info.input_token_limit=}")
print(f"{model_info.output_token_limit=}")
# ( e.g., input_token_limit=30720, output_token_limit=2048 )

トークンのカウント

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

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

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

from google import genai

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

# Count tokens using the new client method.
total_tokens = client.models.count_tokens(
    model="gemini-2.0-flash", contents=prompt
)
print("total_tokens: ", total_tokens)
# ( e.g., total_tokens: 10 )

response = client.models.generate_content(
    model="gemini-2.0-flash", contents=prompt
)

# The usage_metadata provides detailed token counts.
print(response.usage_metadata)
# ( e.g., prompt_token_count: 11, candidates_token_count: 73, total_token_count: 84 )

マルチターン(チャット)トークンをカウントする

from google import genai
from google.genai import types

client = genai.Client()

chat = client.chats.create(
    model="gemini-2.0-flash",
    history=[
        types.Content(
            role="user", parts=[types.Part(text="Hi my name is Bob")]
        ),
        types.Content(role="model", parts=[types.Part(text="Hi Bob!")]),
    ],
)
# Count tokens for the chat history.
print(
    client.models.count_tokens(
        model="gemini-2.0-flash", contents=chat.get_history()
    )
)
# ( e.g., total_tokens: 10 )

response = chat.send_message(
    message="In one sentence, explain how a computer works to a young child."
)
print(response.usage_metadata)
# ( e.g., prompt_token_count: 25, candidates_token_count: 21, total_token_count: 46 )

# You can count tokens for the combined history and a new message.
extra = types.UserContent(
    parts=[
        types.Part(
            text="What is the meaning of life?",
        )
    ]
)
history = chat.get_history()
history.append(extra)
print(client.models.count_tokens(model="gemini-2.0-flash", contents=history))
# ( e.g., total_tokens: 56 )

マルチモーダル トークンをカウントする

Gemini API へのすべての入力(テキスト、画像ファイル、その他のテキスト以外のモダリティを含む)はトークン化されます。Gemini API による処理中のマルチモーダル入力のトークン化に関する重要なポイントは次のとおりです。

  • Gemini 2.0 では、両方の寸法が 384 ピクセル以下の画像入力は 258 個のトークンとしてカウントされます。1 つまたは両方の寸法が大きい画像は、必要に応じて 768x768 ピクセルのタイルに切り抜かれ、スケーリングされます。各タイルは 258 個のトークンとしてカウントされます。Gemini 2.0 より前は、画像は固定の 258 個のトークンを使用していました。

  • 動画ファイルと音声ファイルは、次の固定レートでトークンに変換されます。動画は 1 秒あたり 263 トークン、音声は 1 秒あたり 32 トークン。

画像ファイル

File API からアップロードされた画像を使用する例:

from google import genai

client = genai.Client()
prompt = "Tell me about this image"
your_image_file = client.files.upload(file=media / "organ.jpg")

print(
    client.models.count_tokens(
        model="gemini-2.0-flash", contents=[prompt, your_image_file]
    )
)
# ( e.g., total_tokens: 263 )

response = client.models.generate_content(
    model="gemini-2.0-flash", contents=[prompt, your_image_file]
)
print(response.usage_metadata)
# ( e.g., prompt_token_count: 264, candidates_token_count: 80, total_token_count: 345 )

画像をインライン データとして提供する例:

from google import genai
import PIL.Image

client = genai.Client()
prompt = "Tell me about this image"
your_image_file = PIL.Image.open(media / "organ.jpg")

# Count tokens for combined text and inline image.
print(
    client.models.count_tokens(
        model="gemini-2.0-flash", contents=[prompt, your_image_file]
    )
)
# ( e.g., total_tokens: 263 )

response = client.models.generate_content(
    model="gemini-2.0-flash", contents=[prompt, your_image_file]
)
print(response.usage_metadata)
# ( e.g., prompt_token_count: 264, candidates_token_count: 80, total_token_count: 345 )

動画ファイルまたは音声ファイル

音声と動画は、次の固定レートでトークンに変換されます。

  • 動画: 1 秒あたり 263 トークン
  • 音声: 1 秒あたり 32 トークン
from google import genai
import time

client = genai.Client()
prompt = "Tell me about this video"
your_file = client.files.upload(file=media / "Big_Buck_Bunny.mp4")

# Poll until the video file is completely processed (state becomes ACTIVE).
while not your_file.state or your_file.state.name != "ACTIVE":
    print("Processing video...")
    print("File state:", your_file.state)
    time.sleep(5)
    your_file = client.files.get(name=your_file.name)

print(
    client.models.count_tokens(
        model="gemini-2.0-flash", contents=[prompt, your_file]
    )
)
# ( e.g., total_tokens: 300 )

response = client.models.generate_content(
    model="gemini-2.0-flash", contents=[prompt, your_file]
)
print(response.usage_metadata)
# ( e.g., prompt_token_count: 301, candidates_token_count: 60, total_token_count: 361 )

システム指示とツール

システムの手順とツールも、入力の合計トークン数にカウントされます。

システム指示を使用すると、system_instruction の追加を反映して total_tokens のカウントが増加します。

関数呼び出しを使用すると、tools の追加を反映して total_tokens のカウントが増加します。