توکن ها را بفهمید و بشمارید

Gemini و دیگر مدل‌های هوش مصنوعی مولد، ورودی و خروجی را با جزئیاتی به نام توکن پردازش می‌کنند.

برای مدل‌های Gemini، یک توکن معادل حدود ۴ کاراکتر است. ۱۰۰ توکن معادل حدود ۶۰ تا ۸۰ کلمه انگلیسی است.

درباره توکن‌ها

توکن‌ها می‌توانند کاراکترهای تکی مانند z یا کلمات کاملی مانند cat باشند. کلمات طولانی به چندین توکن تقسیم می‌شوند. مجموعه تمام توکن‌های مورد استفاده توسط مدل، واژگان نامیده می‌شود و فرآیند تقسیم متن به توکن‌ها، توکن‌سازی نامیده می‌شود.

وقتی صورتحساب فعال باشد، هزینه تماس با API جمینی تا حدودی توسط تعداد توکن‌های ورودی و خروجی تعیین می‌شود، بنابراین دانستن نحوه شمارش توکن‌ها می‌تواند مفید باشد.


جاوا

شمارش توکن‌ها را در یک Colab امتحان کنید

می‌توانید با استفاده از Colab شمارش توکن‌ها را امتحان کنید.

مشاهده در ai.google.dev یک دفترچه یادداشت Colab را امتحان کنید مشاهده دفترچه یادداشت در گیت‌هاب

پنجره‌های زمینه

مدل‌های موجود از طریق رابط برنامه‌نویسی نرم‌افزار Gemini دارای پنجره‌های زمینه‌ای هستند که با توکن اندازه‌گیری می‌شوند. پنجره زمینه‌ای مشخص می‌کند که چه مقدار ورودی می‌توانید ارائه دهید و چه مقدار خروجی می‌توانید توسط مدل تولید کنید. می‌توانید اندازه پنجره زمینه‌ای را با فراخوانی نقطه پایانی getModels یا با مراجعه به مستندات مدل‌ها تعیین کنید.

در مثال زیر، می‌توانید ببینید که مدل gemini-2.0-flash دارای محدودیت ورودی حدود ۱،۰۰۰،۰۰۰ توکن و محدودیت خروجی حدود ۸،۰۰۰ توکن است، به این معنی که یک پنجره زمینه ۱،۰۰۰،۰۰۰ توکن است.

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 )

تعداد توکن‌ها

تمام ورودی‌ها و خروجی‌های API جمینی، از جمله متن، فایل‌های تصویری و سایر موارد غیرمتنی، توکن‌سازی شده‌اند.

شما می‌توانید توکن‌ها را به روش‌های زیر بشمارید:

  • تابع count_tokens را با ورودی درخواست فراخوانی کنید.
    این فقط تعداد کل توکن‌های موجود در ورودی را برمی‌گرداند. می‌توانید قبل از ارسال ورودی به مدل، این فراخوانی را انجام دهید تا اندازه درخواست‌های خود را بررسی کنید.

  • از ویژگی usage_metadata روی شیء response پس از فراخوانی generate_content استفاده کنید.
    این تابع تعداد کل توکن‌ها را هم در ورودی و هم در خروجی برمی‌گرداند: total_token_count .
    همچنین تعداد توکن‌های ورودی و خروجی را به صورت جداگانه برمی‌گرداند: prompt_token_count (توکن‌های ورودی) و candidates_token_count (توکن‌های خروجی).

    اگر از یک مدل تفکر مانند مدل‌های ۲.۵ استفاده می‌کنید، توکن مورد استفاده در طول فرآیند تفکر در thoughts_token_count بازگردانده می‌شود. و اگر از Context caching استفاده می‌کنید، تعداد توکن‌های ذخیره شده در cached_content_token_count خواهد بود.

شمارش توکن‌های متنی

