当前位置:   article > 正文

GPT3.5\GPT4系列计算完整prompt token数的官方方法_gpt4 api 上下文 算tokens 吗

gpt4 api 上下文 算tokens 吗

前言:

ChatGPT如何计算token数?https://wtl4it.blog.csdn.net/article/details/135116493?spm=1001.2014.3001.5502icon-default.png?t=N7T8https://wtl4it.blog.csdn.net/article/details/135116493?spm=1001.2014.3001.5502

GPT3.5\GPT4系列计算完整prompt token数的官方方法:

How to count tokens with tiktoken | OpenAI CookbookOpen-source examples and guides for building with the OpenAI API. Browse a collection of snippets, advanced techniques and walkthroughs. Share your own examples and guides.icon-default.png?t=N7T8https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktokenhttps://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynbicon-default.png?t=N7T8https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb

计算的代码如下:
  1. def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):
  2. """Return the number of tokens used by a list of messages."""
  3. try:
  4. encoding = tiktoken.encoding_for_model(model)
  5. except KeyError:
  6. print("Warning: model not found. Using cl100k_base encoding.")
  7. encoding = tiktoken.get_encoding("cl100k_base")
  8. if model in {
  9. "gpt-3.5-turbo-0613",
  10. "gpt-3.5-turbo-16k-0613",
  11. "gpt-4-0314",
  12. "gpt-4-32k-0314",
  13. "gpt-4-0613",
  14. "gpt-4-32k-0613",
  15. }:
  16. tokens_per_message = 3
  17. tokens_per_name = 1
  18. elif model == "gpt-3.5-turbo-0301":
  19. tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
  20. tokens_per_name = -1 # if there's a name, the role is omitted
  21. elif "gpt-3.5-turbo" in model:
  22. print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
  23. return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")
  24. elif "gpt-4" in model:
  25. print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
  26. return num_tokens_from_messages(messages, model="gpt-4-0613")
  27. else:
  28. raise NotImplementedError(
  29. 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."""
  30. )
  31. num_tokens = 0
  32. for message in messages:
  33. num_tokens += tokens_per_message
  34. for key, value in message.items():
  35. num_tokens += len(encoding.encode(value))
  36. if key == "name":
  37. num_tokens += tokens_per_name
  38. num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
  39. return num_tokens

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/290412
推荐阅读
相关标签
  

闽ICP备14008679号