如何计算 ChatGPT 的 Tokens 数量?

一、基本介绍

随着人工智能大模型技术的迅速发展,一种创新的计费模式正在逐渐普及,即以“令牌”(Token)作为衡量使用成本的单位。那么,究竟什么是Token呢?

Token 是一种将自然语言文本转化为计算机可以理解的形式——词向量的手段。这个转化过程涉及对文本进行分词处理,将每个单词、汉字或字符转换为唯一的词向量表示。通过计算这些词向量在模型中的使用次数,服务提供商就能够量化用户所消耗的计算资源,并据此收取费用。

需要注意的是,不同的厂商可能采用不同的方式来定义和计算 Token。一般来说,一个 Token 可能代表一个汉字、一个英文单词,或者一个字符。

在大模型领域,通常情况下,服务商倾向于以千 Tokens(1K Tokens)为单位进行计费。用户可以通过购买一定数量的 Token 来支付模型训练和推理过程中产生的费用。
注意:Token的数量与使用模型的服务次数或数据处理量有关。一般是有梯度的,用得越多可以拿到越便宜的价格,和买东西的道理一样,零售一个价,批发一个价。

二、如何计算 Tokens 数量?

具体要怎么计算 Tokens 数量,这个需要官方提供计算方式,或提供接口,或提供源码。
这里以 openAI 的 GPT 为例,介绍 Tokens 的计算方式。

openAI 官方提供了两种计算方式:网页计算、接口计算。

2.1 网页计算

网页计算顾名思义,就是打开网页输入文字,然后直接计算结果,网页的链接是:https://platform.openai.com/tokenizer。
曾经看到一个粗略的说法:1 个 Token 大约相当于 4 个英文字符或 0.75 个英文单词;而一个汉字则大约需要 1.5 个 Token 来表示。真实性未知,但从个人经验,一个汉字似乎没有达到 1.5 个 Token 这么多。
随意举三个例子:
【例子1】以下十个汉字计算得到的 Token 数是 14 个。​

一二三四五六七八九十

image.png
【例子2】以下 11 个汉字加2个标点计算得到的 Token 数是 13 个。

今天是十二月一日,星期五。

image.png
【例子3】以下 这段话计算得到的 Token 数是 236 个。

人工智能是智能学科重要的组成部分,它企图了解智能的实质,并生产出一种新的能以人类智能相似的方式做出反应的智能机器,该领域的研究包括机器人、语言识别、图像识别、自然语言处理和专家系统等。人工智能从诞生以来,理论和技术日益成熟,应用领域也不断扩大,可以设想,未来人工智能带来的科技产品,将会是人类智慧的“容器”。人工智能可以对人的意识、思维的信息过程的模拟。人工智能不是人的智能,但能像人那样思考、也可能超过人的智能。

image.png

2.2 接口计算

接下来看看怎么使用 Python 接口实现 Token 计算。
相关链接:https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
从 Note 中可以了解到,要计算 Tokens 需要安装两个第三方包:tiktokenopenai。第一个包不需要 GPT 的 API Key 和 API Secret 便可使用,第二个需要有GPT 的 API Key 和 API Secret 才能使用,由于某些限制,还需要海外代理。
不过,好消息是openai可以不用,使用tiktoken来计算即可。

先安装tiktoken包:

pip install tiktoken

注:我使用的是 Python 3.9,默认安装的tiktoken版本是 0.5.1。
安装好tiktoken之后,直接看最后两个 cell(In[14] 和 In[15])。
image.png
完整代码如下:

