You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

chat_gpt_session.py 3.9KB

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