Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

chat_gpt_bot.py 8.9KB

pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
pirms 1 gada
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. 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.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  113. return {
  114. "total_tokens": response["usage"]["total_tokens"],
  115. "completion_tokens": response["usage"]["completion_tokens"],
  116. "content": response.choices[0]["message"]["content"],
  117. }
  118. except Exception as e:
  119. need_retry = retry_count < 2
  120. result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
  121. if isinstance(e, openai.error.RateLimitError):
  122. logger.warn("[CHATGPT] RateLimitError: {}".format(e))
  123. result["content"] = "提问太快啦,请休息一下再问我吧"
  124. if need_retry:
  125. time.sleep(20)
  126. elif isinstance(e, openai.error.Timeout):
  127. logger.warn("[CHATGPT] Timeout: {}".format(e))
  128. result["content"] = "我没有收到你的消息"
  129. if need_retry:
  130. time.sleep(5)
  131. elif isinstance(e, openai.error.APIError):
  132. logger.warn("[CHATGPT] Bad Gateway: {}".format(e))
  133. result["content"] = "请再问我一次"
  134. if need_retry:
  135. time.sleep(10)
  136. elif isinstance(e, openai.error.APIConnectionError):
  137. logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
  138. need_retry = False
  139. result["content"] = "我连接不到你的网络"
  140. else:
  141. logger.exception("[CHATGPT] Exception: {}".format(e))
  142. need_retry = False
  143. self.sessions.clear_session(session.session_id)
  144. if need_retry:
  145. logger.warn("[CHATGPT] 第{}次重试".format(retry_count + 1))
  146. return self.reply_text(session, api_key, args, retry_count + 1)
  147. else:
  148. return result
  149. class AzureChatGPTBot(ChatGPTBot):
  150. def __init__(self):
  151. super().__init__()
  152. openai.api_type = "azure"
  153. openai.api_version = "2023-03-15-preview"
  154. self.args["deployment_id"] = conf().get("azure_deployment_id")
  155. def create_img(self, query, retry_count=0, api_key=None):
  156. api_version = "2022-08-03-preview"
  157. url = "{}dalle/text-to-image?api-version={}".format(openai.api_base, api_version)
  158. api_key = api_key or openai.api_key
  159. headers = {"api-key": api_key, "Content-Type": "application/json"}
  160. try:
  161. body = {"caption": query, "resolution": conf().get("image_create_size", "256x256")}
  162. submission = requests.post(url, headers=headers, json=body)
  163. operation_location = submission.headers["Operation-Location"]
  164. retry_after = submission.headers["Retry-after"]
  165. status = ""
  166. image_url = ""
  167. while status != "Succeeded":
  168. logger.info("waiting for image create..., " + status + ",retry after " + retry_after + " seconds")
  169. time.sleep(int(retry_after))
  170. response = requests.get(operation_location, headers=headers)
  171. status = response.json()["status"]
  172. image_url = response.json()["result"]["contentUrl"]
  173. return True, image_url
  174. except Exception as e:
  175. logger.error("create image error: {}".format(e))
  176. return False, "图片生成失败"