zhaoqingang
2024-11-07 50f9b062456bd595d4fee86e7c90e0cac8904960
app/api/chat.py
@@ -23,6 +23,7 @@
                        chat_id: str,
                        current_user: UserModel = Depends(get_current_user_websocket),
                        db: Session = Depends(get_db)):
    tasks = []
    await websocket.accept()
    print(f"Client {agent_id} connected")
@@ -87,18 +88,31 @@
                                print(f"Error decode ragflow response: {text}")
                                pass
                        except Exception as e:
                            result = {"message": f"内部错误: {e}", "type": "close"}
                        except Exception as e2:
                            result = {"message": f"内部错误: {e2}", "type": "close"}
                            await websocket.send_json(result)
                            print(f"Error process message of ragflow: {e}")
                            print(f"Error process message of ragflow: {e2}")
            # 启动任务处理客户端消息
            tasks = [
                asyncio.create_task(forward_to_ragflow())
            ]
            await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
        except WebSocketDisconnect:
            print(f"Client {chat_id} disconnected")
        except WebSocketDisconnect as e1:
            print(f"Client {chat_id} disconnected: {e1}")
            await websocket.close()
        except Exception as e:
            print(f"Exception occurred: {e}")
        finally:
            print("Cleaning up resources of ragflow")
            # 取消所有任务
            for task in tasks:
                if not task.done():
                    task.cancel()
                    try:
                        await task
                    except asyncio.CancelledError:
                        pass
    elif agent_type == AgentType.BISHENG:
        token = get_bisheng_token(db, current_user.id)
@@ -155,8 +169,23 @@
                    except asyncio.CancelledError:
                        pass
            except WebSocketDisconnect:
                print(f"Client {chat_id} disconnected")
            except WebSocketDisconnect as e:
                print(f"WebSocket connection closed with code {e.code}: {e.reason}")
                await websocket.close()
                await service_websocket.close()
            except Exception as e:
                print(f"Exception occurred: {e}")
            finally:
                print("Cleaning up resources of bisheng")
                # 取消所有任务
                for task in tasks:
                    if not task.done():
                        task.cancel()
                        try:
                            await task
                        except asyncio.CancelledError:
                            pass
    else:
        ret = {"message": "Agent not found", "type": "close"}
        await websocket.send_json(ret)