MikelWL's picture
refactor: Simplified and streamlined the core demo and overall codebase
e3892d4
"""FastAPI main application module for AI Survey Simulator.
This module initializes the FastAPI application and configures:
- CORS middleware for frontend communication
- WebSocket endpoints for real-time conversation streaming
- REST API routes for conversation and persona management
- Database connections and session management
- Global exception handlers and logging
Typical usage:
uvicorn api.main:app --reload --host 0.0.0.0 --port 8000
"""
import logging
import sys
from pathlib import Path
from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
# Ensure project root is available for shared config imports
ROOT_DIR = Path(__file__).resolve().parents[2]
if str(ROOT_DIR) not in sys.path:
sys.path.insert(0, str(ROOT_DIR))
from config.settings import get_settings # noqa: E402
# Import WebSocket endpoint and manager
from .conversation_ws import websocket_endpoint, manager # noqa: E402
from .routes import router as conversations_router # noqa: E402
from .conversation_service import initialize_conversation_service # noqa: E402
# Load application settings
settings = get_settings()
# Setup logging using configured level
log_level = getattr(logging, settings.log_level.upper(), logging.INFO)
logging.basicConfig(level=log_level)
logger = logging.getLogger(__name__)
# Initialize FastAPI app
app = FastAPI(
title="AI Survey Simulator API",
description="Backend API for AI-to-AI healthcare survey conversations",
version="1.0.0"
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:7860", # Gradio default port
"http://127.0.0.1:7860", # Gradio alternative
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API routes
app.include_router(conversations_router)
@app.on_event("startup")
async def startup_event():
"""Initialize services on startup."""
logger.info("Initializing AI Survey Simulator API...")
# Initialize conversation service with WebSocket manager and settings
initialize_conversation_service(manager, settings)
logger.info("API startup complete")
@app.get("/")
async def root():
"""Root endpoint providing API information."""
return {
"message": "AI Survey Simulator API",
"version": "1.0.0",
"docs": "/docs",
"health": "/health"
}
@app.get("/health")
async def health_check():
"""Health check endpoint for monitoring."""
return {"status": "healthy"}
@app.websocket("/ws/conversation/{conversation_id}")
async def websocket_conversation_endpoint(websocket: WebSocket, conversation_id: str):
"""WebSocket endpoint for real-time conversation streaming.
Args:
websocket: WebSocket connection
conversation_id: Unique identifier for the conversation
"""
await websocket_endpoint(websocket, conversation_id)
if __name__ == "__main__":
uvicorn.run(app, host=settings.api.host, port=settings.api.port)