Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

108 lines
4.8KB

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