Понимать и считать жетоны


Gemini и другие генеративные модели ИИ обрабатывают ввод и вывод с степенью детализации, называемой токеном .

О токенах

Токенами могут быть отдельные символы, например z , или целые слова, например cat . Длинные слова разбиваются на несколько токенов. Набор всех токенов, используемых моделью, называется словарем, а процесс разделения текста на токены — токенизацией .

Для моделей Gemini токен эквивалентен примерно 4 символам. 100 токенов равны примерно 60-80 английским словам.

Когда включено биллинг, стоимость вызова Gemini API частично определяется количеством входных и выходных токенов, поэтому знание того, как подсчитывать токены, может оказаться полезным.

Попробуйте посчитать жетоны в Colab

Вы можете попробовать подсчитать жетоны с помощью Colab.

Контекстные окна

Модели, доступные через Gemini API, имеют контекстные окна, которые измеряются в токенах. Контекстное окно определяет, какой объем входных данных вы можете предоставить и какой объем выходных данных может сгенерировать модель. Определить размер контекстного окна можно, вызвав конечную точку getModels или заглянув в документацию модели .

В следующем примере вы можете видеть, что модель gemini-1.5-flash имеет ограничение на вход около 1 000 000 токенов и ограничение на вывод около 8 000 токенов, что означает, что контекстное окно составляет 1 000 000 токенов.

import google.generativeai as genai

model_info = genai.get_model("models/gemini-1.5-flash")

# 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 )

Подсчитайте жетоны

Все входные и выходные данные Gemini API токенизированы, включая текст, файлы изображений и другие нетекстовые модальности.

Подсчитать жетоны можно следующими способами:

  • Вызовите count_tokens с вводом запроса.
    Это возвращает общее количество токенов только во входных данных . Вы можете сделать этот вызов перед отправкой входных данных в модель, чтобы проверить размер ваших запросов.

  • Используйте атрибут usage_metadata в объекте response после вызова generate_content .
    Это возвращает общее количество токенов как на входе, так и на выходе : total_token_count .
    Он также возвращает количество токенов ввода и вывода отдельно: prompt_token_count (входные токены) и candidates_token_count (выходные токены).

Подсчет текстовых жетонов

Если вы вызываете count_tokens только с текстовым вводом, он возвращает количество токенов только для текста на входе ( total_tokens ). Вы можете сделать этот вызов перед generate_content , чтобы проверить размер ваших запросов.

Другой вариант — вызвать generate_content , а затем использовать атрибут usage_metadata объекта response , чтобы получить следующее:

  • Отдельные счетчики входных токенов ( prompt_token_count ) и выходных ( candidates_token_count ).
  • Общее количество токенов как на входе, так и на выходе ( total_token_count )
import google.generativeai as genai

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 )

Подсчет многоходовых (чатовых) жетонов

Если вы вызываете count_tokens с историей чата, он возвращает общее количество токенов текста для каждой роли в чате ( total_tokens ).

Другой вариант — вызвать send_message , а затем использовать атрибут usage_metadata объекта response , чтобы получить следующее:

  • Отдельные счетчики входных токенов ( prompt_token_count ) и выходных ( candidates_token_count ).
  • Общее количество токенов как на входе, так и на выходе ( total_token_count )

Чтобы понять, насколько большим будет ваш следующий диалог, вам нужно добавить его в историю при вызове count_tokens .

import google.generativeai as genai

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 )

Подсчитайте мультимодальные токены

Все входные данные в Gemini API токенизированы, включая текст, файлы изображений и другие нетекстовые модальности. Обратите внимание на следующие ключевые моменты высокого уровня, касающиеся токенизации мультимодальных входных данных во время обработки Gemini API:

  • В Gemini 2.0 входные изображения с обоими размерами <= 384 пикселей считаются как 258 токенов. Изображения, увеличенные в одном или обоих измерениях, обрезаются и масштабируются по мере необходимости в плитки размером 768x768 пикселей, каждая из которых считается 258 токенами. До Gemini 2.0 изображения использовали фиксированные 258 токенов.

  • Видео- и аудиофайлы конвертируются в токены по следующим фиксированным скоростям: видео — 263 токена в секунду, аудио — 32 токена в секунду.

Файлы изображений

Если вы вызываете count_tokens с вводом текста и изображения, он возвращает объединенное количество токенов текста и изображения только на входе ( total_tokens ). Вы можете сделать этот вызов перед generate_content , чтобы проверить размер ваших запросов. Вы также можете дополнительно вызвать count_tokens для текста и файла отдельно.

Другой вариант — вызвать generate_content , а затем использовать атрибут usage_metadata объекта response , чтобы получить следующее:

  • Отдельные счетчики входных токенов ( prompt_token_count ) и выходных ( candidates_token_count ).
  • Общее количество токенов как на входе, так и на выходе ( total_token_count )

Пример использования загруженного изображения из File API:

import google.generativeai as genai

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

prompt = "Tell me about this image"
your_image_file = genai.upload_file(path=media / "organ.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 )

Пример, предоставляющий изображение как встроенные данные:

import google.generativeai as genai

import PIL.Image

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

prompt = "Tell me about this image"
your_image_file = PIL.Image.open(media / "organ.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 )

Видео или аудио файлы

Аудио и видео конвертируются в токены по следующим фиксированным ставкам:

  • Видео: 263 токена в секунду
  • Аудио: 32 токена в секунду

Если вы вызываете count_tokens с вводом текста и видео/аудио, он возвращает объединенное количество токенов текста и видео/аудиофайла только на входе ( total_tokens ). Вы можете сделать этот вызов перед generate_content , чтобы проверить размер ваших запросов. Вы также можете дополнительно вызвать count_tokens для текста и файла отдельно.

Другой вариант — вызвать generate_content , а затем использовать атрибут usage_metadata объекта response , чтобы получить следующее:

  • Отдельные счетчики входных токенов ( prompt_token_count ) и выходных ( candidates_token_count ).
  • Общее количество токенов как на входе, так и на выходе ( total_token_count )
import google.generativeai as genai

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 )

Системные инструкции и инструменты

Системные инструкции и инструменты также учитываются при подсчете общего количества токенов для ввода.

Если вы используете системные инструкции, количество total_tokens увеличивается, отражая добавление system_instruction .

import google.generativeai as genai

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 )

Если вы используете вызов функции, счетчик total_tokens увеличивается, отражая добавление tools .

import google.generativeai as genai

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 )