|
| 1 | +""" |
| 2 | +FastAPI server for the Plexe conversational agent. |
| 3 | +
|
| 4 | +This module provides a lightweight WebSocket API for the conversational agent |
| 5 | +and serves the assistant-ui frontend for local execution. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import uuid |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
| 14 | +from fastapi.staticfiles import StaticFiles |
| 15 | +from fastapi.responses import FileResponse |
| 16 | + |
| 17 | +from plexe.agents.conversational import ConversationalAgent |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +app = FastAPI(title="Plexe Assistant", version="1.0.0") |
| 22 | + |
| 23 | +# Serve static files from the ui directory |
| 24 | +ui_dir = Path(__file__).parent / "ui" |
| 25 | +if ui_dir.exists(): |
| 26 | + app.mount("/static", StaticFiles(directory=str(ui_dir)), name="static") |
| 27 | + |
| 28 | + |
| 29 | +@app.get("/") |
| 30 | +async def root(): |
| 31 | + """Serve the main HTML page.""" |
| 32 | + index_path = ui_dir / "index.html" |
| 33 | + if index_path.exists(): |
| 34 | + return FileResponse(str(index_path)) |
| 35 | + return {"error": "Frontend not found. Please ensure plexe/ui/index.html exists."} |
| 36 | + |
| 37 | + |
| 38 | +@app.websocket("/ws") |
| 39 | +async def websocket_endpoint(websocket: WebSocket): |
| 40 | + """WebSocket endpoint for real-time chat communication.""" |
| 41 | + await websocket.accept() |
| 42 | + session_id = str(uuid.uuid4()) |
| 43 | + logger.info(f"New WebSocket connection: {session_id}") |
| 44 | + |
| 45 | + # Create a new agent instance for this session |
| 46 | + agent = ConversationalAgent() |
| 47 | + |
| 48 | + try: |
| 49 | + while True: |
| 50 | + # Receive message from client |
| 51 | + data = await websocket.receive_text() |
| 52 | + |
| 53 | + try: |
| 54 | + message_data = json.loads(data) |
| 55 | + user_message = message_data.get("content", "") |
| 56 | + |
| 57 | + # Process the message with the agent |
| 58 | + logger.debug(f"Processing message: {user_message[:100]}...") |
| 59 | + response = agent.agent.run(user_message, reset=False) |
| 60 | + |
| 61 | + # Send response back to client |
| 62 | + await websocket.send_json({"role": "assistant", "content": response, "id": str(uuid.uuid4())}) |
| 63 | + |
| 64 | + except json.JSONDecodeError: |
| 65 | + # Handle plain text messages for compatibility |
| 66 | + response = agent.agent.run(data, reset=False) |
| 67 | + await websocket.send_json({"role": "assistant", "content": response, "id": str(uuid.uuid4())}) |
| 68 | + |
| 69 | + except Exception as e: |
| 70 | + logger.error(f"Error processing message: {e}") |
| 71 | + await websocket.send_json( |
| 72 | + { |
| 73 | + "role": "assistant", |
| 74 | + "content": f"I encountered an error: {str(e)}. Please try again.", |
| 75 | + "id": str(uuid.uuid4()), |
| 76 | + "error": True, |
| 77 | + } |
| 78 | + ) |
| 79 | + |
| 80 | + except WebSocketDisconnect: |
| 81 | + logger.info(f"WebSocket disconnected: {session_id}") |
| 82 | + except Exception as e: |
| 83 | + logger.error(f"WebSocket error for session {session_id}: {e}") |
| 84 | + await websocket.close() |
| 85 | + |
| 86 | + |
| 87 | +@app.get("/health") |
| 88 | +async def health_check(): |
| 89 | + """Health check endpoint.""" |
| 90 | + return {"status": "healthy", "service": "plexe-assistant"} |
0 commit comments