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.

194 line
9.0KB

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