Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

144 lignes
6.6KB

  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("[OPEN_AI] 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("[OPEN_AI] 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("[OPEN_AI] 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("[OPEN_AI] 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. return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
  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 openai.error.RateLimitError as e:
  101. # rate limit exception
  102. logger.warn(e)
  103. if retry_count < 1:
  104. time.sleep(5)
  105. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  106. return self.reply_text(session, session_id, retry_count+1)
  107. else:
  108. return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
  109. except openai.error.APIConnectionError as e:
  110. # api connection exception
  111. logger.warn(e)
  112. logger.warn("[OPEN_AI] APIConnection failed")
  113. return {"completion_tokens": 0, "content": "我连接不到你的网络"}
  114. except openai.error.Timeout as e:
  115. logger.warn(e)
  116. logger.warn("[OPEN_AI] Timeout")
  117. return {"completion_tokens": 0, "content": "我没有收到你的消息"}
  118. except Exception as e:
  119. # unknown exception
  120. logger.exception(e)
  121. self.sessions.clear_session(session_id)
  122. return {"completion_tokens": 0, "content": "请再问我一次吧"}
  123. class AzureChatGPTBot(ChatGPTBot):
  124. def __init__(self):
  125. super().__init__()
  126. openai.api_type = "azure"
  127. openai.api_version = "2023-03-15-preview"
  128. def compose_args(self):
  129. args = super().compose_args()
  130. args["engine"] = args["model"]
  131. del(args["model"])
  132. return args