Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

182 linhas
8.4KB

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