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.1KB

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