File size: 4,083 Bytes
501bc8c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | """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"},
)
|