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.

87 rindas
3.5KB

  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. import tiktoken
  52. try:
  53. encoding = tiktoken.encoding_for_model(model)
  54. except KeyError:
  55. logger.debug("Warning: model not found. Using cl100k_base encoding.")
  56. encoding = tiktoken.get_encoding("cl100k_base")
  57. if model == "gpt-3.5-turbo" or model == "gpt-35-turbo":
  58. return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301")
  59. elif model == "gpt-4":
  60. return num_tokens_from_messages(messages, model="gpt-4-0314")
  61. elif model == "gpt-3.5-turbo-0301":
  62. tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
  63. tokens_per_name = -1 # if there's a name, the role is omitted
  64. elif model == "gpt-4-0314":
  65. tokens_per_message = 3
  66. tokens_per_name = 1
  67. else:
  68. logger.warn(f"num_tokens_from_messages() is not implemented for model {model}. Returning num tokens assuming gpt-3.5-turbo-0301.")
  69. return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301")
  70. num_tokens = 0
  71. for message in messages:
  72. num_tokens += tokens_per_message
  73. for key, value in message.items():
  74. num_tokens += len(encoding.encode(value))
  75. if key == "name":
  76. num_tokens += tokens_per_name
  77. num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
  78. return num_tokens