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.

chat_gpt_bot.py 7.2KB

1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # encoding:utf-8
  2. from bot.bot import Bot
  3. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  4. from bot.openai.open_ai_image import OpenAIImage
  5. from bot.session_manager import Session, SessionManager
  6. from bridge.context import ContextType
  7. from bridge.reply import Reply, ReplyType
  8. from config import conf, load_config
  9. from common.log import logger
  10. from common.token_bucket import TokenBucket
  11. from common.expired_dict import ExpiredDict
  12. import openai
  13. import openai.error
  14. import time
  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. def reply(self, query, context=None):
  30. # acquire reply content
  31. if context.type == ContextType.TEXT:
  32. logger.info("[CHATGPT] query={}".format(query))
  33. session_id = context['session_id']
  34. reply = None
  35. clear_memory_commands = conf().get('clear_memory_commands', ['#清除记忆'])
  36. if query in clear_memory_commands:
  37. self.sessions.clear_session(session_id)
  38. reply = Reply(ReplyType.INFO, '记忆已清除')
  39. elif query == '#清除所有':
  40. self.sessions.clear_all_session()
  41. reply = Reply(ReplyType.INFO, '所有人记忆已清除')
  42. elif query == '#更新配置':
  43. load_config()
  44. reply = Reply(ReplyType.INFO, '配置已更新')
  45. if reply:
  46. return reply
  47. session = self.sessions.session_query(query, session_id)
  48. logger.debug("[CHATGPT] session query={}".format(session.messages))
  49. api_key = context.get('openai_api_key')
  50. # if context.get('stream'):
  51. # # reply in stream
  52. # return self.reply_text_stream(query, new_query, session_id)
  53. reply_content = self.reply_text(session, session_id, api_key, 0)
  54. logger.debug("[CHATGPT] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content["content"], reply_content["completion_tokens"]))
  55. if reply_content['completion_tokens'] == 0 and len(reply_content['content']) > 0:
  56. reply = Reply(ReplyType.ERROR, reply_content['content'])
  57. elif reply_content["completion_tokens"] > 0:
  58. self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"])
  59. reply = Reply(ReplyType.TEXT, reply_content["content"])
  60. else:
  61. reply = Reply(ReplyType.ERROR, reply_content['content'])
  62. logger.debug("[CHATGPT] reply {} used 0 tokens.".format(reply_content))
  63. return reply
  64. elif context.type == ContextType.IMAGE_CREATE:
  65. ok, retstring = self.create_img(query, 0)
  66. reply = None
  67. if ok:
  68. reply = Reply(ReplyType.IMAGE_URL, retstring)
  69. else:
  70. reply = Reply(ReplyType.ERROR, retstring)
  71. return reply
  72. else:
  73. reply = Reply(ReplyType.ERROR, 'Bot不支持处理{}类型的消息'.format(context.type))
  74. return reply
  75. def compose_args(self):
  76. return {
  77. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称
  78. "temperature":conf().get('temperature', 0.9), # 值在[0,1]之间,越大表示回复越具有不确定性
  79. # "max_tokens":4096, # 回复最大的字符数
  80. "top_p":1,
  81. "frequency_penalty":conf().get('frequency_penalty', 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  82. "presence_penalty":conf().get('presence_penalty', 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  83. "request_timeout": conf().get('request_timeout', 120), # 请求超时时间,openai接口默认设置为600,对于难问题一般需要较长时间
  84. "timeout": conf().get('request_timeout', 120), #重试超时时间,在这个时间内,将会自动重试
  85. }
  86. def reply_text(self, session:ChatGPTSession, session_id, api_key, retry_count=0) -> dict:
  87. '''
  88. call openai's ChatCompletion to get the answer
  89. :param session: a conversation session
  90. :param session_id: session id
  91. :param retry_count: retry count
  92. :return: {}
  93. '''
  94. try:
  95. if conf().get('rate_limit_chatgpt') and not self.tb4chatgpt.get_token():
  96. raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
  97. # if api_key == None, the default openai.api_key will be used
  98. response = openai.ChatCompletion.create(
  99. api_key=api_key, messages=session.messages, **self.compose_args()
  100. )
  101. # logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  102. return {"total_tokens": response["usage"]["total_tokens"],
  103. "completion_tokens": response["usage"]["completion_tokens"],
  104. "content": response.choices[0]['message']['content']}
  105. except Exception as e:
  106. need_retry = retry_count < 2
  107. result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
  108. if isinstance(e, openai.error.RateLimitError):
  109. logger.warn("[CHATGPT] RateLimitError: {}".format(e))
  110. result['content'] = "提问太快啦,请休息一下再问我吧"
  111. if need_retry:
  112. time.sleep(5)
  113. elif isinstance(e, openai.error.Timeout):
  114. logger.warn("[CHATGPT] Timeout: {}".format(e))
  115. result['content'] = "服务器出现问题"
  116. if need_retry:
  117. time.sleep(5)
  118. elif isinstance(e, openai.error.APIConnectionError):
  119. logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
  120. need_retry = False
  121. result['content'] = "网络连接出现问题"
  122. else:
  123. logger.warn("[CHATGPT] Exception: {}".format(e))
  124. need_retry = False
  125. self.sessions.clear_session(session_id)
  126. result['content'] = str(e)
  127. if need_retry:
  128. logger.warn("[CHATGPT] 第{}次重试".format(retry_count+1))
  129. return self.reply_text(session, session_id, api_key, retry_count+1)
  130. else:
  131. return result
  132. class AzureChatGPTBot(ChatGPTBot):
  133. def __init__(self):
  134. super().__init__()
  135. openai.api_type = "azure"
  136. openai.api_version = "2023-03-15-preview"
  137. def compose_args(self):
  138. args = super().compose_args()
  139. args["engine"] = args["model"]
  140. del(args["model"])
  141. return args