ChatGPT api 启用 stream 返回时,无法统计 token 的解决思路

在使用 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 编码)。

正当失落之际,随便 google 了一下 Tokenizer libraries by java,在 一个帖子 中发现了还是有一位老哥自己用 Java 实现了的,GitHub 地址为:https://github.com/knuddelsgmbh/jtokkit

实测后,确实不错,分享给大家。

posted @ 2023-04-19 18:27    阅读(1322)  评论(0)    收藏  举报