def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):"""Return the number of tokens used by a list of messages."""try:encoding = tiktoken.encoding_for_model(model)except KeyError:print("Warning: model not found. Using cl100k_base encoding.")encoding = tiktoken.get_encoding("cl100k_base")if model in {"gpt-3.5-turbo-0613","gpt-3.5-turbo-16k-0613","gpt-4-0314","gpt-4-32k-0314","gpt-4-0613","gpt-4-32k-0613",}:tokens_per_message = 3tokens_per_name = 1elif model == "gpt-3.5-turbo-0301":tokens_per_message = 4  # every message follows <|start|>{role/name}\n{content}<|end|>\ntokens_per_name = -1  # if there's a name, the role is omittedelif "gpt-3.5-turbo" in model:print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")elif "gpt-4" in model:print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")return num_tokens_from_messages(messages, model="gpt-4-0613")else:raise NotImplementedError(f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")num_tokens = 0for message in messages:num_tokens += tokens_per_messagefor key, value in message.items():num_tokens += len(encoding.encode(value))if key == "name":num_tokens += tokens_per_namenum_tokens += 3  # every reply is primed with <|start|>assistant<|message|>return num_tokens
# let's verify the function above matches the OpenAI API responseimport openaiexample_messages = [{"role": "system","content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English.",},{"role": "system","name": "example_user","content": "New synergies will help drive top-line growth.",},{"role": "system","name": "example_assistant","content": "Things working well together will increase revenue.",},{"role": "system","name": "example_user","content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage.",},{"role": "system","name": "example_assistant","content": "Let's talk later when we're less busy about how to do better.",},{"role": "user","content": "This late pivot means we don't have time to boil the ocean for the client deliverable.",},
]for model in ["gpt-3.5-turbo-0301","gpt-3.5-turbo-0613","gpt-3.5-turbo","gpt-4-0314","gpt-4-0613","gpt-4",]:print(model)# example token count from the function defined aboveprint(f"{num_tokens_from_messages(example_messages, model)} prompt tokens counted by num_tokens_from_messages().")# example token count from the OpenAI APIresponse = openai.ChatCompletion.create(model=model,messages=example_messages,temperature=0,max_tokens=1,  # we're only counting input tokens here, so let's not waste tokens on the output)print(f'{response["usage"]["prompt_tokens"]} prompt tokens counted by the OpenAI API.')print()

接下来处理一下以上代码,把 In[15] 中,和openai包相关的内容可以直接注释掉,然后执行代码。处理之后,可直接执行代码如下:

import tiktoken
def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):"""Return the number of tokens used by a list of messages."""try:encoding = tiktoken.encoding_for_model(model)except KeyError:print("Warning: model not found. Using cl100k_base encoding.")encoding = tiktoken.get_encoding("cl100k_base")if model in {"gpt-3.5-turbo-0613","gpt-3.5-turbo-16k-0613","gpt-4-0314","gpt-4-32k-0314","gpt-4-0613","gpt-4-32k-0613",}:tokens_per_message = 3tokens_per_name = 1elif model == "gpt-3.5-turbo-0301":tokens_per_message = 4  # every message follows <|start|>{role/name}\n{content}<|end|>\ntokens_per_name = -1  # if there's a name, the role is omittedelif "gpt-3.5-turbo" in model:print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")elif "gpt-4" in model:print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")return num_tokens_from_messages(messages, model="gpt-4-0613")else:raise NotImplementedError(f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")num_tokens = 0for message in messages:num_tokens += tokens_per_messagefor key, value in message.items():num_tokens += len(encoding.encode(value))if key == "name":num_tokens += tokens_per_namenum_tokens += 3  # every reply is primed with <|start|>assistant<|message|>return num_tokens
# let's verify the function above matches the OpenAI API responseexample_messages = [{"role": "system","content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English.",},{"role": "system","name": "example_user","content": "New synergies will help drive top-line growth.",},{"role": "system","name": "example_assistant","content": "Things working well together will increase revenue.",},{"role": "system","name": "example_user","content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage.",},{"role": "system","name": "example_assistant","content": "Let's talk later when we're less busy about how to do better.",},{"role": "user","content": "This late pivot means we don't have time to boil the ocean for the client deliverable.",},
]for model in ["gpt-3.5-turbo-0301","gpt-3.5-turbo-0613","gpt-3.5-turbo","gpt-4-0314","gpt-4-0613","gpt-4",]:print(model)# example token count from the function defined aboveprint(f"{num_tokens_from_messages(example_messages, model)} prompt tokens counted by num_tokens_from_messages().")print()

运行结果如下图:
image.png

小解析:

  • example_messages变量是一个列表,列表的元素是字典,这个是 GPT 的数据结构,在这个示例代码中,整个列表作为 GPT 的 prompt 输入,所以计算的是整个的 Token 数。
  • 不同的模型,对于 prompt 的计算规则有一点点不同,重点在于数据结构多出的字符。

问题1:实际生产中的数据,可能不是这样的,更多时候是存一个字符串,又该怎么处理?
demo 是从列表解析出键content的值,这个比较简单,如果是要从字符串中去解析相关的数据,则需要多加一步转化,使用json包将字符串转化为列表,然后其他的处理方式保持一致即可。
参考如下:

