No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

173 líneas
7.4KB

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