Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

251 lines
12KB

  1. # encoding:utf-8
  2. import time
  3. import openai
  4. import openai.error
  5. import requests
  6. import json
  7. from bot.bot import Bot
  8. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  9. from bot.openai.open_ai_image import OpenAIImage
  10. from bot.session_manager import SessionManager
  11. from bridge.context import ContextType
  12. from bridge.reply import Reply, ReplyType
  13. from common.log import logger
  14. from common.token_bucket import TokenBucket
  15. from config import conf, load_config
  16. from channel.chat_message import ChatMessage
  17. # OpenAI对话模型API (可用)
  18. class ChatGPTBot(Bot, OpenAIImage):
  19. def __init__(self):
  20. super().__init__()
  21. # set the default api_key
  22. openai.api_key = conf().get("open_ai_api_key")
  23. if conf().get("open_ai_api_base"):
  24. openai.api_base = conf().get("open_ai_api_base")
  25. proxy = conf().get("proxy")
  26. if proxy:
  27. openai.proxy = proxy
  28. if conf().get("rate_limit_chatgpt"):
  29. self.tb4chatgpt = TokenBucket(conf().get("rate_limit_chatgpt", 20))
  30. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  31. self.args = {
  32. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称
  33. "temperature": conf().get("temperature", 0.9), # 值在[0,1]之间,越大表示回复越具有不确定性
  34. # "max_tokens":4096, # 回复最大的字符数
  35. "top_p": conf().get("top_p", 1),
  36. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  37. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  38. "request_timeout": conf().get("request_timeout", None), # 请求超时时间,openai接口默认设置为600,对于难问题一般需要较长时间
  39. "timeout": conf().get("request_timeout", None), # 重试超时时间,在这个时间内,将会自动重试
  40. }
  41. def reply(self, query, context=None):
  42. # acquire reply content
  43. if context.type == ContextType.TEXT:
  44. # print(context.__dict__)
  45. msg: ChatMessage = context.kwargs['msg']
  46. # print(msg.from_user_nickname)
  47. logger.info("[CHATGPT] {} query={}".format(msg.from_user_nickname,query))
  48. session_id = context["session_id"]
  49. # print(f'会话id:{session_id}')
  50. reply = None
  51. clear_memory_commands = conf().get("clear_memory_commands", ["#清除记忆"])
  52. if query in clear_memory_commands:
  53. self.sessions.clear_session(session_id)
  54. reply = Reply(ReplyType.INFO, "记忆已清除")
  55. elif query == "#清除所有":
  56. self.sessions.clear_all_session()
  57. reply = Reply(ReplyType.INFO, "所有人记忆已清除")
  58. elif query == "#更新配置":
  59. load_config()
  60. reply = Reply(ReplyType.INFO, "配置已更新")
  61. if reply:
  62. return reply
  63. session = self.sessions.session_query(query, session_id)
  64. logger.debug("[CHATGPT] session query={}".format(session.messages))
  65. api_key = context.get("openai_api_key")
  66. model = context.get("gpt_model")
  67. new_args = None
  68. if model:
  69. new_args = self.args.copy()
  70. new_args["model"] = model
  71. # if context.get('stream'):
  72. # # reply in stream
  73. # return self.reply_text_stream(query, new_query, session_id)
  74. reply_content = self.reply_text(session, api_key, args=new_args)
  75. logger.debug(
  76. "[CHATGPT] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(
  77. session.messages,
  78. session_id,
  79. reply_content["content"],
  80. reply_content["completion_tokens"],
  81. )
  82. )
  83. if reply_content["completion_tokens"] == 0 and len(reply_content["content"]) > 0:
  84. reply = Reply(ReplyType.ERROR, reply_content["content"])
  85. elif reply_content["completion_tokens"] > 0:
  86. self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"])
  87. reply = Reply(ReplyType.TEXT, reply_content["content"])
  88. else:
  89. reply = Reply(ReplyType.ERROR, reply_content["content"])
  90. logger.debug("[CHATGPT] reply {} used 0 tokens.".format(reply_content))
  91. return reply
  92. elif context.type == ContextType.IMAGE_CREATE:
  93. ok, retstring = self.create_img(query, 0)
  94. reply = None
  95. if ok:
  96. reply = Reply(ReplyType.IMAGE_URL, retstring)
  97. else:
  98. reply = Reply(ReplyType.ERROR, retstring)
  99. return reply
  100. else:
  101. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  102. return reply
  103. def reply_text(self, session: ChatGPTSession, api_key=None, args=None, retry_count=0) -> dict:
  104. """
  105. call openai's ChatCompletion to get the answer
  106. :param session: a conversation session
  107. :param session_id: session id
  108. :param retry_count: retry count
  109. :return: {}
  110. """
  111. try:
  112. if conf().get("rate_limit_chatgpt") and not self.tb4chatgpt.get_token():
  113. raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
  114. # if api_key == None, the default openai.api_key will be used
  115. if args is None:
  116. args = self.args
  117. response = openai.ChatCompletion.create(api_key=api_key, messages=session.messages, **args)
  118. # print("{}".format(session.__dict__))
  119. logger.info("[CHATGPT] 请求={}".format(session.messages))
  120. # print(f'会话id:{session.session_id}')
  121. # logger.info("[CHATGPT] 响应={}".format(response))
  122. logger.info("[CHATGPT] 响应={}".format(json.dumps(response, separators=(',', ':'),ensure_ascii=False)))
  123. # logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  124. return {
  125. "total_tokens": response["usage"]["total_tokens"],
  126. "completion_tokens": response["usage"]["completion_tokens"],
  127. "content": response.choices[0]["message"]["content"],
  128. }
  129. except Exception as e:
  130. need_retry = retry_count < 2
  131. result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
  132. if isinstance(e, openai.error.RateLimitError):
  133. logger.warn("[CHATGPT] RateLimitError: {}".format(e))
  134. result["content"] = "提问太快啦,请休息一下再问我吧"
  135. if need_retry:
  136. time.sleep(20)
  137. elif isinstance(e, openai.error.Timeout):
  138. logger.warn("[CHATGPT] Timeout: {}".format(e))
  139. result["content"] = "我没有收到你的消息"
  140. if need_retry:
  141. time.sleep(5)
  142. elif isinstance(e, openai.error.APIError):
  143. logger.warn("[CHATGPT] Bad Gateway: {}".format(e))
  144. result["content"] = "请再问我一次"
  145. if need_retry:
  146. time.sleep(10)
  147. elif isinstance(e, openai.error.APIConnectionError):
  148. logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
  149. result["content"] = "我连接不到你的网络"
  150. if need_retry:
  151. time.sleep(5)
  152. else:
  153. logger.exception("[CHATGPT] Exception: {}".format(e))
  154. need_retry = False
  155. self.sessions.clear_session(session.session_id)
  156. if need_retry:
  157. logger.warn("[CHATGPT] 第{}次重试".format(retry_count + 1))
  158. return self.reply_text(session, api_key, args, retry_count + 1)
  159. else:
  160. return result
  161. class AzureChatGPTBot(ChatGPTBot):
  162. def __init__(self):
  163. super().__init__()
  164. openai.api_type = "azure"
  165. openai.api_version = conf().get("azure_api_version", "2023-06-01-preview")
  166. self.args["deployment_id"] = conf().get("azure_deployment_id")
  167. def create_img(self, query, retry_count=0, api_key=None):
  168. text_to_image_model = conf().get("text_to_image")
  169. if text_to_image_model == "dall-e-2":
  170. api_version = "2023-06-01-preview"
  171. endpoint = conf().get("azure_openai_dalle_api_base","open_ai_api_base")
  172. # 检查endpoint是否以/结尾
  173. if not endpoint.endswith("/"):
  174. endpoint = endpoint + "/"
  175. url = "{}openai/images/generations:submit?api-version={}".format(endpoint, api_version)
  176. api_key = conf().get("azure_openai_dalle_api_key","open_ai_api_key")
  177. headers = {"api-key": api_key, "Content-Type": "application/json"}
  178. try:
  179. body = {"prompt": query, "size": conf().get("image_create_size", "256x256"),"n": 1}
  180. submission = requests.post(url, headers=headers, json=body)
  181. operation_location = submission.headers['operation-location']
  182. status = ""
  183. while (status != "succeeded"):
  184. if retry_count > 3:
  185. return False, "图片生成失败"
  186. response = requests.get(operation_location, headers=headers)
  187. status = response.json()['status']
  188. retry_count += 1
  189. image_url = response.json()['result']['data'][0]['url']
  190. return True, image_url
  191. except Exception as e:
  192. logger.error("create image error: {}".format(e))
  193. return False, "图片生成失败"
  194. elif text_to_image_model == "dall-e-3":
  195. api_version = conf().get("azure_api_version", "2024-02-15-preview")
  196. endpoint = conf().get("azure_openai_dalle_api_base","open_ai_api_base")
  197. # 检查endpoint是否以/结尾
  198. if not endpoint.endswith("/"):
  199. endpoint = endpoint + "/"
  200. url = "{}openai/deployments/{}/images/generations?api-version={}".format(endpoint, conf().get("azure_openai_dalle_deployment_id","text_to_image"),api_version)
  201. api_key = conf().get("azure_openai_dalle_api_key","open_ai_api_key")
  202. headers = {"api-key": api_key, "Content-Type": "application/json"}
  203. try:
  204. body = {"prompt": query, "size": conf().get("image_create_size", "1024x1024"), "quality": conf().get("dalle3_image_quality", "standard")}
  205. response = requests.post(url, headers=headers, json=body)
  206. response.raise_for_status() # 检查请求是否成功
  207. data = response.json()
  208. # 检查响应中是否包含图像 URL
  209. if 'data' in data and len(data['data']) > 0 and 'url' in data['data'][0]:
  210. image_url = data['data'][0]['url']
  211. return True, image_url
  212. else:
  213. error_message = "响应中没有图像 URL"
  214. logger.error(error_message)
  215. return False, "图片生成失败"
  216. except requests.exceptions.RequestException as e:
  217. # 捕获所有请求相关的异常
  218. try:
  219. error_detail = response.json().get('error', {}).get('message', str(e))
  220. except ValueError:
  221. error_detail = str(e)
  222. error_message = f"{error_detail}"
  223. logger.error(error_message)
  224. return False, error_message
  225. except Exception as e:
  226. # 捕获所有其他异常
  227. error_message = f"生成图像时发生错误: {e}"
  228. logger.error(error_message)
  229. return False, "图片生成失败"
  230. else:
  231. return False, "图片生成失败,未配置text_to_image参数"