Comprendi e conteggia i token


Gemini e altri modelli di IA generativa elaborano input e output con granularità chiamato token.

Questa guida spiega come ottenere finestre di contesto di modelli specifici, nonché su come conteggio dei token per casi d'uso come input di testo, chat, modalità multimodali input nonché istruzioni e strumenti di sistema.

Informazioni sui token

I token possono essere singoli caratteri come z o parole intere come cat. Parole lunghe sono suddivisi in diversi token. L'insieme di tutti i token utilizzati dal modello il vocabolario, mentre il processo di suddivisione del testo in token prende il nome tokenizzazione.

Per i modelli Gemini, un token equivale a circa 4 caratteri. 100 token equivalgono a circa 60-80 parole inglesi.

Se la fatturazione è abilitata, il costo di una chiamata all'API Gemini è determinato in parte dal numero di token di input e di output, quindi sapere come il conteggio dei token può essere utile.

Visualizza su ai.google.dev Esegui in Google Colab Visualizza il codice sorgente su GitHub

Finestre di contesto

I modelli disponibili tramite l'API Gemini hanno finestre contestuali che misurate in token. La finestra contestuale definisce la quantità di input che puoi fornire e quanti output può generare il modello. Puoi determinare la dimensione finestra contestuale utilizzando l'API o cercando nella documentazione di models.

Nell'esempio seguente, puoi vedere che il modello gemini-1.0-pro-001 ha un un limite di input di circa 30.000 token e un limite di output di circa 2.000 token, indica una finestra contestuale di circa 32.000 token.

model_info = genai.get_model("models/gemini-1.0-pro-001")

# Returns the "context window" for the model,
# which is the combined input and output token limits.
print(f"{model_info.input_token_limit=}")
print(f"{model_info.output_token_limit=}")
# ( input_token_limit=30720, output_token_limit=2048 )

Come ulteriore esempio, se al contrario hai richiesto i limiti di token per un modello come gemini-1.5-flash-001, vedrai una finestra contestuale di 2 M.

Conta token

Tutti gli input e gli output dall'API Gemini sono tokenizzati, inclusi testo, immagini e altre modalità non testuali.

Puoi contare i token nei seguenti modi:

Conta token di testo

model = genai.GenerativeModel("models/gemini-1.5-flash")

prompt = "The quick brown fox jumps over the lazy dog."

# Call `count_tokens` to get the input token count (`total_tokens`).
print("total_tokens: ", model.count_tokens(prompt))
# ( total_tokens: 10 )

response = model.generate_content(prompt)

# On the response for `generate_content`, use `usage_metadata`
# to get separate input and output token counts
# (`prompt_token_count` and `candidates_token_count`, respectively),
# as well as the combined token count (`total_token_count`).
print(response.usage_metadata)
# ( prompt_token_count: 11, candidates_token_count: 73, total_token_count: 84 )

Conteggia i token in più passaggi (chat)

model = genai.GenerativeModel("models/gemini-1.5-flash")

chat = model.start_chat(
    history=[
        {"role": "user", "parts": "Hi my name is Bob"},
        {"role": "model", "parts": "Hi Bob!"},
    ]
)
# Call `count_tokens` to get the input token count (`total_tokens`).
print(model.count_tokens(chat.history))
# ( total_tokens: 10 )

response = chat.send_message(
    "In one sentence, explain how a computer works to a young child."
)

# On the response for `send_message`, use `usage_metadata`
# to get separate input and output token counts
# (`prompt_token_count` and `candidates_token_count`, respectively),
# as well as the combined token count (`total_token_count`).
print(response.usage_metadata)
# ( prompt_token_count: 25, candidates_token_count: 21, total_token_count: 46 )

from google.generativeai.types.content_types import to_contents

# You can call `count_tokens` on the combined history and content of the next turn.
print(model.count_tokens(chat.history + to_contents("What is the meaning of life?")))
# ( total_tokens: 56 )

Conta token multimodali

Tutti gli input all'API Gemini sono tokenizzati, inclusi testo, file immagine e altri modalità non testuali. Tieni presente i seguenti punti chiave di alto livello sulla tokenizzazione di input multimodale durante l'elaborazione da parte dell'API Gemini:

  • Le immagini sono considerate di dimensioni fisse, pertanto consumano un numero fisso di (attualmente 258 token), a prescindere dalle dimensioni di visualizzazione o del file.

  • I file video e audio vengono convertiti in token con le seguenti tariffe fisse: video a 263 token al secondo e audio a 32 token al secondo.

File immagine

Durante l'elaborazione, l'API Gemini considera le immagini di dimensioni fisse, quindi consumano un numero fisso di token (attualmente 258 token), indipendentemente dalla loro dimensioni di visualizzazione o del file.

