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.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 = num_tokens_from_messages(self.messages, self.model)
  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 = num_tokens_from_messages(self.messages, self.model)
  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 = num_tokens_from_messages(self.messages, self.model)
  43. else:
  44. cur_tokens = cur_tokens - max_tokens
  45. return cur_tokens
  46. # refer to https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
  47. def num_tokens_from_messages(messages, model):
  48. """Returns the number of tokens used by a list of messages."""
  49. import tiktoken
  50. try:
  51. encoding = tiktoken.encoding_for_model(model)
  52. except KeyError:
  53. logger.debug("Warning: model not found. Using cl100k_base encoding.")
  54. encoding = tiktoken.get_encoding("cl100k_base")
  55. if model == "gpt-3.5-turbo":
  56. return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301")
  57. elif model == "gpt-4":
  58. return num_tokens_from_messages(messages, model="gpt-4-0314")
  59. elif model == "gpt-3.5-turbo-0301":
  60. tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
  61. tokens_per_name = -1 # if there's a name, the role is omitted
  62. elif model == "gpt-4-0314":
  63. tokens_per_message = 3
  64. tokens_per_name = 1
  65. else:
  66. logger.warn(f"num_tokens_from_messages() is not implemented for model {model}. Returning num tokens assuming gpt-3.5-turbo-0301.")
  67. return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301")
  68. num_tokens = 0
  69. for message in messages:
  70. num_tokens += tokens_per_message
  71. for key, value in message.items():
  72. num_tokens += len(encoding.encode(value))
  73. if key == "name":
  74. num_tokens += tokens_per_name
  75. num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
  76. return num_tokens