Jetonları anlama ve sayma


Gemini ve diğer üretken yapay zeka modelleri, giriş ve çıkışı ayrıntılı bir şekilde işler. jeton adı verilir.

Bu kılavuzda, belirli modellerin bağlam pencerelerini ve Metin girişi, sohbet, çok modlu gibi kullanım alanları için sayım jetonları bilgileri girebiliriz.

Jetonlar hakkında

Jetonlar, z gibi tek karakterlerden veya cat gibi tam kelimelerden oluşabilir. Uzun kelimeler ve daha sonra birkaç jetona bölünür. Model tarafından kullanılan tüm jeton kümesi kelime dağarcığı denir ve metni simgesel parçalara ayırma işlemine tokenization değerleridir.

Gemini modellerinde bir jeton, yaklaşık 4 karaktere eşdeğerdir. 100 jeton, yaklaşık 60-80 İngilizce kelimeye eşittir.

Faturalandırma etkinleştirildiğinde Gemini API'ye yapılan aramaların maliyeti kısmen giriş ve çıkış jetonlarının sayısına göre belirlenir. Böylece, sayma jetonları faydalı olabilir.

ai.google.dev'de görüntüleyin Google Colab'de çalıştır Kaynağı GitHub'da görüntüle

Bağlam aralıkları

Gemini API aracılığıyla kullanılabilen modellerde bağlam aralıkları şu şekildedir: jetonlarla ölçülür. Bağlam penceresi, ne kadar giriş sağlayabileceğinizi tanımlar ve modelin ne kadar çıktı üretebileceği. Etiketlerin boyutunu; API'yı kullanarak veya doğrudan models belgesini inceleyin.

Aşağıdaki örnekte, gemini-1.0-pro-001 modelinin bir yaklaşık 30 bin jeton giriş sınırı ve yaklaşık 2.000 jetonluk çıkış sınırı. yaklaşık 32 bin jetonluk bir bağlam penceresi anlamına gelir.

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 )

Başka bir örnek vermek gerekirse gemini-1.5-flash-001 bağlam penceresinin 2 milyon olduğunu görürsünüz.

Jetonları say

Metin, resim dahil Gemini API'ye yapılan tüm girişler ve çıkışlar tokenlere ayrılmıştır diğer metin dışı modlardan da yararlanabilirsiniz.

Jetonları aşağıdaki şekillerde sayabilirsiniz:

Metin jetonlarını say

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 )

Çok dönüşlü (sohbet) jetonlarını sayma

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 )

Çok modlu jetonları sayma

Metin, resim dosyaları ve diğer işlemler dahil Gemini API'ye yapılan tüm girişler tokenlere ayrılmıştır metin dışı modaliteleri var. Tokenleştirmeyle ilgili aşağıdaki üst düzey önemli noktaları unutmayın çok modlu girişin Gemini API tarafından işlenmesi sırasında:

  • Resimler sabit boyutlu olarak kabul edilir, bu nedenle sabit sayıda jetonları (şu anda 258 jeton) olarak gösterilir.

  • Video ve ses dosyaları, aşağıdaki sabit ücretlerle jetonlara dönüştürülür: saniyede 263 jeton hızında video ve saniyede 32 jetonla ses.

Resim dosyaları

Gemini API, işleme sırasında resimleri sabit boyutlu olarak kabul eder. Bu nedenle sabit sayıda jeton (şu anda 258 jeton) tükettiğinde, veya dosya boyutu olabilir.

File API'den yüklenmiş bir resmin kullanıldığı örnek:

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 )

Resmi satır içi veri olarak sağlayan örnek:

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 )

Video veya ses dosyaları

Ses ve videoların her biri aşağıdaki sabit ücretlerle jetonlara dönüştürülür:

  • Video: Saniyede 263 jeton
  • Ses: Saniyede 32 jeton
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 )

Sistem talimatları ve araçları

Sistem talimatları ve araçları da giriş.

Sistem talimatlarını kullanırsanız total_tokens sayısı, bilgileri yansıtacak şekilde artar system_instruction eklenmesi.

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 )

İşlev çağrısı kullanıyorsanız total_tokens sayısı tools eklendi.

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 )