Esempio che utilizza un'immagine caricata dall'API File:

model = genai.GenerativeModel("models/gemini-1.5-flash")

prompt = "Tell me about this image"
your_image_file = genai.upload_file(path="image.jpg")

# Call `count_tokens` to get the input token count
# of the combined text and file (`total_tokens`).
# An image's display or file size does not affect its token count.
# Optionally, you can call `count_tokens` for the text and file separately.
print(model.count_tokens([prompt, your_image_file]))
# ( total_tokens: 263 )

response = model.generate_content([prompt, your_image_file])
response.text
# On the response for `generate_content`, use `usage_metadata`
# to get separate input and output token counts
# (`prompt_token_count` and `candidates_token_count`, respectively),
# as well as the combined token count (`total_token_count`).
print(response.usage_metadata)
# ( prompt_token_count: 264, candidates_token_count: 80, total_token_count: 345 )

Esempio che fornisce l'immagine come dati in linea:

import PIL.Image

model = genai.GenerativeModel("models/gemini-1.5-flash")

prompt = "Tell me about this image"
your_image_file = PIL.Image.open("image.jpg")

# Call `count_tokens` to get the input token count
# of the combined text and file (`total_tokens`).
# An image's display or file size does not affect its token count.
# Optionally, you can call `count_tokens` for the text and file separately.
print(model.count_tokens([prompt, your_image_file]))
# ( total_tokens: 263 )

response = model.generate_content([prompt, your_image_file])

# On the response for `generate_content`, use `usage_metadata`
# to get separate input and output token counts
# (`prompt_token_count` and `candidates_token_count`, respectively),
# as well as the combined token count (`total_token_count`).
print(response.usage_metadata)
# ( prompt_token_count: 264, candidates_token_count: 80, total_token_count: 345 )

File video o audio

Audio e video vengono convertiti in token alle seguenti tariffe fisse:

  • Video: 263 token al secondo
  • Audio: 32 token al secondo
import time

model = genai.GenerativeModel("models/gemini-1.5-flash")

prompt = "Tell me about this video"
your_file = genai.upload_file(path=media / "Big_Buck_Bunny.mp4")

# Videos need to be processed before you can use them.
while your_file.state.name == "PROCESSING":
    print("processing video...")
    time.sleep(5)
    your_file = genai.get_file(your_file.name)

# Call `count_tokens` to get the input token count
# of the combined text and video/audio file (`total_tokens`).
# A video or audio file is converted to tokens at a fixed rate of tokens per second.
# Optionally, you can call `count_tokens` for the text and file separately.
print(model.count_tokens([prompt, your_file]))
# ( total_tokens: 300 )

response = model.generate_content([prompt, your_file])

# On the response for `generate_content`, use `usage_metadata`
# to get separate input and output token counts
# (`prompt_token_count` and `candidates_token_count`, respectively),
# as well as the combined token count (`total_token_count`).
print(response.usage_metadata)
# ( prompt_token_count: 301, candidates_token_count: 60, total_token_count: 361 )

Istruzioni e strumenti di sistema

Anche le istruzioni e gli strumenti di sistema vengono conteggiati ai fini del conteggio totale dei token per di testo.

Se usi le istruzioni di sistema, il conteggio di total_tokens aumenta per riflettere l'aggiunta di system_instruction.

model = genai.GenerativeModel(model_name="gemini-1.5-flash")

prompt = "The quick brown fox jumps over the lazy dog."

print(model.count_tokens(prompt))
# total_tokens: 10

model = genai.GenerativeModel(
    model_name="gemini-1.5-flash", system_instruction="You are a cat. Your name is Neko."
)

# The total token count includes everything sent to the `generate_content` request.
# When you use system instructions, the total token count increases.
print(model.count_tokens(prompt))
# ( total_tokens: 21 )

Se utilizzi le chiamate di funzione, il conteggio di total_tokens aumenta per riflettere la aggiunta di tools.

model = genai.GenerativeModel(model_name="gemini-1.5-flash")

prompt = "I have 57 cats, each owns 44 mittens, how many mittens is that in total?"

print(model.count_tokens(prompt))
# ( total_tokens: 22 )

def add(a: float, b: float):
    """returns a + b."""
    return a + b

def subtract(a: float, b: float):
    """returns a - b."""
    return a - b

def multiply(a: float, b: float):
    """returns a * b."""
    return a * b

def divide(a: float, b: float):
    """returns a / b."""
    return a / b

model = genai.GenerativeModel(
    "models/gemini-1.5-flash-001", tools=[add, subtract, multiply, divide]
)

# The total token count includes everything sent to the `generate_content` request.
# When you use tools (like function calling), the total token count increases.
print(model.count_tokens(prompt))
# ( total_tokens: 206 )