赞
踩
ChatGPT 按 token 计费,当你把一段长文本发送给它时,你如何计算该文本消耗了多少 token?
在非流式访问的情况下,ChatGPT 的回复信息中包含有 token 消耗数量。但是在流式访问的情况下,回复信息里没有 token 数量,因此必须自己计算。下面是 Javascript 中使用GPT-3-Encoder 来计算文本的 token 数量的方法。
首先安装该库
npm install gpt-3-encoder
计算
下面是计算的示例代码:
const {encode, decode} = require('gpt-3-encoder')
const str = 'This is an example sentence to try encoding out on!'
const encoded = encode(str)
console.log('Token number: ', encoded.length)
上面代码运行结果为:
Token number: 11
基本上,一个简单的英文单词是一个token,一个复杂的英文单词可能包含了2~4个token,一个中文字符是1~3
个token。
在上面的代码后面加上以下代码,就可以打印出token的详细结果:
for(let token of encoded){
console.log({token, string: decode([token])})
}
结果:
{ token: 1212, string: 'This' }
{ token: 318, string: ' is' }
{ token: 281, string: ' an' }
{ token: 1672, string: ' example' }
{ token: 6827, string: ' sentence' }
{ token: 284, string: ' to' }
{ token: 1949, string: ' try' }
{ token: 21004, string: ' encoding' }
{ token: 503, string: ' out' }
{ token: 319, string: ' on' }
{ token: 0, string: '!' }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。