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.

106 lines
4.0KB

  1. from common.expired_dict import ExpiredDict
  2. from common.log import logger
  3. from config import conf
  4. import json
  5. class Session(object):
  6. def __init__(self, session_id, system_prompt=None):
  7. self.session_id = session_id
  8. self.messages = []
  9. if system_prompt is None:
  10. self.system_prompt = conf().get("character_desc", "")
  11. else:
  12. self.system_prompt = system_prompt
  13. # 重置会话
  14. def reset(self):
  15. system_item = {"role": "system", "content": self.system_prompt}
  16. self.messages = [system_item]
  17. def set_system_prompt(self, system_prompt):
  18. self.system_prompt = system_prompt
  19. self.reset()
  20. # def add_query(self, query):
  21. # user_item = {"role": "user", "content": query}
  22. # self.messages.append(user_item)
  23. def add_query(self, query):
  24. try:
  25. # 判断是否为 JSON 字符串,如果是则转换为 Python 字典
  26. json_data = json.loads(query)
  27. if isinstance(json_data, dict) or isinstance(json_data, list): # 检查是否为字典格式
  28. user_item = {"role": "user", "content": json_data}
  29. else:
  30. user_item = {"role": "user", "content": query}
  31. except json.JSONDecodeError:
  32. # 如果不是 JSON 字符串,直接保存为字符串
  33. user_item = {"role": "user", "content": query}
  34. self.messages.append(user_item)
  35. def add_reply(self, reply):
  36. assistant_item = {"role": "assistant", "content": reply}
  37. self.messages.append(assistant_item)
  38. def discard_exceeding(self, max_tokens=None, cur_tokens=None):
  39. raise NotImplementedError
  40. def calc_tokens(self):
  41. raise NotImplementedError
  42. class SessionManager(object):
  43. def __init__(self, sessioncls, **session_args):
  44. if conf().get("expires_in_seconds"):
  45. sessions = ExpiredDict(conf().get("expires_in_seconds"))
  46. else:
  47. sessions = dict()
  48. self.sessions = sessions
  49. self.sessioncls = sessioncls
  50. self.session_args = session_args
  51. def build_session(self, session_id, system_prompt=None):
  52. """
  53. 如果session_id不在sessions中,创建一个新的session并添加到sessions中
  54. 如果system_prompt不会空,会更新session的system_prompt并重置session
  55. """
  56. if session_id is None:
  57. return self.sessioncls(session_id, system_prompt, **self.session_args)
  58. if session_id not in self.sessions:
  59. self.sessions[session_id] = self.sessioncls(session_id, system_prompt, **self.session_args)
  60. elif system_prompt is not None: # 如果有新的system_prompt,更新并重置session
  61. self.sessions[session_id].set_system_prompt(system_prompt)
  62. session = self.sessions[session_id]
  63. return session
  64. def session_query(self, query, session_id):
  65. session = self.build_session(session_id)
  66. session.add_query(query)
  67. try:
  68. max_tokens = conf().get("conversation_max_tokens", 1000)
  69. total_tokens = session.discard_exceeding(max_tokens, None)
  70. logger.debug("prompt tokens used={}".format(total_tokens))
  71. except Exception as e:
  72. logger.warning("Exception when counting tokens precisely for prompt: {}".format(str(e)))
  73. return session
  74. def session_reply(self, reply, session_id, total_tokens=None):
  75. session = self.build_session(session_id)
  76. session.add_reply(reply)
  77. try:
  78. max_tokens = conf().get("conversation_max_tokens", 1000)
  79. tokens_cnt = session.discard_exceeding(max_tokens, total_tokens)
  80. logger.debug("raw total_tokens={}, savesession tokens={}".format(total_tokens, tokens_cnt))
  81. except Exception as e:
  82. logger.warning("Exception when counting tokens precisely for session: {}".format(str(e)))
  83. return session
  84. def clear_session(self, session_id):
  85. if session_id in self.sessions:
  86. del self.sessions[session_id]
  87. def clear_all_session(self):
  88. self.sessions.clear()