OpenAI
此頁面由機器翻譯。查看原文英文文章

我可以如何在嘗試嵌入字串前,知道它會有多少個 token?

計算/估算嵌入的 token 數

更新日期:13 days ago

在將字串送出作嵌入前,你可以套用 OpenAI 的 tiktoken tokenizer 程式庫,估算它會使用多少個 token。

這尤其實用,因為嵌入模型(例如 text-embedding-3-small)設有你必須遵守的 token 上限。


如何使用 Tiktoken 計算 token

你可以使用 tiktoken Python 套件來計算一個字串會產生多少個 token。

以下是範例程式碼片段:

import tiktoken

def num_tokens_from_string(string: str, encoding_name: str) -> int:
"""返回文字字串中的 token 數。"""
encoding = tiktoken.get_encoding(encoding_name)
num_tokens = len(encoding.encode(string))
return num_tokens

# 使用範例
num_tokens = num_tokens_from_string("tiktoken is great!", "cl100k_base")
print(num_tokens)

重要

  • 對於第三代嵌入模型(例如 text-embedding-3-smalltext-embedding-3-large),你應使用 "cl100k_base" 編碼。

  • 不同模型可能需要不同編碼;如有疑問,請一律參閱模型文件。


為何計算 token 很重要

  • 如果你的字串超出模型的最大輸入大小,你的 API 請求將會失敗。

  • 預先準確計算 token,可確保嵌入工作流程更順暢,並防止處理期間出錯。


實用連結

這篇文章對你有幫助嗎?