OpenAI的编码方式Tiktoken

OpenAI模型的编码方式

        OpenAI的模型使用自己的开源的库Tiktoken进行字符的编码。Tiktoken支持三种OpenAI模型的字符编码:

Encoding nameOpenAI models
cl100k_basegpt-4gpt-3.5-turbotext-embedding-ada-002
p50k_baseCodex models, text-davinci-002text-davinci-003
r50k_base (or gpt2)GPT-3 models like davinci

可以通过以下两种方式进行字符编码器定义:

encoding = tiktoken.encoding_for_model('gpt-3.5-turbo')
encoding = tiktoken.get_encoding("cl100k_base")

使用方法docede和encode进行字符和token id之间的转换。

encoding.encode("tiktoken is great!")
>>>
[83, 1609, 5963, 374, 2294, 0]


encoding.decode([83, 1609, 5963, 374, 2294, 0])
>>>
'tiktoken is great!'

对话补全API的token计算方式

        以下代码来自openai-cookbook,可以实现对openai不同的chat completions api接口输入messages的token长度计算。

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 = 3
        tokens_per_name = 1
    elif model == "gpt-3.5-turbo-0301":
        tokens_per_message = 4  # every message follows <|start|>{role/name}\n{content}<|end|>\n
        tokens_per_name = -1  # if there's a name, the role is omitted
    elif "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 = 0
    for message in messages:
        num_tokens += tokens_per_message
        for key, value in message.items():
            num_tokens += len(encoding.encode(value))
            if key == "name":
                num_tokens += tokens_per_name
    num_tokens += 3  # every reply is primed with <|start|>assistant<|message|>
    return num_tokens

        可以看出gpt-3.5-turbo-0301版本的计算方式和其他模型有所区别。主要区别在与连接字符设置的变化,message中name关键词的处理有所不同。

token计算实践中的问题

        使用上述的代码进行prompt tokens length计算的时候发现,与openai的api返回长度出现了不一致的现象。messages的格式中四种role:system、user、assistant、function。当role为function的时候,会需要添加一个name的关键词,所以当我在messages中添加了带有function的message时就会出现上诉情况。

        为了使chatgpt能够实现实时信息的回复,定义了一个get_info_from_web的函数用于实时搜索网络信息供chatgpt调用以便获得更好的问题答案。所以当我询问的问题为:今天杭州天气怎么样?,并且chatgpt通过function call功能获得网络信息之后构造的新的messages:

[{
      'role': 'system',
      'content': "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous. "},
 {
      'role': 'user', 
      'content': '今天杭州天气怎么样?'},
 {    
      'role': 'function', 
      'name': 'get_info_from_web', 
      'content': '86°F'}
]

        上述的messages调用chatgpt:

response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo-0613",
                messages=messages,
                temperature=0,
            )
print(response)

>>>
{
  "id": "chatcmpl-xxxxxxx",
  "object": "chat.completion",
  "created": xxxxxxxx,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "今天杭州的天气是86°F。请问还有其他关于天气的信息需要我提供吗?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 56,
    "completion_tokens": 32,
    "total_tokens": 88
  }
}

        从上述的代码结果看到prompt tokens length为56,而同样的messages调用openai-cookbook中的方法的结果为58,两者的计算结果相差了2个token长度。

分析

        以上的不一致问题只会出现在messages中的message包含了name关键, 也就是说在使用function这个role的时候才会发生,并且每添加一个有function的message,最后的token差距增加2。所以可以看出问题应该是出现在role为function的message环节的计算上,我猜测是gpt-3.5-turbo-0613模型使用了和gpt-3.5-turbo-0301一样的tokens_per_name,使用了-1而不是1,所以会出现2的差距。

        上面的现象和推测是本人的测试结果和猜测,希望有知道其中原因的朋友可以指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值