chat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import json
  2. import uuid
  3. from fastapi import WebSocket, WebSocketDisconnect, APIRouter, Depends
  4. import asyncio
  5. import websockets
  6. from sqlalchemy.orm import Session
  7. from app.api import get_current_user_websocket
  8. from app.config.config import settings
  9. from app.models.agent_model import AgentModel, AgentType
  10. from app.models.base_model import get_db
  11. from app.models.user_model import UserModel
  12. from app.service.dialog import update_session_history
  13. from app.service.basic import BasicService
  14. from app.service.ragflow import RagflowService
  15. from app.service.service_token import get_bisheng_token, get_ragflow_token
  16. from app.service.session import SessionService
  17. router = APIRouter()
  18. # 中间层WebSocket 服务器,接收客户端的连接
  19. @router.websocket("/ws/{agent_id}/{chat_id}")
  20. async def handle_client(websocket: WebSocket,
  21. agent_id: str,
  22. chat_id: str,
  23. current_user: UserModel = Depends(get_current_user_websocket),
  24. db: Session = Depends(get_db)):
  25. tasks = []
  26. await websocket.accept()
  27. print(f"Client {agent_id} connected")
  28. agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
  29. if not agent:
  30. ret = {"message": "Agent not found", "type": "close"}
  31. await websocket.send_json(ret)
  32. return
  33. agent_type = agent.agent_type
  34. if chat_id == "" or chat_id == "0":
  35. ret = {"message": "Chat ID not found", "type": "close"}
  36. await websocket.send_json(ret)
  37. return
  38. if agent_type == AgentType.RAGFLOW:
  39. ragflow_service = RagflowService(settings.fwr_base_url)
  40. token = get_ragflow_token(db, current_user.id)
  41. try:
  42. async def forward_to_ragflow():
  43. while True:
  44. is_new = False
  45. message = await websocket.receive_json()
  46. print(f"Received from client {chat_id}: {message}")
  47. chat_history = message.get('chatHistory', [])
  48. message["role"] = "user"
  49. if len(chat_history) == 0:
  50. chat_history = await ragflow_service.get_session_history(token, chat_id)
  51. if len(chat_history) == 0:
  52. is_new = True
  53. chat_history = await ragflow_service.set_session(token, agent_id,
  54. message, chat_id, True)
  55. # print("chat_history------------------------", chat_history)
  56. if len(chat_history) == 0:
  57. result = {"message": "内部错误:创建会话失败", "type": "close"}
  58. await websocket.send_json(result)
  59. await websocket.close()
  60. return
  61. else:
  62. chat_history.append({
  63. "content": message["message"],
  64. "doc_ids": message.get("doc_ids", []),
  65. "role": "user"
  66. })
  67. complete_response = ""
  68. async for rag_response in ragflow_service.chat(token, chat_id, chat_history):
  69. try:
  70. if rag_response[:5] == "data:":
  71. # 如果是,则截取掉前5个字符,并去除首尾空白符
  72. text = rag_response[5:].strip()
  73. else:
  74. # 否则,保持原样
  75. text = rag_response
  76. complete_response += text
  77. try:
  78. json_data = json.loads(complete_response)
  79. data = json_data.get("data")
  80. if data is True: # 完成输出
  81. result = {"message": "", "type": "close"}
  82. elif data is None: # 发生错误
  83. answer = json_data.get("retmsg", json_data.get("retcode"))
  84. result = {"message": "内部错误:" + answer, "type": "message"}
  85. else: # 正常输出
  86. answer = data.get("answer", "")
  87. reference = data.get("reference", {})
  88. result = {"message": answer, "type": "message", "reference": reference}
  89. await websocket.send_json(result)
  90. complete_response = ""
  91. except json.JSONDecodeError as e:
  92. print(f"Error decoding JSON: {e}")
  93. # print(f"Response text: {text}")
  94. except Exception as e2:
  95. result = {"message": f"内部错误: {e2}", "type": "close"}
  96. await websocket.send_json(result)
  97. print(f"Error process message of ragflow: {e2}")
  98. dialog_chat_history = await ragflow_service.get_session_history(token, chat_id, 1)
  99. await update_session_history(db, dialog_chat_history, current_user.id, is_new)
  100. # 启动任务处理客户端消息
  101. tasks = [
  102. asyncio.create_task(forward_to_ragflow())
  103. ]
  104. await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
  105. except WebSocketDisconnect as e1:
  106. print(f"Client {chat_id} disconnected: {e1}")
  107. await websocket.close()
  108. except Exception as e:
  109. print(f"Exception occurred: {e}")
  110. finally:
  111. print("Cleaning up resources of ragflow")
  112. # 取消所有任务
  113. for task in tasks:
  114. if not task.done():
  115. task.cancel()
  116. try:
  117. await task
  118. except asyncio.CancelledError:
  119. pass
  120. elif agent_type == AgentType.BISHENG:
  121. token = get_bisheng_token(db, current_user.id)
  122. service_uri = f"{settings.sgb_websocket_url}/api/v1/assistant/chat/{agent_id}?t=&chat_id={chat_id}"
  123. headers = {'cookie': f"access_token_cookie={token};"}
  124. async with websockets.connect(service_uri, extra_headers=headers) as service_websocket:
  125. try:
  126. # 处理客户端发来的消息
  127. async def forward_to_service():
  128. while True:
  129. message = await websocket.receive_json()
  130. print(f"Received from client, {chat_id}: {message}")
  131. # 添加 'agent_id' 和 'chat_id' 字段
  132. message['flow_id'] = agent_id
  133. message['chat_id'] = chat_id
  134. msg = message["message"]
  135. del message["message"]
  136. message['inputs'] = {
  137. "data": {"chatId": chat_id, "id": agent_id, "type": "assistant"},
  138. "input": msg
  139. }
  140. await service_websocket.send(json.dumps(message))
  141. print(f"Forwarded to bisheng: {message}")
  142. # 监听毕昇发来的消息并转发给客户端
  143. async def forward_to_client():
  144. while True:
  145. message = await service_websocket.recv()
  146. print(f"Received from bisheng: {message}")
  147. data = json.loads(message)
  148. if data["type"] == "close" or data["type"] == "stream" or data["type"] == "end_cover":
  149. if data["type"] == "close":
  150. t = "close"
  151. else:
  152. t = "stream"
  153. result = {"message": data["message"], "type": t}
  154. await websocket.send_json(result)
  155. print(f"Forwarded to client, {chat_id}: {result}")
  156. # 启动两个任务,分别处理客户端和服务端的消息
  157. tasks = [
  158. asyncio.create_task(forward_to_service()),
  159. asyncio.create_task(forward_to_client())
  160. ]
  161. done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
  162. # 取消未完成的任务
  163. for task in pending:
  164. task.cancel()
  165. try:
  166. await task
  167. except asyncio.CancelledError:
  168. pass
  169. except WebSocketDisconnect as e:
  170. print(f"WebSocket connection closed with code {e.code}: {e.reason}")
  171. await websocket.close()
  172. await service_websocket.close()
  173. except Exception as e:
  174. print(f"Exception occurred: {e}")
  175. finally:
  176. print("Cleaning up resources of bisheng")
  177. # 取消所有任务
  178. for task in tasks:
  179. if not task.done():
  180. task.cancel()
  181. try:
  182. await task
  183. except asyncio.CancelledError:
  184. pass
  185. elif agent_type == AgentType.BASIC:
  186. try:
  187. while True:
  188. # 接收前端消息
  189. message = await websocket.receive_json()
  190. question = message.get("message")
  191. SessionService(db).create_session(
  192. session_id=chat_id,
  193. name=question,
  194. agent_id=agent_id,
  195. agent_type=AgentType.BASIC
  196. )
  197. if not question:
  198. await websocket.send_json({"message": "Invalid request", "type": "error"})
  199. continue
  200. service = BasicService(base_url=settings.basic_base_url)
  201. async for result in service.excel_talk(question, chat_id):
  202. try:
  203. if result[:5] == "data:":
  204. # 如果是,则截取掉前5个字符,并去除首尾空白符
  205. text = result[5:].strip()
  206. else:
  207. # 否则,保持原样
  208. text = result
  209. try:
  210. data = json.loads(text)
  211. output = data.get("output", "")
  212. excel_name = data.get("excel_name", "")
  213. image_name = data.get("excel_name", "")
  214. excel_url = None
  215. image_url = None
  216. if excel_name:
  217. excel_url = f"/api/files/download/?agent_id=basic_excel_talk&file_id={excel_name}&file_type=excel"
  218. if image_name:
  219. image_url = f"/api/files/download/?agent_id=basic_excel_talk&file_id={image_name}&file_type=image"
  220. result = {"message": output, "type": "message", "excel_url": excel_url, "image_url": image_url}
  221. await websocket.send_json(result | data)
  222. except json.JSONDecodeError as e:
  223. print(f"Error decoding JSON: {e}")
  224. print(f"Response text: {text}")
  225. except Exception as e2:
  226. result = {"message": f"内部错误: {e2}", "type": "close"}
  227. await websocket.send_json(result)
  228. print(f"Error process message of basic agent: {e2}")
  229. except Exception as e:
  230. await websocket.send_json({"message": str(e), "type": "error"})
  231. finally:
  232. await websocket.close()
  233. print(f"Client {agent_id} disconnected")
  234. else:
  235. ret = {"message": "Agent not found", "type": "close"}
  236. await websocket.send_json(ret)