Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

chat_gpt_session.py 3.6KB

1 ano atrás
1 ano atrás
1 ano atrás
1 ano atrás
1 ano atrás
1 ano atrás
1 ano atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. if model in ["gpt-3.5-turbo-0301", "gpt-35-turbo"]:
  53. return num_tokens_from_messages(messages, model="gpt-3.5-turbo")
  54. elif model in ["gpt-4-0314", "gpt-4-0613", "gpt-4-32k", "gpt-4-32k-0613", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613"]:
  55. return num_tokens_from_messages(messages, model="gpt-4")
  56. try:
  57. encoding = tiktoken.encoding_for_model(model)
  58. except KeyError:
  59. logger.debug("Warning: model not found. Using cl100k_base encoding.")
  60. encoding = tiktoken.get_encoding("cl100k_base")
  61. if model == "gpt-3.5-turbo":
  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":
  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.")
  69. return num_tokens_from_messages(messages, model="gpt-3.5-turbo")
  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