Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

187 lines
8.7KB

  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": 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. self.args['model'] = context.get('gpt_model') or "gpt-3.5-turbo"
  61. # if context.get('stream'):
  62. # # reply in stream
  63. # return self.reply_text_stream(query, new_query, session_id)
  64. reply_content = self.reply_text(session, api_key)
  65. logger.debug(
  66. "[CHATGPT] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(
  67. session.messages,
  68. session_id,
  69. reply_content["content"],
  70. reply_content["completion_tokens"],
  71. )
  72. )
  73. if reply_content["completion_tokens"] == 0 and len(reply_content["content"]) > 0:
  74. reply = Reply(ReplyType.ERROR, reply_content["content"])
  75. elif reply_content["completion_tokens"] > 0:
  76. self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"])
  77. reply = Reply(ReplyType.TEXT, reply_content["content"])
  78. else:
  79. reply = Reply(ReplyType.ERROR, reply_content["content"])
  80. logger.debug("[CHATGPT] reply {} used 0 tokens.".format(reply_content))
  81. return reply
  82. elif context.type == ContextType.IMAGE_CREATE:
  83. ok, retstring = self.create_img(query, 0)
  84. reply = None
  85. if ok:
  86. reply = Reply(ReplyType.IMAGE_URL, retstring)
  87. else:
  88. reply = Reply(ReplyType.ERROR, retstring)
  89. return reply
  90. else:
  91. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  92. return reply
  93. def reply_text(self, session: ChatGPTSession, api_key=None, retry_count=0) -> dict:
  94. """
  95. call openai's ChatCompletion to get the answer
  96. :param session: a conversation session
  97. :param session_id: session id
  98. :param retry_count: retry count
  99. :return: {}
  100. """
  101. try:
  102. if conf().get("rate_limit_chatgpt") and not self.tb4chatgpt.get_token():
  103. raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
  104. # if api_key == None, the default openai.api_key will be used
  105. response = openai.ChatCompletion.create(api_key=api_key, messages=session.messages, **self.args)
  106. # logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  107. return {
  108. "total_tokens": response["usage"]["total_tokens"],
  109. "completion_tokens": response["usage"]["completion_tokens"],
  110. "content": response.choices[0]["message"]["content"],
  111. }
  112. except Exception as e:
  113. need_retry = retry_count < 2
  114. result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
  115. if isinstance(e, openai.error.RateLimitError):
  116. logger.warn("[CHATGPT] RateLimitError: {}".format(e))
  117. result["content"] = "提问太快啦,请休息一下再问我吧"
  118. if need_retry:
  119. time.sleep(20)
  120. elif isinstance(e, openai.error.Timeout):
  121. logger.warn("[CHATGPT] Timeout: {}".format(e))
  122. result["content"] = "我没有收到你的消息"
  123. if need_retry:
  124. time.sleep(5)
  125. elif isinstance(e, openai.error.APIError):
  126. logger.warn("[CHATGPT] Bad Gateway: {}".format(e))
  127. result["content"] = "请再问我一次"
  128. if need_retry:
  129. time.sleep(10)
  130. elif isinstance(e, openai.error.APIConnectionError):
  131. logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
  132. need_retry = False
  133. result["content"] = "我连接不到你的网络"
  134. else:
  135. logger.exception("[CHATGPT] Exception: {}".format(e))
  136. need_retry = False
  137. self.sessions.clear_session(session.session_id)
  138. if need_retry:
  139. logger.warn("[CHATGPT] 第{}次重试".format(retry_count + 1))
  140. return self.reply_text(session, api_key, retry_count + 1)
  141. else:
  142. return result
  143. class AzureChatGPTBot(ChatGPTBot):
  144. def __init__(self):
  145. super().__init__()
  146. openai.api_type = "azure"
  147. openai.api_version = "2023-03-15-preview"
  148. self.args["deployment_id"] = conf().get("azure_deployment_id")
  149. def create_img(self, query, retry_count=0, api_key=None):
  150. api_version = "2022-08-03-preview"
  151. url = "{}dalle/text-to-image?api-version={}".format(openai.api_base, api_version)
  152. api_key = api_key or openai.api_key
  153. headers = {"api-key": api_key, "Content-Type": "application/json"}
  154. try:
  155. body = {"caption": query, "resolution": conf().get("image_create_size", "256x256")}
  156. submission = requests.post(url, headers=headers, json=body)
  157. operation_location = submission.headers["Operation-Location"]
  158. retry_after = submission.headers["Retry-after"]
  159. status = ""
  160. image_url = ""
  161. while status != "Succeeded":
  162. logger.info("waiting for image create..., " + status + ",retry after " + retry_after + " seconds")
  163. time.sleep(int(retry_after))
  164. response = requests.get(operation_location, headers=headers)
  165. status = response.json()["status"]
  166. image_url = response.json()["result"]["contentUrl"]
  167. return True, image_url
  168. except Exception as e:
  169. logger.error("create image error: {}".format(e))
  170. return False, "图片生成失败"