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.

247 lines
8.1KB

  1. # encoding:utf-8
  2. import requests, json
  3. from bot.bot import Bot
  4. from bot.session_manager import SessionManager
  5. from bot.baidu.baidu_wenxin_session import BaiduWenxinSession
  6. from bridge.context import ContextType, Context
  7. from bridge.reply import Reply, ReplyType
  8. from common.log import logger
  9. from config import conf
  10. from common import const
  11. import time
  12. import _thread as thread
  13. import datetime
  14. from datetime import datetime
  15. from wsgiref.handlers import format_date_time
  16. from urllib.parse import urlencode
  17. import base64
  18. import ssl
  19. import hashlib
  20. import hmac
  21. import json
  22. from time import mktime
  23. from urllib.parse import urlparse
  24. import websocket
  25. import queue
  26. import threading
  27. import random
  28. # 消息队列 map
  29. queue_map = dict()
  30. class XunFeiBot(Bot):
  31. def __init__(self):
  32. super().__init__()
  33. self.app_id = conf().get("xunfei_app_id")
  34. self.api_key = conf().get("xunfei_api_key")
  35. self.api_secret = conf().get("xunfei_api_secret")
  36. # 默认使用v2.0版本,1.5版本可设置为 general
  37. self.domain = "generalv2"
  38. # 默认使用v2.0版本,1.5版本可设置为 "ws://spark-api.xf-yun.com/v1.1/chat"
  39. self.spark_url = "ws://spark-api.xf-yun.com/v2.1/chat"
  40. self.host = urlparse(self.spark_url).netloc
  41. self.path = urlparse(self.spark_url).path
  42. self.answer = ""
  43. # 和wenxin使用相同的session机制
  44. self.sessions = SessionManager(BaiduWenxinSession, model=const.XUNFEI)
  45. def reply(self, query, context: Context = None) -> Reply:
  46. if context.type == ContextType.TEXT:
  47. logger.info("[XunFei] query={}".format(query))
  48. session_id = context["session_id"]
  49. request_id = self.gen_request_id(session_id)
  50. session = self.sessions.session_query(query, session_id)
  51. threading.Thread(target=self.create_web_socket, args=(session.messages, request_id)).start()
  52. depth = 0
  53. time.sleep(0.1)
  54. t1 = time.time()
  55. usage = {}
  56. while depth <= 300:
  57. try:
  58. data_queue = queue_map.get(request_id)
  59. if not data_queue:
  60. depth += 1
  61. time.sleep(0.1)
  62. continue
  63. data_item = data_queue.get(block=True, timeout=0.1)
  64. if data_item.is_end:
  65. # 请求结束
  66. del queue_map[request_id]
  67. if data_item.reply:
  68. self.answer += data_item.reply
  69. usage = data_item.usage
  70. break
  71. self.answer += data_item.reply
  72. depth += 1
  73. except Exception as e:
  74. depth += 1
  75. continue
  76. t2 = time.time()
  77. logger.info(f"[XunFei-API] response={self.answer}, time={t2 - t1}s, usage={usage}")
  78. self.sessions.session_reply(self.answer, session_id, usage.get("total_tokens"))
  79. reply = Reply(ReplyType.TEXT, self.answer)
  80. return reply
  81. else:
  82. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  83. return reply
  84. def create_web_socket(self, prompt, session_id, temperature=0.5):
  85. logger.info(f"[XunFei] start connect, prompt={prompt}")
  86. websocket.enableTrace(False)
  87. wsUrl = self.create_url()
  88. ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close,
  89. on_open=on_open)
  90. data_queue = queue.Queue(1000)
  91. queue_map[session_id] = data_queue
  92. ws.appid = self.app_id
  93. ws.question = prompt
  94. ws.domain = self.domain
  95. ws.session_id = session_id
  96. ws.temperature = temperature
  97. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  98. def gen_request_id(self, session_id: str):
  99. return session_id + "_" + str(int(time.time())) + "" + str(random.randint(0, 100))
  100. # 生成url
  101. def create_url(self):
  102. # 生成RFC1123格式的时间戳
  103. now = datetime.now()
  104. date = format_date_time(mktime(now.timetuple()))
  105. # 拼接字符串
  106. signature_origin = "host: " + self.host + "\n"
  107. signature_origin += "date: " + date + "\n"
  108. signature_origin += "GET " + self.path + " HTTP/1.1"
  109. # 进行hmac-sha256进行加密
  110. signature_sha = hmac.new(self.api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
  111. digestmod=hashlib.sha256).digest()
  112. signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
  113. authorization_origin = f'api_key="{self.api_key}", algorithm="hmac-sha256", headers="host date request-line", ' \
  114. f'signature="{signature_sha_base64}"'
  115. authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
  116. # 将请求的鉴权参数组合为字典
  117. v = {
  118. "authorization": authorization,
  119. "date": date,
  120. "host": self.host
  121. }
  122. # 拼接鉴权参数,生成url
  123. url = self.spark_url + '?' + urlencode(v)
  124. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  125. return url
  126. def gen_params(self, appid, domain, question):
  127. """
  128. 通过appid和用户的提问来生成请参数
  129. """
  130. data = {
  131. "header": {
  132. "app_id": appid,
  133. "uid": "1234"
  134. },
  135. "parameter": {
  136. "chat": {
  137. "domain": domain,
  138. "random_threshold": 0.5,
  139. "max_tokens": 2048,
  140. "auditing": "default"
  141. }
  142. },
  143. "payload": {
  144. "message": {
  145. "text": question
  146. }
  147. }
  148. }
  149. return data
  150. class ReplyItem:
  151. def __init__(self, reply, usage=None, is_end=False):
  152. self.is_end = is_end
  153. self.reply = reply
  154. self.usage = usage
  155. # 收到websocket错误的处理
  156. def on_error(ws, error):
  157. logger.error("[XunFei] error:", error)
  158. # 收到websocket关闭的处理
  159. def on_close(ws, one, two):
  160. data_queue = queue_map.get(ws.session_id)
  161. data_queue.put("END")
  162. # 收到websocket连接建立的处理
  163. def on_open(ws):
  164. logger.info(f"[XunFei] Start websocket, session_id={ws.session_id}")
  165. thread.start_new_thread(run, (ws,))
  166. def run(ws, *args):
  167. data = json.dumps(gen_params(appid=ws.appid, domain=ws.domain, question=ws.question, temperature=ws.temperature))
  168. ws.send(data)
  169. # Websocket 操作
  170. # 收到websocket消息的处理
  171. def on_message(ws, message):
  172. data = json.loads(message)
  173. code = data['header']['code']
  174. if code != 0:
  175. logger.error(f'请求错误: {code}, {data}')
  176. ws.close()
  177. else:
  178. choices = data["payload"]["choices"]
  179. status = choices["status"]
  180. content = choices["text"][0]["content"]
  181. data_queue = queue_map.get(ws.session_id)
  182. if not data_queue:
  183. logger.error(f"[XunFei] can't find data queue, session_id={ws.session_id}")
  184. return
  185. reply_item = ReplyItem(content)
  186. if status == 2:
  187. usage = data["payload"].get("usage")
  188. reply_item = ReplyItem(content, usage)
  189. reply_item.is_end = True
  190. ws.close()
  191. data_queue.put(reply_item)
  192. def gen_params(appid, domain, question, temperature=0.5):
  193. """
  194. 通过appid和用户的提问来生成请参数
  195. """
  196. data = {
  197. "header": {
  198. "app_id": appid,
  199. "uid": "1234"
  200. },
  201. "parameter": {
  202. "chat": {
  203. "domain": domain,
  204. "temperature": temperature,
  205. "random_threshold": 0.5,
  206. "max_tokens": 2048,
  207. "auditing": "default"
  208. }
  209. },
  210. "payload": {
  211. "message": {
  212. "text": question
  213. }
  214. }
  215. }
  216. return data