Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

251 line
8.3KB

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