اگر count_tokens با یک ورودی فقط متنی فراخوانی کنید، تعداد توکن‌های متن موجود در ورودی ( total_tokens ) را برمی‌گرداند. می‌توانید این فراخوانی را قبل از فراخوانی generate_content انجام دهید تا اندازه درخواست‌های خود را بررسی کنید.

گزینه دیگر فراخوانی generate_content و سپس استفاده از ویژگی usage_metadata در شیء response برای دریافت موارد زیر است:

  • شمارش جداگانه توکن‌های ورودی ( prompt_token_count )، محتوای ذخیره شده ( cached_content_token_count ) و خروجی ( candidates_token_count )
  • تعداد توکن‌ها برای فرآیند تفکر ( thoughts_token_count )
  • تعداد کل توکن‌ها در ورودی و خروجی ( total_token_count )
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 )

Count multi-turn (chat) tokens

If you call count_tokens with the chat history, it returns the total token count of the text from each role in the chat ( total_tokens ).

Another option is calling send_message and then using the usage_metadata attribute on the response object to get the following:

  • The separate token counts of the input ( prompt_token_count ), the cached content ( cached_content_token_count ) and the output ( candidates_token_count )
  • The token count for the thinking process ( thoughts_token_count )
  • The total number of tokens in both the input and the output ( total_token_count )

To understand how big your next conversational turn will be, you need to append it to the history when you call count_tokens .

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 )

شمارش توکن‌های چندوجهی

All input to the Gemini API is tokenized, including text, image files, and other non-text modalities. Note the following high-level key points about tokenization of multimodal input during processing by the Gemini API:

  • With Gemini 2.0, image inputs with both dimensions <=384 pixels are counted as 258 tokens. Images larger in one or both dimensions are cropped and scaled as needed into tiles of 768x768 pixels, each counted as 258 tokens. Prior to Gemini 2.0, images used a fixed 258 tokens.

  • Video and audio files are converted to tokens at the following fixed rates: video at 263 tokens per second and audio at 32 tokens per second.

Media resolutions

Gemini 3 Pro Preview introduces granular control over multimodal vision processing with the media_resolution parameter. The media_resolution parameter determines the maximum number of tokens allocated per input image or video frame. Higher resolutions improve the model's ability to read fine text or identify small details, but increase token usage and latency.

برای جزئیات بیشتر در مورد این پارامتر و نحوه تأثیر آن بر محاسبات توکن، به راهنمای تفکیک‌پذیری رسانه مراجعه کنید.

فایل‌های تصویری

If you call count_tokens with a text-and-image input, it returns the combined token count of the text and the image in the input only ( total_tokens ). You can make this call before calling generate_content to check the size of your requests. You can also optionally call count_tokens on the text and the file separately.

Another option is calling generate_content and then using the usage_metadata attribute on the response object to get the following:

  • The separate token counts of the input ( prompt_token_count ), the cached content ( cached_content_token_count ) and the output ( candidates_token_count )
  • The token count for the thinking process ( thoughts_token_count )
  • The total number of tokens in both the input and the output ( total_token_count )

Example that uses an uploaded image from the 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 )

Example that provides the image as inline data:

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 )

Video or audio files

Audio and video are each converted to tokens at the following fixed rates:

  • Video: 263 tokens per second
  • Audio: 32 tokens per second

If you call count_tokens with a text-and-video/audio input, it returns the combined token count of the text and the video/audio file in the input only ( total_tokens ). You can make this call before calling generate_content to check the size of your requests. You can also optionally call count_tokens on the text and the file separately.

Another option is calling generate_content and then using the usage_metadata attribute on the response object to get the following:

  • The separate token counts of the input ( prompt_token_count ), the cached content ( cached_content_token_count ) and the output ( candidates_token_count )
  • The token count for the thinking process ( thoughts_token_count )
  • The total number of tokens in both the input and the output ( total_token_count )
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 instructions and tools

System instructions and tools also count towards the total token count for the input.

If you use system instructions, the total_tokens count increases to reflect the addition of system_instruction .

If you use function calling, the total_tokens count increases to reflect the addition of tools .