Kuptoni dhe numëroni shenjat

Gemini dhe modele të tjera të IA-së gjeneruese përpunojnë hyrjen dhe daljen në një shkallë të detajuar të quajtur token .

Për modelet Gemini, një token është ekuivalent me rreth 4 karaktere. 100 tokena janë të barabarta me rreth 60-80 fjalë në anglisht.

Rreth tokenëve

Shenjat mund të jenë karaktere të vetme si z ose fjalë të tëra si cat . Fjalët e gjata ndahen në disa shenja. Bashkësia e të gjitha shenjave të përdorura nga modeli quhet fjalor, dhe procesi i ndarjes së tekstit në shenja quhet tokenizim .

Kur faturimi është i aktivizuar, kostoja e një thirrjeje në Gemini API përcaktohet pjesërisht nga numri i tokenëve hyrës dhe dalës, kështu që të dish se si të numërosh tokenët mund të jetë e dobishme.


Provo të numërosh tokenët në një Colab

Mund të provosh të numërosh tokenët duke përdorur një Colab.

Shiko në ai.google.dev Provo një fletore shënimesh Colab Shiko fletoren në GitHub

Dritaret e kontekstit

Modelet e disponueshme përmes Gemini API kanë dritare konteksti që maten në tokena. Dritarja e kontekstit përcakton se sa të dhëna hyrëse mund të jepni dhe sa të dhëna dalëse mund të gjenerojë modeli. Mund të përcaktoni madhësinë e dritares së kontekstit duke thirrur pikën fundore getModels ose duke parë dokumentacionin e modeleve .

Në shembullin e mëposhtëm, mund të shihni se modeli gemini-2.0-flash ka një limit hyrjeje prej rreth 1,000,000 tokenësh dhe një limit daljeje prej rreth 8,000 tokenësh, që do të thotë se një dritare konteksti është 1,000,000 tokenësh.

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 )

Numëroni shenjat

Të gjitha të dhënat hyrëse dhe dalëse nga Gemini API janë të tokenizuara, duke përfshirë tekstin, skedarët e imazheve dhe modalitete të tjera jo-tekstuale.

Ju mund të numëroni shenjat në mënyrat e mëposhtme:

  • Thirrni count_tokens me të dhënat hyrëse të kërkesës.
    Kjo kthen numrin total të tokenëve vetëm në të dhënat hyrëse . Mund ta bëni këtë thirrje përpara se të dërgoni të dhënat hyrëse në model për të kontrolluar madhësinë e kërkesave tuaja.

  • Përdorni atributin usage_metadata në objektin response pas thirrjes generate_content .
    Kjo kthen numrin total të tokenëve si në të dhënat hyrëse ashtu edhe në të dhënat dalëse : total_token_count .
    Gjithashtu kthen numërimin e tokenëve të të dhënave hyrëse dhe dalëse veçmas: prompt_token_count (tokenët hyrës) dhe candidates_token_count (tokenët dalës).

    Nëse përdorni një model të të menduarit si ai 2.5, token-et e përdorura gjatë procesit të të menduarit kthehen në thoughts_token_count . Dhe nëse përdorni ruajtjen në memorje të kontekstit , numri i token-eve të ruajtura në memorje do të jetë në cached_content_token_count .

Numëroni shenjat e tekstit

Nëse e thërrisni count_tokens me një input vetëm tekst, ai kthen numrin e token-ave të tekstit vetëm në input ( total_tokens ). Mund ta bëni këtë thirrje përpara se të thërrisni generate_content për të kontrolluar madhësinë e kërkesave tuaja.

Një tjetër mundësi është thirrja generate_content dhe më pas përdorimi i atributit usage_metadata në objektin response për të marrë sa vijon:

  • 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

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 )

Count multimodal tokens

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.

For more details about the parameter and how it can impact token calculations, see the media resolution guide.

Image files

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 .