ChatGPT采用流式请求后,如何优雅计算指令与回答的Token数

1、什么是token?

每次请求输入的提示词和返回的答案,都占用token。

非流式请求请求返回值会展示本次请求token使用情况(流式请求不会返回),也可以通过算法本地计算,每1000token进行一次计费,1000个token大约为700个英文单词或450(davinci)~900(GPT3.5/4)个汉字。

2、官方接口返回情况?

在使用 ChatGPT 的 Create chat completion (长对话) 接口中,若不启用 stream 选项,接口返回的格式为:

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

其中的 usage 字段记录了本次「对话」提问消耗的 token,回答消耗的 token,以及总共消耗的 token 数。

但是启用 stream 选项后,接口返回的每个 deltas 的格式为:

...  // 其它 deltas
{
  "id":"chatcmpl76y3gsGmxYfioodOWIFgxxxxxV",
  "object":"chat.completion.chunk",
  "created":1681895111,
  "model":"gpt-3.5-turbo-0301",
  "choices":[
    {
      "delta":{"content":"xx""},
      "index":0,
      "finish_reason":null
    }
  ]
}
...  // 其它 deltas

可以看到发过来的每个 deltas 少了 usage 字段,那怎么获得本次「对话」消耗的 token 呢,官方文档 中这样介绍:

Another small drawback of streaming responses is that the response no longer includes the usage field to tell you how many tokens were consumed. After receiving and combining all of the responses, you can calculate this yourself using tiktoken.

它让我们自己使用 tiktoken 这个工具来计算对话的 token。好吧,点开它,发现它没有 Java 的官方库(gpt-3.5-turbo 使用的是 cl100k_base 编码)。

3、如何优雅实现?

直接上代码:

JTokkit is a Java tokenizer library designed for use with OpenAI models. 我们依赖了JTokkit。 引入最新中央仓库依赖:

<dependency>
    <groupId>com.knuddels</groupId>
    <artifactId>jtokkit</artifactId>
    <version>0.5.1</version>
</dependency>

使用也十分优雅简单:

public int tokens(String content)  {
    EncodingRegistry registry = Encodings.newLazyEncodingRegistry();
    Encoding encoding = registry.getEncoding(EncodingType.CL100K_BASE);
    return encoding.countTokens(content);
}


彩蛋:

AIGC你问我答小站生成式AI服务),提供GPT3.5、GPT4、 AI绘画、语音、翻译等功能。无需翻墙,无需注册账号。欢迎访问体验:https://aigc.kungfu.wang/

评论区

小飞象

2023-06-27 14:50

即拿即用

热门分享

扫码入社