Tìm hiểu và tính mã thông báo


Gemini và các mô hình AI tạo sinh khác xử lý dữ liệu đầu vào và đầu ra ở mức độ chi tiết có tên là mã thông báo.

Hướng dẫn này giải thích cách nhận cửa sổ ngữ cảnh của các mô hình cụ thể, cũng như cách đếm mã thông báo cho các trường hợp sử dụng như nhập văn bản, trò chuyện, đa phương thức phương thức nhập, lệnh và công cụ của hệ thống.

Giới thiệu về mã thông báo

Mã thông báo có thể là các ký tự đơn như z hoặc toàn bộ các từ như cat. Từ dài đều được chia thành nhiều mã thông báo. Tập hợp tất cả các mã thông báo mà mô hình sử dụng là có tên là từ vựng và quá trình tách văn bản thành các mã thông báo được gọi là mã thông báo.

Đối với các mô hình Gemini, một mã thông báo tương đương với khoảng 4 ký tự. 100 token bằng khoảng 60-80 từ tiếng Anh.

Khi bật tính năng thanh toán, chi phí của cuộc gọi đến Gemini API là được xác định một phần theo số lượng mã thông báo đầu vào và đầu ra, vì vậy, nếu biết cách mã đếm số có thể hữu ích.

Xem trên ai.google.dev Chạy trong Google Colab Xem nguồn trên GitHub

Cửa sổ ngữ cảnh

Các mô hình có sẵn thông qua API Gemini có các cửa sổ ngữ cảnh được đo lường bằng mã thông báo. Cửa sổ ngữ cảnh xác định lượng thông tin đầu vào bạn có thể cung cấp và mức đầu ra mà mô hình đó có thể tạo ra. Bạn có thể xác định kích thước của cửa sổ ngữ cảnh bằng cách sử dụng API hoặc bằng cách xem trong tài liệu về mô hình.

Trong ví dụ sau, bạn có thể thấy rằng mô hình gemini-1.0-pro-001 có đầu vào là khoảng 30.000 token và giới hạn đầu ra là khoảng 2.000 token. nghĩa là một cửa sổ ngữ cảnh chứa khoảng 32.000 mã thông báo.

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 )

Một ví dụ khác là nếu bạn yêu cầu hạn mức mã thông báo cho một mô hình như gemini-1.5-flash-001, bạn sẽ thấy lớp này có cửa sổ ngữ cảnh 2 triệu.

Đếm mã

Mọi dữ liệu đầu vào và đầu ra của Gemini API đều được mã hoá, bao gồm cả văn bản, hình ảnh tệp và các phương thức phi văn bản khác.

Bạn có thể đếm mã thông báo theo các cách sau:

Đếm mã thông báo văn bản

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 )

Đếm mã thông báo cho cuộc trò chuyện nhiều lượt

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 )

Đếm mã thông báo đa phương thức

Mọi dữ liệu đầu vào cho Gemini API đều được mã hoá, bao gồm cả tệp văn bản, hình ảnh và các dữ liệu khác phương thức phi văn bản. Xin lưu ý các điểm chính sau đây về hoạt động mã hoá dữ liệu nhập đa phương thức trong quá trình xử lý của Gemini API:

  • Hình ảnh được coi là kích thước cố định, vì vậy chúng sử dụng số lượng (hiện là 258 mã thông báo), bất kể kích thước hiển thị hoặc kích thước tệp.

  • Tệp video và âm thanh được chuyển đổi thành mã thông báo theo tỷ lệ cố định sau đây: cho video với tốc độ 263 mã thông báo mỗi giây và âm thanh với 32 mã thông báo mỗi giây.

Tệp hình ảnh

Trong quá trình xử lý, Gemini API coi hình ảnh là một kích thước cố định nên chúng sử dụng một số lượng mã thông báo cố định (hiện là 258 mã), bất kể kích thước tệp hoặc màn hình.

Ví dụ về cách sử dụng hình ảnh được tải lên qua 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 )

Ví dụ cung cấp hình ảnh dưới dạng dữ liệu cùng dòng:

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 )

Tệp video hoặc âm thanh

Mỗi âm thanh và video đều được chuyển đổi thành mã thông báo theo các mức giá cố định sau:

  • Video: 263 mã thông báo mỗi giây
  • Âm thanh: 32 mã thông báo mỗi giây
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 )

Công cụ và hướng dẫn về hệ thống

Các hướng dẫn của hệ thống và công cụ cũng được tính vào tổng số mã thông báo cho đầu vào.

Nếu bạn sử dụng hướng dẫn của hệ thống, số lượng total_tokens sẽ tăng lên để phản ánh thêm 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 )

Nếu bạn sử dụng lệnh gọi hàm, số lượng total_tokens sẽ tăng để phản ánh thêm 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 )