"""FastAPI backend for UX Research Agent — serves the SearchEngine over HTTP/SSE.""" import json import logging from contextlib import asynccontextmanager from typing import List, Dict, Optional from fastapi import FastAPI, UploadFile, File, Form, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse from pydantic import BaseModel from src.engine.search_engine import SearchEngine from src.engine.config import config logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") logger = logging.getLogger("API") engine: Optional[SearchEngine] = None @asynccontextmanager async def lifespan(app: FastAPI): global engine logger.info("Starting up — initializing SearchEngine...") # Data sync (optional, for HF Spaces deployment) if config.hf_token and config.hf_dataset_repo: from src.data_sync import sync_from_huggingface sync_from_huggingface() engine = SearchEngine() logger.info("SearchEngine ready.") yield logger.info("Shutting down.") app = FastAPI(title="UX Research Agent API", lifespan=lifespan) # --- CORS --- ALLOWED_ORIGINS = [ "http://localhost:3000", "http://localhost:3001", ] # Allow any *.vercel.app preview deploy app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_origin_regex=r"https://.*\.vercel\.app", allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- Request / Response models --- class ChatRequest(BaseModel): query: str chat_history: List[Dict[str, str]] = [] # --- SSE helpers --- def _sse_event(event: str, data) -> str: """Format a single SSE event.""" payload = json.dumps(data, ensure_ascii=False) if not isinstance(data, str) else data return f"event: {event}\ndata: {payload}\n\n" def _stream_chat(query: str, chat_history: list, media_file: dict | None = None): """Convert SearchEngine.stream_answer() into SSE events.""" try: for event_type, data in engine.stream_answer( query=query, chat_history=chat_history, media_file=media_file, platform="web", ): if event_type == "metadata": yield _sse_event("metadata", data) elif event_type == "thinking": yield _sse_event("thinking", data) elif event_type == "status": yield _sse_event("status", {"message": data}) elif event_type == "text_delta": yield _sse_event("text_delta", {"chunk": data}) elif event_type == "complete": # Serialize answer — may be a string or dict depending on platform yield _sse_event("complete", data) yield _sse_event("done", {"status": "ok"}) except Exception as e: logger.error(f"Stream error: {e}", exc_info=True) yield _sse_event("error", {"message": str(e)}) # --- Endpoints --- @app.get("/api/health") async def health(): return {"status": "ok", "engine_loaded": engine is not None} @app.post("/api/chat") async def chat(req: ChatRequest): if not engine: raise HTTPException(status_code=503, detail="Engine not ready") return StreamingResponse( _stream_chat(req.query, req.chat_history), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) @app.post("/api/chat/multimodal") async def chat_multimodal( query: str = Form(...), chat_history: str = Form("[]"), file: UploadFile = File(...), ): if not engine: raise HTTPException(status_code=503, detail="Engine not ready") history = json.loads(chat_history) file_data = await file.read() media_file = {"data": file_data, "mime_type": file.content_type} return StreamingResponse( _stream_chat(query, history, media_file), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, )