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ů.

chat_gpt_bot.py 7.2KB

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