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.

121 lines
5.4KB

  1. # encoding:utf-8
  2. import requests
  3. import json
  4. from common import const
  5. from bot.bot import Bot
  6. from bot.session_manager import SessionManager
  7. from bridge.context import ContextType
  8. from bridge.reply import Reply, ReplyType
  9. from common.log import logger
  10. from config import conf
  11. from bot.baidu.baidu_wenxin_session import BaiduWenxinSession
  12. BAIDU_API_KEY = conf().get("baidu_wenxin_api_key")
  13. BAIDU_SECRET_KEY = conf().get("baidu_wenxin_secret_key")
  14. class BaiduWenxinBot(Bot):
  15. def __init__(self):
  16. super().__init__()
  17. wenxin_model = conf().get("baidu_wenxin_model")
  18. self.prompt_enabled = conf().get("baidu_wenxin_prompt_enabled")
  19. if self.prompt_enabled:
  20. self.prompt = conf().get("character_desc", "")
  21. if self.prompt == "":
  22. logger.warn("[BAIDU] Although you enabled model prompt, character_desc is not specified.")
  23. if wenxin_model is not None:
  24. wenxin_model = conf().get("baidu_wenxin_model") or "eb-instant"
  25. else:
  26. if conf().get("model") and conf().get("model") == const.WEN_XIN:
  27. wenxin_model = "completions"
  28. elif conf().get("model") and conf().get("model") == const.WEN_XIN_4:
  29. wenxin_model = "completions_pro"
  30. self.sessions = SessionManager(BaiduWenxinSession, model=wenxin_model)
  31. def reply(self, query, context=None):
  32. # acquire reply content
  33. if context and context.type:
  34. if context.type == ContextType.TEXT:
  35. logger.info("[BAIDU] query={}".format(query))
  36. session_id = context["session_id"]
  37. reply = None
  38. if query == "#清除记忆":
  39. self.sessions.clear_session(session_id)
  40. reply = Reply(ReplyType.INFO, "记忆已清除")
  41. elif query == "#清除所有":
  42. self.sessions.clear_all_session()
  43. reply = Reply(ReplyType.INFO, "所有人记忆已清除")
  44. else:
  45. session = self.sessions.session_query(query, session_id)
  46. result = self.reply_text(session)
  47. total_tokens, completion_tokens, reply_content = (
  48. result["total_tokens"],
  49. result["completion_tokens"],
  50. result["content"],
  51. )
  52. logger.debug(
  53. "[BAIDU] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content, completion_tokens)
  54. )
  55. if total_tokens == 0:
  56. reply = Reply(ReplyType.ERROR, reply_content)
  57. else:
  58. self.sessions.session_reply(reply_content, session_id, total_tokens)
  59. reply = Reply(ReplyType.TEXT, reply_content)
  60. return reply
  61. elif context.type == ContextType.IMAGE_CREATE:
  62. ok, retstring = self.create_img(query, 0)
  63. reply = None
  64. if ok:
  65. reply = Reply(ReplyType.IMAGE_URL, retstring)
  66. else:
  67. reply = Reply(ReplyType.ERROR, retstring)
  68. return reply
  69. def reply_text(self, session: BaiduWenxinSession, retry_count=0):
  70. try:
  71. logger.info("[BAIDU] model={}".format(session.model))
  72. access_token = self.get_access_token()
  73. if access_token == 'None':
  74. logger.warn("[BAIDU] access token 获取失败")
  75. return {
  76. "total_tokens": 0,
  77. "completion_tokens": 0,
  78. "content": 0,
  79. }
  80. url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/" + session.model + "?access_token=" + access_token
  81. headers = {
  82. 'Content-Type': 'application/json'
  83. }
  84. payload = {'messages': session.messages, 'system': self.prompt} if self.prompt_enabled else {'messages': session.messages}
  85. response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
  86. response_text = json.loads(response.text)
  87. logger.info(f"[BAIDU] response text={response_text}")
  88. res_content = response_text["result"]
  89. total_tokens = response_text["usage"]["total_tokens"]
  90. completion_tokens = response_text["usage"]["completion_tokens"]
  91. logger.info("[BAIDU] reply={}".format(res_content))
  92. return {
  93. "total_tokens": total_tokens,
  94. "completion_tokens": completion_tokens,
  95. "content": res_content,
  96. }
  97. except Exception as e:
  98. need_retry = retry_count < 2
  99. logger.warn("[BAIDU] Exception: {}".format(e))
  100. need_retry = False
  101. self.sessions.clear_session(session.session_id)
  102. result = {"total_tokens": 0, "completion_tokens": 0, "content": "出错了: {}".format(e)}
  103. return result
  104. def get_access_token(self):
  105. """
  106. 使用 AK,SK 生成鉴权签名(Access Token)
  107. :return: access_token,或是None(如果错误)
  108. """
  109. url = "https://aip.baidubce.com/oauth/2.0/token"
  110. params = {"grant_type": "client_credentials", "client_id": BAIDU_API_KEY, "client_secret": BAIDU_SECRET_KEY}
  111. return str(requests.post(url, params=params).json().get("access_token"))