Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

102 rindas
4.0KB

  1. from bot.session_manager import Session
  2. from common.log import logger
  3. from common import const
  4. """
  5. e.g. [
  6. {"role": "system", "content": "You are a helpful assistant."},
  7. {"role": "user", "content": "Who won the world series in 2020?"},
  8. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  9. {"role": "user", "content": "Where was it played?"}
  10. ]
  11. """
  12. class ChatGPTSession(Session):
  13. def __init__(self, session_id, system_prompt=None, model="gpt-3.5-turbo"):
  14. super().__init__(session_id, system_prompt)
  15. self.model = model
  16. self.reset()
  17. def discard_exceeding(self, max_tokens, cur_tokens=None):
  18. precise = True
  19. try:
  20. cur_tokens = self.calc_tokens()
  21. except Exception as e:
  22. precise = False
  23. if cur_tokens is None:
  24. raise e
  25. logger.debug("Exception when counting tokens precisely for query: {}".format(e))
  26. while cur_tokens > max_tokens:
  27. if len(self.messages) > 2:
  28. self.messages.pop(1)
  29. elif len(self.messages) == 2 and self.messages[1]["role"] == "assistant":
  30. self.messages.pop(1)
  31. if precise:
  32. cur_tokens = self.calc_tokens()
  33. else:
  34. cur_tokens = cur_tokens - max_tokens
  35. break
  36. elif len(self.messages) == 2 and self.messages[1]["role"] == "user":
  37. logger.warn("user message exceed max_tokens. total_tokens={}".format(cur_tokens))
  38. break
  39. else:
  40. logger.debug("max_tokens={}, total_tokens={}, len(messages)={}".format(max_tokens, cur_tokens, len(self.messages)))
  41. break
  42. if precise:
  43. cur_tokens = self.calc_tokens()
  44. else:
  45. cur_tokens = cur_tokens - max_tokens
  46. return cur_tokens
  47. def calc_tokens(self):
  48. return num_tokens_from_messages(self.messages, self.model)
  49. # refer to https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
  50. def num_tokens_from_messages(messages, model):
  51. """Returns the number of tokens used by a list of messages."""
  52. if model in ["wenxin", "xunfei", const.GEMINI]:
  53. return num_tokens_by_character(messages)
  54. import tiktoken
  55. if model in ["gpt-3.5-turbo-0301", "gpt-35-turbo", "gpt-3.5-turbo-1106"]:
  56. return num_tokens_from_messages(messages, model="gpt-3.5-turbo")
  57. elif model in ["gpt-4-0314", "gpt-4-0613", "gpt-4-32k", "gpt-4-32k-0613", "gpt-3.5-turbo-0613",
  58. "gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613", "gpt-35-turbo-16k", const.GPT4_TURBO_PREVIEW, const.GPT4_VISION_PREVIEW]:
  59. return num_tokens_from_messages(messages, model="gpt-4")
  60. try:
  61. encoding = tiktoken.encoding_for_model(model)
  62. except KeyError:
  63. logger.debug("Warning: model not found. Using cl100k_base encoding.")
  64. encoding = tiktoken.get_encoding("cl100k_base")
  65. if model == "gpt-3.5-turbo":
  66. tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
  67. tokens_per_name = -1 # if there's a name, the role is omitted
  68. elif model == "gpt-4":
  69. tokens_per_message = 3
  70. tokens_per_name = 1
  71. else:
  72. logger.warn(f"num_tokens_from_messages() is not implemented for model {model}. Returning num tokens assuming gpt-3.5-turbo.")
  73. return num_tokens_from_messages(messages, model="gpt-3.5-turbo")
  74. num_tokens = 0
  75. for message in messages:
  76. num_tokens += tokens_per_message
  77. for key, value in message.items():
  78. num_tokens += len(encoding.encode(value))
  79. if key == "name":
  80. num_tokens += tokens_per_name
  81. num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
  82. return num_tokens
  83. def num_tokens_by_character(messages):
  84. """Returns the number of tokens used by a list of messages."""
  85. tokens = 0
  86. for msg in messages:
  87. tokens += len(msg["content"])
  88. return tokens