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.

158 lines
7.1KB

  1. # encoding:utf-8
  2. import time
  3. import openai
  4. import openai.error
  5. from bot.bot import Bot
  6. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  7. from bot.openai.open_ai_image import OpenAIImage
  8. from bot.session_manager import SessionManager
  9. from bridge.context import ContextType
  10. from bridge.reply import Reply, ReplyType
  11. from common.log import logger
  12. from common.token_bucket import TokenBucket
  13. from config import conf, load_config
  14. # OpenAI对话模型API (可用)
  15. class ChatGPTBot(Bot, OpenAIImage):
  16. def __init__(self):
  17. super().__init__()
  18. # set the default api_key
  19. openai.api_key = conf().get("open_ai_api_key")
  20. if conf().get("open_ai_api_base"):
  21. openai.api_base = conf().get("open_ai_api_base")
  22. proxy = conf().get("proxy")
  23. if proxy:
  24. openai.proxy = proxy
  25. if conf().get("rate_limit_chatgpt"):
  26. self.tb4chatgpt = TokenBucket(conf().get("rate_limit_chatgpt", 20))
  27. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  28. self.args = {
  29. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称
  30. "temperature": conf().get("temperature", 0.9), # 值在[0,1]之间,越大表示回复越具有不确定性
  31. # "max_tokens":4096, # 回复最大的字符数
  32. "top_p": 1,
  33. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  34. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  35. "request_timeout": conf().get("request_timeout", None), # 请求超时时间,openai接口默认设置为600,对于难问题一般需要较长时间
  36. "timeout": conf().get("request_timeout", None), # 重试超时时间,在这个时间内,将会自动重试
  37. }
  38. def reply(self, query, context=None):
  39. # acquire reply content
  40. if context.type == ContextType.TEXT:
  41. logger.info("[CHATGPT] query={}".format(query))
  42. session_id = context["session_id"]
  43. reply = None
  44. clear_memory_commands = conf().get("clear_memory_commands", ["#清除记忆"])
  45. if query in clear_memory_commands:
  46. self.sessions.clear_session(session_id)
  47. reply = Reply(ReplyType.INFO, "记忆已清除")
  48. elif query == "#清除所有":
  49. self.sessions.clear_all_session()
  50. reply = Reply(ReplyType.INFO, "所有人记忆已清除")
  51. elif query == "#更新配置":
  52. load_config()
  53. reply = Reply(ReplyType.INFO, "配置已更新")
  54. if reply:
  55. return reply
  56. session = self.sessions.session_query(query, session_id)
  57. logger.debug("[CHATGPT] session query={}".format(session.messages))
  58. api_key = context.get("openai_api_key")
  59. # if context.get('stream'):
  60. # # reply in stream
  61. # return self.reply_text_stream(query, new_query, session_id)
  62. reply_content = self.reply_text(session, api_key)
  63. logger.debug(
  64. "[CHATGPT] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(
  65. session.messages,
  66. session_id,
  67. reply_content["content"],
  68. reply_content["completion_tokens"],
  69. )
  70. )
  71. if reply_content["completion_tokens"] == 0 and len(reply_content["content"]) > 0:
  72. reply = Reply(ReplyType.ERROR, reply_content["content"])
  73. elif reply_content["completion_tokens"] > 0:
  74. self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"])
  75. reply = Reply(ReplyType.TEXT, reply_content["content"])
  76. else:
  77. reply = Reply(ReplyType.ERROR, reply_content["content"])
  78. logger.debug("[CHATGPT] reply {} used 0 tokens.".format(reply_content))
  79. return reply
  80. elif context.type == ContextType.IMAGE_CREATE:
  81. ok, retstring = self.create_img(query, 0)
  82. reply = None
  83. if ok:
  84. reply = Reply(ReplyType.IMAGE_URL, retstring)
  85. else:
  86. reply = Reply(ReplyType.ERROR, retstring)
  87. return reply
  88. else:
  89. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  90. return reply
  91. def reply_text(self, session: ChatGPTSession, api_key=None, retry_count=0) -> dict:
  92. """
  93. call openai's ChatCompletion to get the answer
  94. :param session: a conversation session
  95. :param session_id: session id
  96. :param retry_count: retry count
  97. :return: {}
  98. """
  99. try:
  100. if conf().get("rate_limit_chatgpt") and not self.tb4chatgpt.get_token():
  101. raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
  102. # if api_key == None, the default openai.api_key will be used
  103. response = openai.ChatCompletion.create(api_key=api_key, messages=session.messages, **self.args)
  104. # logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  105. return {
  106. "total_tokens": response["usage"]["total_tokens"],
  107. "completion_tokens": response["usage"]["completion_tokens"],
  108. "content": response.choices[0]["message"]["content"],
  109. }
  110. except Exception as e:
  111. need_retry = retry_count < 2
  112. result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
  113. if isinstance(e, openai.error.RateLimitError):
  114. logger.warn("[CHATGPT] RateLimitError: {}".format(e))
  115. result["content"] = "提问太快啦,请休息一下再问我吧"
  116. if need_retry:
  117. time.sleep(20)
  118. elif isinstance(e, openai.error.Timeout):
  119. logger.warn("[CHATGPT] Timeout: {}".format(e))
  120. result["content"] = "我没有收到你的消息"
  121. if need_retry:
  122. time.sleep(5)
  123. elif isinstance(e, openai.error.APIConnectionError):
  124. logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
  125. need_retry = False
  126. result["content"] = "我连接不到你的网络"
  127. else:
  128. logger.warn("[CHATGPT] Exception: {}".format(e))
  129. need_retry = False
  130. self.sessions.clear_session(session.session_id)
  131. if need_retry:
  132. logger.warn("[CHATGPT] 第{}次重试".format(retry_count + 1))
  133. return self.reply_text(session, api_key, retry_count + 1)
  134. else:
  135. return result
  136. class AzureChatGPTBot(ChatGPTBot):
  137. def __init__(self):
  138. super().__init__()
  139. openai.api_type = "azure"
  140. openai.api_version = "2023-03-15-preview"
  141. self.args["deployment_id"] = conf().get("azure_deployment_id")