From ed7ba0230d7c3e1d25304ae199d8f40e0449c99d Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期三, 16 十月 2024 15:26:30 +0800
Subject: [PATCH] 对话兼容报错没data前缀,ragflow会话历史传空时创建会话

---
 app/api/chat.py |   19 ++++++++++++++++---
 1 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/app/api/chat.py b/app/api/chat.py
index 80005f7..828b7e8 100644
--- a/app/api/chat.py
+++ b/app/api/chat.py
@@ -43,10 +43,23 @@
                 while True:
                     message = await websocket.receive_json()
                     print(f"Received from client {chat_id}: {message}")
-                    async for rag_response in ragflow_service.chat(token, chat_id, message["chatHistory"]):
+                    chat_history = message.get('chatHistory', [])
+                    if len(chat_history) == 0:
+
+                        chat_history = await ragflow_service.set_session(token, agent_id, message["message"], chat_id, True)
+                        if len(chat_history) == 0:
+                            result = {"message": "鍐呴儴閿欒锛氬垱寤轰細璇濆け璐�", "type": "close"}
+                            await websocket.send_json(result)
+                            continue
+                    async for rag_response in ragflow_service.chat(token, chat_id, chat_history):
                         try:
                             print(f"Received from ragflow: {rag_response}")
-                            json_str = rag_response[5:].strip()
+                            if rag_response[:5] == "data:":
+                                # 濡傛灉鏄紝鍒欐埅鍙栨帀鍓�5涓瓧绗︼紝骞跺幓闄ら灏剧┖鐧界
+                                json_str = rag_response[5:].strip()
+                            else:
+                                # 鍚﹀垯锛屼繚鎸佸師鏍�
+                                json_str = rag_response
                             json_data = json.loads(json_str)
                             data = json_data.get("data")
                             if data is True:  # 瀹屾垚杈撳嚭
@@ -55,7 +68,7 @@
                                 answer = json_data.get("retmsg", json_data.get("retcode"))
                                 result = {"message": "鍐呴儴閿欒锛�" + answer, "type": "stream"}
                             else:  # 姝e父杈撳嚭
-                                answer = json_data.get("data", {}).get("answer", "")
+                                answer = data.get("answer", "")
                                 result = {"message": answer, "type": "stream"}
                             await websocket.send_json(result)
                             print(f"Forwarded to client {chat_id}: {result}")

--
Gitblit v1.8.0