Gemini ve diğer üretken yapay zeka modelleri, giriş ve çıkışı jeton adı verilen bir ayrıntı düzeyinde işler.
Jetonlar hakkında
Jetonlar, z
gibi tek karakterler veya cat
gibi tam kelimeler olabilir. Uzun kelimeler birkaç jetona bölünür. Model tarafından kullanılan tüm jetonların kümesine kelime dağarcığı, metni jetonlara bölme işlemine ise jetonlara ayırma adı verilir.
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 bir çağrının maliyeti kısmen giriş ve çıkış jetonlarının sayısına göre belirlenir. Bu nedenle, jetonları nasıl sayacağınızı bilmek faydalı olabilir.
Colab'da jeton saymayı deneyin
Colab kullanarak jeton saymayı deneyebilirsiniz.
Bağlam pencereleri
Gemini API üzerinden kullanılabilen modeller, parça cinsinden ölçülen bağlam pencerelerine sahiptir. Bağlam penceresi, ne kadar giriş sağlayabileceğinizi ve modelin ne kadar çıktı oluşturabileceğini tanımlar. getModels uç noktasını çağırarak veya model dokümanlarına bakarak bağlam penceresinin boyutunu belirleyebilirsiniz.
Aşağıdaki örnekte, gemini-1.5-flash
modelinin yaklaşık 1.000.000 jeton giriş sınırına ve yaklaşık 8.000 jeton çıkış sınırına sahip olduğunu görebilirsiniz. Bu da bağlam penceresinin 1.000.000 jeton olduğu anlamına gelir.
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 )
Jetonları sayma
Metin, resim dosyaları ve metin dışı diğer modlar da dahil olmak üzere Gemini API'ye gelen ve API'den gelen tüm girişler ve çıkışlar jetonlara ayrılır.
Jetonları aşağıdaki yöntemlerle sayabilirsiniz:
İsteği girip
count_tokens
'yi arayın.
Bu işlev, yalnızca girişteki jetonların toplam sayısını döndürür. İstemlerinizin boyutunu kontrol etmek için girişi modele göndermeden önce bu çağrıyı yapabilirsiniz.generate_content
işlevini çağırdıktan sonraresponse
nesnesindeusage_metadata
özelliğini kullanın.
Bu işlev, hem girişte hem de çıkışta toplam jeton sayısını döndürür:total_token_count
.
Ayrıca giriş ve çıkışın jeton sayılarını ayrı ayrı döndürür:prompt_token_count
(giriş jetonları) vecandidates_token_count
(çıkış jetonları).
Metin jetonlarını sayma
count_tokens
işlevini yalnızca metin içeren bir girişle çağırırsanız işlev, yalnızca girişteki metnin jeton sayısını döndürür (total_tokens
). İstemlerinizin boyutunu kontrol etmek için generate_content
işlevini çağırmadan önce bu işlevi çağırabilirsiniz.
Başka bir seçenek de generate_content
'ü çağırıp aşağıdakileri elde etmek için response
nesnesinde usage_metadata
özelliğini kullanmaktır:
- Giriş (
prompt_token_count
) ve çıkışın (candidates_token_count
) ayrı jeton sayıları - Hem girişte hem de çıkışta toplam jeton sayısı (
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 )
Çoklu turlu (sohbet) jetonları sayma
count_tokens
işlevini sohbet geçmişiyle çağırırsanız sohbetteki her rolden gelen metnin toplam jeton sayısını döndürür (total_tokens
).
Başka bir seçenek de send_message
'ü çağırıp response
nesnesinde usage_metadata
özelliğini kullanarak aşağıdakileri elde etmektir:
- Giriş (
prompt_token_count
) ve çıkışın (candidates_token_count
) ayrı jeton sayıları - Hem girişte hem de çıkışta toplam jeton sayısı (
total_token_count
)
Bir sonraki konuşma sıranızın ne kadar büyük olacağını anlamak için count_tokens
işlevini çağırırken bunu geçmişe eklemeniz gerekir.
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 )
Çok modlu jetonları sayma
Metin, resim dosyaları ve metin olmayan diğer modlar dahil olmak üzere Gemini API'ye yapılan tüm girişler jeton haline getirilir. Gemini API tarafından işleme sırasında çok modlu girişin jetonlaştırılmasıyla ilgili aşağıdaki üst düzey önemli noktaları göz önünde bulundurun:
Gemini 2.0'da, her iki boyutu da 384 pikselden küçük olan resim girişleri 258 jeton olarak sayılır. Bir veya her iki boyutu da daha büyük olan resimler, gerektiği şekilde kırpılır ve 768x768 piksellik karolara ölçeklendirilir. Her karo 258 jeton olarak sayılır. Gemini 2.0'dan önce, resimler sabit 258 jeton kullanıyordu.
Video ve ses dosyaları aşağıdaki sabit hızlarda jetona dönüştürülür: video için saniyede 263 jeton, ses için saniyede 32 jeton.
Resim dosyaları
count_tokens
işlevini metin ve resim girişiyle çağırırsanız işlev, metin ve resmin birleşik jeton sayısını yalnızca girişte (total_tokens
) döndürür. İstemlerinizin boyutunu kontrol etmek için generate_content
işlevini çağırmadan önce bu çağrıyı yapabilirsiniz. İsteğe bağlı olarak metin ve dosya üzerinde count_tokens
işlevini ayrı ayrı da çağırabilirsiniz.
Başka bir seçenek de generate_content
'ü çağırıp response
nesnesinde usage_metadata
özelliğini kullanarak aşağıdakileri elde etmektir:
- Giriş (
prompt_token_count
) ve çıkışın (candidates_token_count
) ayrı jeton sayıları - Hem girişte hem de çıkışta toplam jeton sayısı (
total_token_count
)
File API'den yüklenen bir resmi kullanan örnek:
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 )
Resmi satır içi veri olarak sağlayan örnek:
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 )
Video veya ses dosyaları
Ses ve video, aşağıdaki sabit ücretlerde jetona dönüştürülür:
- Video: Saniyede 263 jeton
- Ses: Saniyede 32 jeton
count_tokens
işlevini metin ve video/ses girişi ile çağırırsanız metin ile video/ses dosyasının birleşik jeton sayısını yalnızca girişte (total_tokens
) döndürür. İstemlerinizin boyutunu kontrol etmek için generate_content
işlevini çağırmadan önce bu işlevi çağırabilirsiniz. İsterseniz metin ve dosya üzerinde count_tokens
işlevini ayrı ayrı da çağırabilirsiniz.
Başka bir seçenek de generate_content
'ü çağırıp aşağıdakileri elde etmek için response
nesnesinde usage_metadata
özelliğini kullanmaktır:
- Giriş (
prompt_token_count
) ve çıkışın (candidates_token_count
) ayrı jeton sayıları - Hem girişte hem de çıkışta toplam jeton sayısı (
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 )
Sistem talimatları ve araçları
Sistem talimatları ve araçları da girişin toplam jeton sayısına dahil edilir.
Sistem talimatlarını kullanırsanız total_tokens
sayısı, system_instruction
eklenmesini yansıtacak şekilde artar.
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 )
İşlev çağrısı kullanırsanız total_tokens
sayısı, tools
eklenmesini yansıtacak şekilde artar.
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 )