Zrozumienie i liczenie tokenów


Gemini i inne modele generatywnej AI przetwarzają dane wejściowe i wyjściowe z dokładnością nazywany tokenem.

Z tego przewodnika dowiesz się, jak uzyskać okna kontekstów konkretnych modeli i dowiedz się, jak tokeny liczenia na potrzeby przypadków użycia takich jak wprowadzanie tekstu, czat, tryb multimodalny oraz instrukcje i narzędzia systemowe.

Informacje o tokenach

Tokenami mogą być pojedyncze znaki, np. z, lub całe słowa, np. cat. Długie słowa są podzielone na kilka tokenów. Zbiór wszystkich tokenów używanych przez model to to słownictwo, a proces dzielenia tekstu na tokeny nazywa się tokenizacji.

W przypadku modeli Gemini token jest odpowiednikiem około 4 znaków. 100 tokenów to około 60–80 angielskich słów.

Gdy włączone są płatności, koszt wywołania interfejsu Gemini API wynosi określane częściowo na podstawie liczby tokenów wejściowych i wyjściowych, dzięki czemu wiesz, tokeny licznika, mogą być pomocne.

Wyświetl na ai.google.dev Uruchom w Google Colab Wyświetl źródło w GitHubie

Okna kontekstu

Modele dostępne przez interfejs Gemini API mają okna kontekstu mierzone w tokenach. Okno kontekstu określa, ile danych wejściowych możesz podać i jaką ilość danych wyjściowych może wygenerować model. Możesz określić wielkość w oknie kontekstu za pomocą API lub dokumentacji modeli.

W przykładzie poniżej widać, że model gemini-1.0-pro-001 ma określone z limitem danych wejściowych do około 30 tys. tokenów oraz limitem wyjściowym do około 2 tys., oznacza okno kontekstu z około 32 tys. tokenów.

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 )

Kolejny przykład: jeśli poprosisz o limity tokenów dla modelu takiego jak gemini-1.5-flash-001, zobaczysz, że ma okno kontekstu o rozmiarze 2 mln.

Policz tokeny

Wszystkie dane wejściowe do i wychodzące z interfejsu Gemini API są tokenizowane, w tym tekst, obraz i inne modalności nietekstowe.

Tokeny możesz liczyć na następujące sposoby:

Policz tokeny tekstowe

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 )

Liczenie tokenów wieloetapowych (czatu)

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 )

Policzanie tokenów multimodalnych

Wszystkie dane wejściowe do interfejsu Gemini API są tokenizowane, w tym tekst, pliki graficzne i inne nietekstowych. Zwróć uwagę na te najważniejsze kwestie związane z tokenizacją. multimodalne dane wejściowe podczas przetwarzania przez interfejs Gemini API:

  • Obrazy mają stały rozmiar, więc zajmują (obecnie 258 tokenów) niezależnie od wyświetlanego rozmiaru pliku.

  • Pliki wideo i audio są konwertowane na tokeny po tych stałych stawkach: wideo z szybkością 263 tokenów na sekundę i dźwięk z 32 tokenami na sekundę.

Pliki graficzne

Podczas przetwarzania interfejs Gemini API uznaje obrazy za stały rozmiar, wykorzystują stałą liczbę tokenów (obecnie jest to 258 tokenów) niezależnie od ich lub rozmiarem wyświetlanego pliku.

Przykład wykorzystania obrazu przesłanego za pomocą interfejsu File API:

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 )

Przykład wyświetlający obraz jako dane wbudowane:

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 )

Pliki wideo lub audio

Dźwięk i obraz są konwertowane na tokeny po tych stałych stawkach:

  • Wideo: 263 tokeny na sekundę
  • Audio: 32 tokeny na sekundę
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 )

Instrukcje i narzędzia systemowe

Instrukcje i narzędzia systemowe również wliczają się do łącznej liczby tokenów dane wejściowe.

Jeśli korzystasz z instrukcji systemowych, liczba zdarzeń total_tokens wzrośnie, aby odzwierciedlić dodanie 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 )

Jeśli używasz wywoływania funkcji, liczba total_tokens zwiększa się, aby odzwierciedlić dodanie 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 )