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.

105 satır
4.6KB

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