فهم الرموز المميّزة وعدّها


تعالج تطبيقات 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 رمزًا. يتم اقتصاص الصور الأكبر حجمًا في أحد الأبعاد أو كليهما وتعديل حجمها كما هو مطلوب لتصبح مربّعات بحجم 768 × 768 بكسل، ويتم احتساب كل منها على أنّه 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 باستخدام إدخال نصي وفيديو/صوت، سيعرض 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 )