Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

265 rindas
8.7KB

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