您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

baidu_wenxin.py 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # encoding:utf-8
  2. import requests, json
  3. from bot.bot import Bot
  4. from bridge.reply import Reply, ReplyType
  5. from bot.session_manager import SessionManager
  6. from bridge.context import ContextType
  7. from bridge.reply import Reply, ReplyType
  8. from common.log import logger
  9. from config import conf
  10. from bot.baidu.baidu_wenxin_session import BaiduWenxinSession
  11. BAIDU_API_KEY = conf().get("baidu_wenxin_api_key")
  12. BAIDU_SECRET_KEY = conf().get("baidu_wenxin_secret_key")
  13. class BaiduWenxinBot(Bot):
  14. def __init__(self):
  15. super().__init__()
  16. self.sessions = SessionManager(BaiduWenxinSession, model=conf().get("baidu_wenxin_model") or "eb-instant")
  17. def reply(self, query, context=None):
  18. # acquire reply content
  19. if context and context.type:
  20. if context.type == ContextType.TEXT:
  21. logger.info("[BAIDU] query={}".format(query))
  22. session_id = context["session_id"]
  23. reply = None
  24. if query == "#清除记忆":
  25. self.sessions.clear_session(session_id)
  26. reply = Reply(ReplyType.INFO, "记忆已清除")
  27. elif query == "#清除所有":
  28. self.sessions.clear_all_session()
  29. reply = Reply(ReplyType.INFO, "所有人记忆已清除")
  30. else:
  31. session = self.sessions.session_query(query, session_id)
  32. result = self.reply_text(session)
  33. total_tokens, completion_tokens, reply_content = (
  34. result["total_tokens"],
  35. result["completion_tokens"],
  36. result["content"],
  37. )
  38. logger.debug(
  39. "[BAIDU] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content, completion_tokens)
  40. )
  41. if total_tokens == 0:
  42. reply = Reply(ReplyType.ERROR, reply_content)
  43. else:
  44. self.sessions.session_reply(reply_content, session_id, total_tokens)
  45. reply = Reply(ReplyType.TEXT, reply_content)
  46. return reply
  47. elif context.type == ContextType.IMAGE_CREATE:
  48. ok, retstring = self.create_img(query, 0)
  49. reply = None
  50. if ok:
  51. reply = Reply(ReplyType.IMAGE_URL, retstring)
  52. else:
  53. reply = Reply(ReplyType.ERROR, retstring)
  54. return reply
  55. def reply_text(self, session: BaiduWenxinSession, retry_count=0):
  56. try:
  57. logger.info("[BAIDU] model={}".format(session.model))
  58. access_token = self.get_access_token()
  59. if access_token == 'None':
  60. logger.warn("[BAIDU] access token 获取失败")
  61. return {
  62. "total_tokens": 0,
  63. "completion_tokens": 0,
  64. "content": 0,
  65. }
  66. url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/" + session.model + "?access_token=" + access_token
  67. headers = {
  68. 'Content-Type': 'application/json'
  69. }
  70. payload = {'messages': session.messages}
  71. response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
  72. response_text = json.loads(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"))