zhaoqingang
2024-11-26 6ae19ce01dbdfdb1080802d854b13adda3982172
app/api/chat.py
@@ -297,7 +297,7 @@
                    conversation_id = ""
                    receive_message = await websocket.receive_json()
                    print(f"Received from client {chat_id}: {receive_message}")
                    upload_file_id = receive_message.get('upload_file_id', [])
                    upload_file_id = receive_message.get('upload_file_id', "")
                    question = receive_message.get('message', "")
                    if not question and not image_url:
                        await websocket.send_json({"message": "Invalid request", "type": "error"})
@@ -313,30 +313,60 @@
                        conversation_id = session.conversation_id
                    except Exception as e:
                        logger.error(e)
                    complete_response = ""
                    async for rag_response in dify_service.chat(token, chat_id, question, upload_file_id, conversation_id):
                    # complete_response = ""
                    answer_str = ""
                    async for rag_response in dify_service.chat(token, current_user.id, question, upload_file_id, conversation_id):
                        # print("=============================================")
                        # print(rag_response)
                        try:
                            if rag_response[:5] == "data:":
                                # 如果是,则截取掉前5个字符,并去除首尾空白符
                                text = rag_response[5:].strip()
                                complete_response = rag_response[5:].strip()
                            else:
                                # 否则,保持原样
                                text = rag_response
                            complete_response += text
                                complete_response = rag_response
                            # complete_response += text
                            try:
                                data = json.loads(complete_response)
                                complete_response = ""
                                # data = json_data.get("data")
                                if "answer" not in  data:  # 信息过滤
                                    continue
                                else:  # 正常输出
                                    answer = data.get("answer", "")
                                if data.get("event") == "agent_message":# "event": "message_end"
                                    if "answer" not in  data or not data["answer"]:  # 信息过滤
                                        logger.error("非法数据--------------------")
                                        # logger.error(data)
                                    result = {"message": answer, "type": "message"}
                                        continue
                                    else:  # 正常输出
                                        answer = data.get("answer", "")
                                        if isinstance(answer, str):
                                            answer_str += answer
                                        elif isinstance(answer, dict):
                                            logger.error("未知数据体:0---------------------------------")
                                            logger.error(answer)
                                            answer_str += answer.get("action_input", "")
                                        result = {"message": answer_str, "type": "message"}
                                elif data.get("event") == "message_end":
                                    message_files = []
                                    res_msg = await dify_service.get_session_history(token, data.get("conversation_id"), str(current_user.id))
                                    if len(res_msg) > 0:
                                        message_files = res_msg[0].get("message_files")
                                    result = {"message": answer_str, "type": "close", "message_files": message_files}
                                    try:
                                        SessionService(db).update_session(chat_id,
                                                                          message={"role": "assistant", "content": data, "conversation_id": data.get("conversation_id")})
                                                                          message={"role": "assistant", "content": {"answer":answer_str, "images":[i.get("url") for i in message_files]}},conversation_id=data.get("conversation_id"))
                                    except Exception as e:
                                        logger.error("保存dify的会话异常!")
                                        logger.error(e)
                                elif data.get("event") == "message_file":
                                    url = data.get("url", "")
                                    result = {"message": url, "type": "image"}
                                else:
                                    continue
                                await websocket.send_json(result)
                                complete_response = ""
                            except json.JSONDecodeError as e:
@@ -346,12 +376,7 @@
                            result = {"message": f"内部错误: {e2}", "type": "close"}
                            await websocket.send_json(result)
                            print(f"Error process message of ragflow: {e2}")
                    try:
                        dialog_chat_history = await ragflow_service.get_session_history(token, chat_id, 1)
                        await update_session_history(db, dialog_chat_history, current_user.id)
                    except Exception as e:
                        logger.error(e)
                        logger.error("-----------------保存ragflow的历史会话异常-----------------")
            # 启动任务处理客户端消息
            tasks = [