Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

148 lines
6.7KB

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