import tiktoken,json
def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):"""Return the number of tokens used by a list of messages."""try:encoding = tiktoken.encoding_for_model(model)except KeyError:print("Warning: model not found. Using cl100k_base encoding.")encoding = tiktoken.get_encoding("cl100k_base")if model in {"gpt-3.5-turbo-0613","gpt-3.5-turbo-16k-0613","gpt-4-0314","gpt-4-32k-0314","gpt-4-0613","gpt-4-32k-0613",}:tokens_per_message = 3tokens_per_name = 1elif model == "gpt-3.5-turbo-0301":tokens_per_message = 4  # every message follows <|start|>{role/name}\n{content}<|end|>\ntokens_per_name = -1  # if there's a name, the role is omittedelif "gpt-3.5-turbo" in model:print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")elif "gpt-4" in model:print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")return num_tokens_from_messages(messages, model="gpt-4-0613")else:raise NotImplementedError(f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")# 结构转化,结构不完整则返回0try:messages = json.loads(messages)num_tokens = 0for message in messages:num_tokens += tokens_per_messagefor key, value in message.items():num_tokens += len(encoding.encode(value))if key == "name":num_tokens += tokens_per_namenum_tokens += 3  # every reply is primed with <|start|>assistant<|message|>except json.JSONDecodeError:num_tokens = 0return num_tokens
# let's verify the function above matches the OpenAI API responseexample_messages = [{"role": "system","content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English.",},{"role": "system","name": "example_user","content": "New synergies will help drive top-line growth.",},{"role": "system","name": "example_assistant","content": "Things working well together will increase revenue.",},{"role": "system","name": "example_user","content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage.",},{"role": "system","name": "example_assistant","content": "Let's talk later when we're less busy about how to do better.",},{"role": "user","content": "This late pivot means we don't have time to boil the ocean for the client deliverable.",},
]
example_messages = json.dumps(example_messages)# 假设使用的是 "gpt-4-0613" 模型
model = "gpt-4-0613"
print(f"{num_tokens_from_messages(example_messages, model)} prompt tokens counted by num_tokens_from_messages().")

问题2:在网页计算小节中使用的字符串跑出来的数据是否和tiktoken一样呢?
实现这个验证很简单,把上面的代码再做简化,直接计算字符串即可。参考逻辑如下:

import tiktokendef num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):"""Return the number of tokens used by a list of messages."""try:encoding = tiktoken.encoding_for_model(model)except KeyError:print("Warning: model not found. Using cl100k_base encoding.")encoding = tiktoken.get_encoding("cl100k_base")num_tokens = len(encoding.encode(messages))return num_tokensstr1 = num_tokens_from_messages('一二三四五六七八九十')
str2 = num_tokens_from_messages('今天是十二月一日,星期五。')
str3 = num_tokens_from_messages('人工智能是智能学科重要的组成部分,它企图了解智能的实质,并生产出一种新的能以人类智能相似的方式做出反应的智能机器,该领域的研究包括机器人、语言识别、图像识别、自然语言处理和专家系统等。人工智能从诞生以来,理论和技术日益成熟,应用领域也不断扩大,可以设想,未来人工智能带来的科技产品,将会是人类智慧的“容器”。人工智能可以对人的意识、思维的信息过程的模拟。人工智能不是人的智能,但能像人那样思考、也可能超过人的智能。')print(f'字符串1长度{str1},字符串2长度{str2},字符串3长度{str3}。')

返回结果如下:
image.png
返回结果和网页计算的结果完全一致!
其实这个有点像是 GPT 给我们返回的文本数据,可以直接计算其长度,不需要像上面那么复杂,如果数据结构也是像上面一样,那就需要多加一步解析。

import tiktoken,jsondef num_tokens_from_messages(messages):"""Return the number of tokens used by a list of messages."""try:encoding = tiktoken.encoding_for_model(model)except KeyError:print("Warning: model not found. Using cl100k_base encoding.")encoding = tiktoken.get_encoding("cl100k_base")try:messages = json.loads(messages)[0]['content']num_tokens = len(encoding.encode(messages))except json.JSONDecodeError:num_tokens = 0return num_tokensexample_messages = '''[{"role": "system","content": "一二三四五六七八九十"}
]'''
print(num_tokens_from_messages(example_messages))

三、小结

