openai推出了tiktoken工具用于统计输出的tokens数量,只要在最后一个tokens输出后将前面的tokens累积交给tiktokoen计算即可。
# -*- coding: utf-8 -*- import tiktoken def num_tokens_from_string(string: str, encoding_name: str) -> int: # Returns the number of tokens in a text string. encoding = tiktoken.get_encoding(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens print(num_tokens_from_string('今天几号?', 'cl100k_base'))其中编码方式展示了大模型是如何编码为tokens,不同的编码计算的token是不一样,这是三种编码方式适用的大模型
tiktokens已经开源,
https://github.com/openai/tiktoken
而且GitHub也有除python外其他语言的版本
https://github.com/search?q=tiktoken&type=repositories
网友回复