Elenca e conteggia i token

Questa pagina mostra come elencare i token e i relativi ID token di un prompt e come ottenere un conteggio totale dei token di un prompt utilizzando l'SDK Google Gen AI.

Token e importanza dell'elenco e del conteggio dei token

I modelli di AI generativa suddividono il testo e altri dati di un prompt in unità chiamate token per l'elaborazione. Il modo in cui i dati vengono convertiti in token dipende dal tokenizer utilizzato. Un token può essere costituito da caratteri, parole o frasi.

Ogni modello ha un numero massimo di token che può gestire in un prompt e in una risposta. Conoscere il numero di token del prompt ti consente di sapere se hai superato questo limite. Inoltre, il conteggio dei token restituisce anche i caratteri fatturabili per il prompt, il che ti aiuta a stimare i costi.

L'elenco dei token restituisce un elenco dei token in cui è suddiviso il prompt. Ogni token elencato è associato a un ID token, che ti aiuta a eseguire la risoluzione dei problemi e analizzare il comportamento del modello.

Modelli supportati

La tabella seguente mostra i modelli che supportano l'elenco dei token e il conteggio dei token:

Ottenere un elenco di token e ID token per un prompt

Il seguente esempio di codice mostra come ottenere un elenco di token e ID token per un prompt. Il prompt deve contenere solo testo. I prompt multimodali non sono supportati.

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
response = client.models.compute_tokens(
    model="gemini-2.5-flash",
    contents="What's the longest word in the English language?",
)

print(response)
# Example output:
# tokens_info=[TokensInfo(
#    role='user',
#    token_ids=[1841, 235303, 235256, 573, 32514, 2204, 575, 573, 4645, 5255, 235336],
#    tokens=[b'What', b"'", b's', b' the', b' longest', b' word', b' in', b' the', b' English', b' language', b'?']
#  )]

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// computeWithTxt shows how to compute tokens with text input.
func computeWithTxt(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "What's the longest word in the English language?"},
		},
			Role: "user"},
	}

	resp, err := client.Models.ComputeTokens(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	type tokenInfoDisplay struct {
		IDs    []int64  `json:"token_ids"`
		Tokens []string `json:"tokens"`
	}
	// See the documentation: https://pkg.go.dev/google.golang.org/genai#ComputeTokensResponse
	for _, instance := range resp.TokensInfo {
		display := tokenInfoDisplay{
			IDs:    instance.TokenIDs,
			Tokens: make([]string, len(instance.Tokens)),
		}
		for i, t := range instance.Tokens {
			display.Tokens[i] = string(t)
		}

		data, err := json.MarshalIndent(display, "", "  ")
		if err != nil {
			return fmt.Errorf("failed to marshal token info: %w", err)
		}
		fmt.Fprintln(w, string(data))
	}

	// Example response:
	// {
	// 	"ids": [
	// 		1841,
	// 		235303,
	// 		235256,
	//    ...
	// 	],
	// 	"values": [
	// 		"What",
	// 		"'",
	// 		"s",
	//    ...
	// 	]
	// }

	return nil
}

Ottenere il conteggio dei token e i caratteri fatturabili di un prompt

Il seguente esempio di codice mostra come ottenere il conteggio dei token e il numero di caratteri fatturabili di un prompt. Sono supportati sia i prompt solo testuali che quelli multimodali.

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))

prompt = "Why is the sky blue?"

# Send text to Gemini
response = client.models.generate_content(
    model="gemini-2.5-flash", contents=prompt
)

# Prompt and response tokens count
print(response.usage_metadata)

# Example output:
#  cached_content_token_count=None
#  candidates_token_count=311
#  prompt_token_count=6
#  total_token_count=317

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// generateTextAndCount shows how to generate text and obtain token count metadata from the model response.
func generateTextAndCount(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	modelName := "gemini-2.0-flash-001"
	contents := []*genai.Content{
		{Parts: []*genai.Part{
			{Text: "Why is the sky blue?"},
		},
			Role: "user"},
	}

	resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	usage, err := json.MarshalIndent(resp.UsageMetadata, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to convert usage metadata to JSON: %w", err)
	}
	fmt.Fprintln(w, string(usage))

	// Example response:
	// {
	// 	 "candidatesTokenCount": 339,
	// 	 "promptTokenCount": 6,
	// 	 "totalTokenCount": 345
	// }

	return nil
}