本文主要介绍了 GPT 如何计算 Tokens 的方法,官方提供了两种方式:网页计算和接口计算。
网页计算不需要技术,只需要魔法即可体验,而接口计算,事实上接口计算包含了两种方法,一种使用tiktoken,则需要点 Python 基础,而openai还需要点网络基础和货币基础,需要代理和 plus 账号(20刀/月)等。


参考链接:
网页计算链接:https://platform.openai.com/tokenizer
接口使用链接:https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/198187.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

容器重启后,Conda文件完整保存(虚拟环境、库包),如何重新安装conda并迁移之前的虚拟环境

Vim安装 容器重启后默认是vi&#xff0c;升级vim&#xff0c;执行命令 apt install -y vim安装 Anaconda 1. 下载Anaconda 其他版本请查看Anaconda官方库 wget https://mirrors.bfsu.edu.cn/anaconda/archive/Anaconda3-2023.03-1-Linux-x86_64.sh --no-check-certificate…

【DBeaver】驱动添加-Hive和星环

驱动 Hive驱动 hive驱动可以直接去官网下载官网地址&#xff0c;填一下个人信息。 如果想直接下载可以去我上次的资源下地址&#xff0c;需要用zip解压。 星环驱动 星环驱动是我第一次接触&#xff0c;是国产的基于开源Hive驱动自研的产品&#xff0c;我看到官网上有很多类…

[leetcode ~二叉树] 模版

文章目录 1. 左叶子之和2. 翻转二叉树 E 1. 左叶子之和 :::details 给定二叉树的根节点 root &#xff0c;返回所有左叶子之和。 示例 1&#xff1a; 输入: root [3,9,20,null,null,15,7] 输出: 24 解释: 在这个二叉树中&#xff0c;有两个左叶子&#xff0c;分别是 9 和 15&…

跨浏览器测试:如何确保你的应用在各种浏览器上都能正常运行

在当今的互联网时代&#xff0c;浏览器已成为我们获取信息、与他人交流、工作和娱乐的主要工具。然而&#xff0c;不同的浏览器、不同的版本和不同的操作系统可能会对你的应用造成不同的影响&#xff0c;可能使其表现出各种不同的行为和问题。为了确保你的应用能在各种浏览器环…

GaussDB数据库SQL系列-序列的使用

目录 一、前言 二、GaussDB数据库中的序列 1、语法(CREATE SEQUENCE) 2、注意事项 三、GaussDB数据库中的示例 1、示例一&#xff1a;创建普通序列 2、示例二&#xff1a;创建与表关联的序列 四、小结 一、前言 在数据库管理中&#xff0c;序列&#xff08;SEQUENCE&a…

Nginx的使用

Nginx的使用 一、配置前端项目访问二、配置SSL证书1、正常配置2、配置报错 三、配置域名反向代理1、简单代理2、带参数代理3、指定后缀域名跳转4、访问反向代理域名的静态资源5、配置静态资源访问&#xff08;1&#xff09;、将域名配置到小程序&#xff0c;获得TXT文件&#x…

leetcode:对称二叉树

题目描述 题目链接&#xff1a;101. 对称二叉树 - 力扣&#xff08;LeetCode&#xff09; 题目分析 题目中说至少存在一个节点&#xff0c;所以我们只需要对比左右子树 写一个子函数对比左右子树&#xff1a;用递归的思路&#xff0c;左子树的左子树和右子树的右子树对比&…

2024 年甘肃省职业院校技能大赛中职组 电子与信息类“网络安全”赛项竞赛样题-B

2024 年甘肃省职业院校技能大赛中职组 电子与信息类“网络安全”赛项竞赛样题-B 目录 2024 年甘肃省职业院校技能大赛中职组 电子与信息类“网络安全”赛项竞赛样题-B 需要环境或者解析可以私信 &#xff08;二&#xff09;A 模块基础设施设置/安全加固&#xff08;200 分&…

使用Python Flask搭建Web问答应用程序并发布到公网远程访问

使用Python Flask搭建web问答应用程序框架&#xff0c;并发布到公网上访问 文章目录 使用Python Flask搭建web问答应用程序框架&#xff0c;并发布到公网上访问前言1. 安装部署Flask并制作SayHello问答界面2. 安装Cpolar内网穿透3. 配置Flask的问答界面公网访问地址4. 公网远程…

打开游戏提示缺少(或找不到)XINPUT1_3.DLL怎么解决

