Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

148 lines
7.0KB

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