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.

241 line
12KB

  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. result["content"] = "我连接不到你的网络"
  140. if need_retry:
  141. time.sleep(5)
  142. else:
  143. logger.exception("[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, args, 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 = conf().get("azure_api_version", "2023-06-01-preview")
  156. self.args["deployment_id"] = conf().get("azure_deployment_id")
  157. def create_img(self, query, retry_count=0, api_key=None):
  158. text_to_image_model = conf().get("text_to_image")
  159. if text_to_image_model == "dall-e-2":
  160. api_version = "2023-06-01-preview"
  161. endpoint = conf().get("azure_openai_dalle_api_base","open_ai_api_base")
  162. # 检查endpoint是否以/结尾
  163. if not endpoint.endswith("/"):
  164. endpoint = endpoint + "/"
  165. url = "{}openai/images/generations:submit?api-version={}".format(endpoint, api_version)
  166. api_key = conf().get("azure_openai_dalle_api_key","open_ai_api_key")
  167. headers = {"api-key": api_key, "Content-Type": "application/json"}
  168. try:
  169. body = {"prompt": query, "size": conf().get("image_create_size", "256x256"),"n": 1}
  170. submission = requests.post(url, headers=headers, json=body)
  171. operation_location = submission.headers['operation-location']
  172. status = ""
  173. while (status != "succeeded"):
  174. if retry_count > 3:
  175. return False, "图片生成失败"
  176. response = requests.get(operation_location, headers=headers)
  177. status = response.json()['status']
  178. retry_count += 1
  179. image_url = response.json()['result']['data'][0]['url']
  180. return True, image_url
  181. except Exception as e:
  182. logger.error("create image error: {}".format(e))
  183. return False, "图片生成失败"
  184. elif text_to_image_model == "dall-e-3":
  185. api_version = conf().get("azure_api_version", "2024-02-15-preview")
  186. endpoint = conf().get("azure_openai_dalle_api_base","open_ai_api_base")
  187. # 检查endpoint是否以/结尾
  188. if not endpoint.endswith("/"):
  189. endpoint = endpoint + "/"
  190. url = "{}openai/deployments/{}/images/generations?api-version={}".format(endpoint, conf().get("azure_openai_dalle_deployment_id","text_to_image"),api_version)
  191. api_key = conf().get("azure_openai_dalle_api_key","open_ai_api_key")
  192. headers = {"api-key": api_key, "Content-Type": "application/json"}
  193. try:
  194. body = {"prompt": query, "size": conf().get("image_create_size", "1024x1024"), "quality": conf().get("dalle3_image_quality", "standard")}
  195. response = requests.post(url, headers=headers, json=body)
  196. response.raise_for_status() # 检查请求是否成功
  197. data = response.json()
  198. # 检查响应中是否包含图像 URL
  199. if 'data' in data and len(data['data']) > 0 and 'url' in data['data'][0]:
  200. image_url = data['data'][0]['url']
  201. return True, image_url
  202. else:
  203. error_message = "响应中没有图像 URL"
  204. logger.error(error_message)
  205. return False, "图片生成失败"
  206. except requests.exceptions.RequestException as e:
  207. # 捕获所有请求相关的异常
  208. try:
  209. error_detail = response.json().get('error', {}).get('message', str(e))
  210. except ValueError:
  211. error_detail = str(e)
  212. error_message = f"{error_detail}"
  213. logger.error(error_message)
  214. return False, error_message
  215. except Exception as e:
  216. # 捕获所有其他异常
  217. error_message = f"生成图像时发生错误: {e}"
  218. logger.error(error_message)
  219. return False, "图片生成失败"
  220. else:
  221. return False, "图片生成失败,未配置text_to_image参数"