在电脑使用过程中&#xff0c;我们可能会遇到一些错误提示&#xff0c;其中之一就是xinput1_3.dll丢失。那么&#xff0c;xinput1_3.dll是什么文件&#xff1f;它对电脑有什么影响&#xff1f;本文将详细介绍xinput1_3.dll丢失的原因以及五个详细的解决方法&#xff0c;帮助大家…

帮企多城市分站系统源码+关键词排名优化推广 附带完整的搭建教程

随着市场竞争的加剧&#xff0c;企业对于网络营销的需求越来越多元化。传统的单一网站已经无法满足企业在网络营销方面的需求&#xff0c;因此我们需要开发一套多城市分站系统&#xff0c;以满足企业在不同地区、不同行业的需求。同时&#xff0c;我们还结合了关键词排名优化推…

外包干了2个月,技术明显退步了...

先说一下自己的情况&#xff0c;大专生&#xff0c;19年通过校招进入广州某软件公司&#xff0c;干了接近5年的功能测试&#xff0c;今年11月份&#xff0c;感觉自己不能够在这样下去了&#xff0c;长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测…

UE4 双屏分辨率设置

背景&#xff1a; 做了一个UI 应用&#xff0c;需要在双屏上进行显示。 分辨率如下&#xff1a;3840*1080&#xff1b; 各种折腾&#xff0c;其实很简单&#xff1a; 主要是在全屏模式的时候 一开始没有选对&#xff0c;双屏总是不稳定。 全屏模式改成&#xff1a;Windows 之…

JS加密/解密之HOOK实战

之前的章节有介绍过Javascript的Hook相关的基础知识&#xff0c;相信大部分人也知道了什么是Hook&#xff0c;今天我们来讲一下Hook实战&#xff0c;实际的运用。 0x1.事上练 // 程序员们基本都喜欢简单精辟 直入主题 不喜欢咬文嚼字 我们先直接上代码 var _log console.log…

23、什么是卷积的 Feature Map?

这一节介绍一个概念&#xff0c;什么是卷积的 Feature Map&#xff1f; Feature Map, 中文称为特征图&#xff0c;卷积的 Feature Map 指的是在卷积神经网络&#xff08;CNN&#xff09;中&#xff0c;通过卷积这一操作从输入图像中提取的特征图。 上一节用示意动图介绍了卷积算…

web自动化 -- pyppeteer

由于Selenium流行已久&#xff0c;现在稍微有点反爬的网站都会对selenium和webdriver进行识别&#xff0c;网站只需要在前端js添加一下判断脚本&#xff0c;很容易就可以判断出是真人访问还是webdriver。虽然也可以通过中间代理的方式进行js注入屏蔽webdriver检测&#xff0c;但…

MySQL笔记-第04章_运算符

视频链接&#xff1a;【MySQL数据库入门到大牛&#xff0c;mysql安装到优化&#xff0c;百科全书级&#xff0c;全网天花板】 文章目录 第04章_运算符1. 算术运算符2. 比较运算符3. 逻辑运算符4. 位运算符5. 运算符的优先级拓展&#xff1a;使用正则表达式查询 第04章_运算符 …

​ 海外服务器创新高地:亚马逊云科技树立云计算韧性标杆

云计算的大潮中&#xff0c;众多企业对云服务器的需求与日俱增。但随之而来的就是云服务器的运行对于企业的业务的重要性也越来越高。想象一下&#xff0c;如果在全球范围内运行的服务和应用程序遭遇意外中断&#xff0c;从而产生的重大影响可能会给一些企业带来严重损失。因此…

如何将整个文件内容加载到富文本控件?

众所周知&#xff0c;富文本控件&#xff0c;Rich Text Control&#xff0c;用来呈现文本内容的一个控件&#xff0c;功能上相对记事本来说更加丰富&#xff0c;但又不及 Word。 但&#xff0c;我们的目标又不是开发另外一个 Word。 我们可以使用 EM_STREAMIN 消息将整个文件…

ubuntu安装tomcat并配置前端项目

1.1查找 # 先更新 sudo apt update # 查找 apt search jdk1.2安装 sudo apt install openjdk-8-jdk1.3验证 java -version 2.安装tomcat 下载链接&#xff1a;Apache Tomcat - Apache Tomcat 8 Software Downloadshttps://tomcat.apache.org/download-80.cgi下载这个&…