瞭解及計算符記


Gemini 和其他生成式 AI 模型會以「詞元」為單位處理輸入和輸出內容。

關於權杖

權杖可以是 z 等單一字元,也可以是 cat 等完整字詞。長字會拆分成多個權杖。模型使用的所有符記集合稱為詞彙,將文字分割為符記的過程稱為「符記化」

以 Gemini 模型來說,一個符記約等於 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 的所有輸入和輸出內容都會經過權杖化,包括文字、圖片檔案和其他非文字模態。

您可以透過下列方式計算權杖:

計算文字權杖

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 個權杖。如果圖片在一個或兩個維度上較大,系統會視需要裁剪並縮放圖片,成為 768x768 像素的圖塊,每個圖塊算做 258 個權杖。在 Gemini 2.0 推出前,圖片一律使用 258 個權杖。

  • 系統會以固定費率將影片和音訊檔案轉換為權杖: 影片為每秒 263 個權杖,音訊為每秒 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 )

影片或音訊檔案

音訊和影片會分別以以下固定費率轉換為權杖:

  • 影片:每秒 263 個權杖
  • 音訊:每秒 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 )

系統指示和工具

系統指令和工具也會計入輸入內容的詞元總數。

如果使用系統指令,total_tokens 數量會增加,反映 system_instruction 的新增。

如果您使用函式呼叫,total_tokens 計數會增加,反映 tools 的新增。