chat_gpt_bot.py 9.3 KB

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