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.

baidu_wenxin_session.py 3.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from bot.session_manager import Session
  2. from common.log import logger
  3. """
  4. e.g. [
  5. {"role": "user", "content": "Who won the world series in 2020?"},
  6. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  7. {"role": "user", "content": "Where was it played?"}
  8. ]
  9. """
  10. class BaiduWenxinSession(Session):
  11. def __init__(self, session_id, system_prompt=None, model="gpt-3.5-turbo"):
  12. super().__init__(session_id, system_prompt)
  13. self.model = model
  14. # 百度文心不支持system prompt
  15. # self.reset()
  16. def discard_exceeding(self, max_tokens, cur_tokens=None):
  17. # pdb.set_trace()
  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. import tiktoken
  53. if model in ["gpt-3.5-turbo-0301", "gpt-35-turbo"]:
  54. return num_tokens_from_messages(messages, model="gpt-3.5-turbo")
  55. 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", "gpt-35-turbo-16k"]:
  56. return num_tokens_from_messages(messages, model="gpt-4")
  57. try:
  58. encoding = tiktoken.encoding_for_model(model)
  59. except KeyError:
  60. logger.debug("Warning: model not found. Using cl100k_base encoding.")
  61. encoding = tiktoken.get_encoding("cl100k_base")
  62. if model == "gpt-3.5-turbo":
  63. tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
  64. tokens_per_name = -1 # if there's a name, the role is omitted
  65. elif model == "gpt-4":
  66. tokens_per_message = 3
  67. tokens_per_name = 1
  68. else:
  69. logger.warn(f"num_tokens_from_messages() is not implemented for model {model}. Returning num tokens assuming gpt-3.5-turbo.")
  70. return num_tokens_from_messages(messages, model="gpt-3.5-turbo")
  71. num_tokens = 0
  72. for message in messages:
  73. num_tokens += tokens_per_message
  74. for key, value in message.items():
  75. num_tokens += len(encoding.encode(value))
  76. if key == "name":
  77. num_tokens += tokens_per_name
  78. num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
  79. return num_tokens