Memahami dan menghitung token


Gemini dan model AI generatif lainnya memproses input dan output pada tingkat perincian disebut token.

Panduan ini menjelaskan cara mendapatkan jendela konteks model tertentu, serta cara penghitungan token untuk kasus penggunaan seperti input teks, chat, multimodal input, serta petunjuk dan alat sistem.

Tentang token

Token dapat berupa karakter tunggal seperti z atau seluruh kata seperti cat. Kata-kata panjang dipecah menjadi beberapa token. Kumpulan semua token yang digunakan oleh model adalah disebut kosakata, dan proses pemisahan teks menjadi token disebut tokenization.

Untuk model Gemini, token setara dengan sekitar 4 karakter. 100 token sama dengan sekitar 60-80 kata bahasa Inggris.

Jika penagihan diaktifkan, biaya panggilan ke Gemini API adalah sebagian ditentukan oleh jumlah token input dan {i>output<i}, sehingga mengetahui cara tibble dapat membantu.

Lihat di ai.google.dev Berjalan di Google Colab Lihat sumber di GitHub

Jendela konteks

Model yang tersedia melalui Gemini API memiliki jendela konteks yang yang diukur dalam token. Jendela konteks menentukan seberapa banyak input yang dapat Anda berikan dan berapa banyak output yang dapat dihasilkan model. Anda dapat menentukan ukuran jendela konteks menggunakan API atau dengan melihat dokumentasi model.

Pada contoh berikut, Anda dapat melihat bahwa model gemini-1.0-pro-001 memiliki masukan sekitar 30 ribu token dan batas output sekitar 2 ribu token, yang berarti jendela konteks berisi sekitar 32 ribu 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 )

Contoh lain, jika Anda justru meminta batas token untuk model seperti gemini-1.5-flash-001, Anda akan melihat bahwa kode ini memiliki jendela konteks 2 juta.

Hitung token

Semua input ke dan output dari Gemini API akan ditokenkan, termasuk teks, gambar file, dan modalitas non-teks lainnya.

Anda dapat menghitung token dengan cara berikut:

Menghitung token teks

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 )

Menghitung token multi-giliran (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 )

Menghitung token multimodal

Semua input ke Gemini API akan ditokenkan, termasuk teks, file gambar, dan modalitas non-teks. Perhatikan poin-poin penting tingkat tinggi berikut tentang tokenisasi input multimodal selama pemrosesan oleh Gemini API:

  • Gambar dianggap berukuran tetap, sehingga menggunakan jumlah token (saat ini 258 token), terlepas dari tampilan atau ukuran filenya.

  • File video dan audio dikonversi menjadi token dengan tarif tetap berikut: video pada 263 token per detik dan audio pada 32 token per detik.

File gambar

Selama pemrosesan, Gemini API menganggap gambar memiliki ukuran tetap, sehingga memakai token dalam jumlah tetap (saat ini 258 token), terlepas dari tampilan atau ukuran file.

Contoh yang menggunakan gambar yang diupload dari 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 )

Contoh yang menyediakan gambar sebagai data inline:

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 atau audio

Audio dan video masing-masing dikonversi menjadi token dengan tarif tetap berikut:

  • Video: 263 token per detik
  • Audio: 32 token per detik
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 )

Alat dan petunjuk sistem

Petunjuk sistem dan alat juga diperhitungkan dalam jumlah total token untuk input teks.

Jika Anda menggunakan petunjuk sistem, jumlah total_tokens akan meningkat untuk mencerminkan penambahan 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 )

Jika Anda menggunakan panggilan fungsi, jumlah total_tokens akan bertambah untuk mencerminkan penambahan 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 )