Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

zhipuai_bot.py 6.7KB

pirms 9 mēnešiem
pirms 9 mēnešiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # encoding:utf-8
  2. import time
  3. import openai
  4. import openai.error
  5. from bot.bot import Bot
  6. from bot.zhipuai.zhipu_ai_session import ZhipuAISession
  7. from bot.zhipuai.zhipu_ai_image import ZhipuAIImage
  8. from bot.session_manager import SessionManager
  9. from bridge.context import ContextType
  10. from bridge.reply import Reply, ReplyType
  11. from common.log import logger
  12. from config import conf, load_config
  13. from zhipuai import ZhipuAI
  14. # ZhipuAI对话模型API
  15. class ZHIPUAIBot(Bot, ZhipuAIImage):
  16. def __init__(self):
  17. super().__init__()
  18. self.sessions = SessionManager(ZhipuAISession, model=conf().get("model") or "ZHIPU_AI")
  19. self.args = {
  20. "model": conf().get("model") or "glm-4", # 对话模型的名称
  21. "temperature": conf().get("temperature", 0.9), # 值在(0,1)之间(智谱AI 的温度不能取 0 或者 1)
  22. "top_p": conf().get("top_p", 0.7), # 值在(0,1)之间(智谱AI 的 top_p 不能取 0 或者 1)
  23. }
  24. self.client = ZhipuAI(api_key=conf().get("zhipu_ai_api_key"))
  25. def reply(self, query, context=None):
  26. # acquire reply content
  27. if context.type == ContextType.TEXT:
  28. logger.info("[ZHIPU_AI] query={}".format(query))
  29. session_id = context["session_id"]
  30. reply = None
  31. clear_memory_commands = conf().get("clear_memory_commands", ["#清除记忆"])
  32. if query in clear_memory_commands:
  33. self.sessions.clear_session(session_id)
  34. reply = Reply(ReplyType.INFO, "记忆已清除")
  35. elif query == "#清除所有":
  36. self.sessions.clear_all_session()
  37. reply = Reply(ReplyType.INFO, "所有人记忆已清除")
  38. elif query == "#更新配置":
  39. load_config()
  40. reply = Reply(ReplyType.INFO, "配置已更新")
  41. if reply:
  42. return reply
  43. session = self.sessions.session_query(query, session_id)
  44. logger.debug("[ZHIPU_AI] session query={}".format(session.messages))
  45. api_key = context.get("openai_api_key") or openai.api_key
  46. model = context.get("gpt_model")
  47. new_args = None
  48. if model:
  49. new_args = self.args.copy()
  50. new_args["model"] = model
  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, api_key, args=new_args)
  55. logger.debug(
  56. "[ZHIPU_AI] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(
  57. session.messages,
  58. session_id,
  59. reply_content["content"],
  60. reply_content["completion_tokens"],
  61. )
  62. )
  63. if reply_content["completion_tokens"] == 0 and len(reply_content["content"]) > 0:
  64. reply = Reply(ReplyType.ERROR, reply_content["content"])
  65. elif reply_content["completion_tokens"] > 0:
  66. self.sessions.session_reply(reply_content["content"], session_id, reply_content["total_tokens"])
  67. reply = Reply(ReplyType.TEXT, reply_content["content"])
  68. else:
  69. reply = Reply(ReplyType.ERROR, reply_content["content"])
  70. logger.debug("[ZHIPU_AI] reply {} used 0 tokens.".format(reply_content))
  71. return reply
  72. elif context.type == ContextType.IMAGE_CREATE:
  73. ok, retstring = self.create_img(query, 0)
  74. reply = None
  75. if ok:
  76. reply = Reply(ReplyType.IMAGE_URL, retstring)
  77. else:
  78. reply = Reply(ReplyType.ERROR, retstring)
  79. return reply
  80. else:
  81. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  82. return reply
  83. def reply_text(self, session: ZhipuAISession, api_key=None, args=None, retry_count=0) -> dict:
  84. """
  85. call openai's ChatCompletion to get the answer
  86. :param session: a conversation session
  87. :param session_id: session id
  88. :param retry_count: retry count
  89. :return: {}
  90. """
  91. try:
  92. # if conf().get("rate_limit_chatgpt") and not self.tb4chatgpt.get_token():
  93. # raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
  94. # if api_key == None, the default openai.api_key will be used
  95. if args is None:
  96. args = self.args
  97. # response = openai.ChatCompletion.create(api_key=api_key, messages=session.messages, **args)
  98. response = self.client.chat.completions.create(messages=session.messages, **args)
  99. # logger.debug("[ZHIPU_AI] response={}".format(response))
  100. # logger.info("[ZHIPU_AI] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  101. return {
  102. "total_tokens": response.usage.total_tokens,
  103. "completion_tokens": response.usage.completion_tokens,
  104. "content": response.choices[0].message.content,
  105. }
  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("[ZHIPU_AI] RateLimitError: {}".format(e))
  111. result["content"] = "提问太快啦,请休息一下再问我吧"
  112. if need_retry:
  113. time.sleep(20)
  114. elif isinstance(e, openai.error.Timeout):
  115. logger.warn("[ZHIPU_AI] Timeout: {}".format(e))
  116. result["content"] = "我没有收到你的消息"
  117. if need_retry:
  118. time.sleep(5)
  119. elif isinstance(e, openai.error.APIError):
  120. logger.warn("[ZHIPU_AI] Bad Gateway: {}".format(e))
  121. result["content"] = "请再问我一次"
  122. if need_retry:
  123. time.sleep(10)
  124. elif isinstance(e, openai.error.APIConnectionError):
  125. logger.warn("[ZHIPU_AI] APIConnectionError: {}".format(e))
  126. result["content"] = "我连接不到你的网络"
  127. if need_retry:
  128. time.sleep(5)
  129. else:
  130. logger.exception("[ZHIPU_AI] Exception: {}".format(e), e)
  131. need_retry = False
  132. self.sessions.clear_session(session.session_id)
  133. if need_retry:
  134. logger.warn("[ZHIPU_AI] 第{}次重试".format(retry_count + 1))
  135. return self.reply_text(session, api_key, args, retry_count + 1)
  136. else:
  137. return result