Spaces:
Running
Running
| import logging | |
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.exceptions import RequestValidationError | |
| from starlette.exceptions import HTTPException as StarletteHTTPException | |
| # Import routers | |
| from api.routers import medical, health, export, auth | |
| from api.middleware import ( | |
| ProcessTimeMiddleware, | |
| LoggingMiddleware, | |
| RateLimitMiddleware, | |
| AuthenticationMiddleware, | |
| get_cors_middleware_config | |
| ) | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from api.exceptions import ( | |
| http_exception_handler, | |
| validation_exception_handler, | |
| general_exception_handler, | |
| starlette_exception_handler | |
| ) | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| async def lifespan(app: FastAPI): | |
| """Application lifespan management with background initialization""" | |
| # Startup | |
| logger.info("Starting Lung Cancer AI Advisor API...") | |
| # Start background initialization of heavy components | |
| try: | |
| from core.background_init import start_background_initialization | |
| logger.info("π Starting background initialization of components...") | |
| start_background_initialization() | |
| logger.info("API started successfully (components loading in background)") | |
| except Exception as e: | |
| logger.error(f"Failed to start background initialization: {e}") | |
| logger.info("API started with lazy loading fallback") | |
| yield | |
| # Shutdown | |
| logger.info("Shutting down Lung Cancer AI Advisor API...") | |
| # Create FastAPI application | |
| app = FastAPI( | |
| title="Lung Cancer AI Advisor API", | |
| description="""AI-Powered Lung Cancer Information & Support API | |
| This API provides intelligent responses to lung cancer-related queries using advanced AI and medical knowledge retrieval. | |
| **Key Features:** | |
| - Intelligent Query Processing: AI agent automatically selects appropriate tools and data sources | |
| - Session Management: Maintains conversation context across multiple queries | |
| - Streaming Support: Real-time response streaming for better UX | |
| - Medical Knowledge Base: Access to comprehensive lung cancer information | |
| **Main Endpoints:** | |
| - POST /ask - Get complete AI response for a query | |
| - POST /ask/stream - Stream AI response in real-time (recommended for better UX) | |
| - GET /health - Check API health and initialization status | |
| - POST /export/{format} - Export conversation history | |
| """, | |
| version="1.0.0", | |
| docs_url="/docs", | |
| redoc_url="/redoc", | |
| lifespan=lifespan | |
| ) | |
| # Add middleware | |
| app.add_middleware(CORSMiddleware, **get_cors_middleware_config()) | |
| app.add_middleware(ProcessTimeMiddleware) | |
| app.add_middleware(LoggingMiddleware) | |
| app.add_middleware(RateLimitMiddleware, calls_per_minute=100) # Adjust as needed | |
| app.add_middleware(AuthenticationMiddleware) # Protect API endpoints | |
| # Add exception handlers | |
| app.add_exception_handler(HTTPException, http_exception_handler) | |
| app.add_exception_handler(RequestValidationError, validation_exception_handler) | |
| app.add_exception_handler(StarletteHTTPException, starlette_exception_handler) | |
| app.add_exception_handler(Exception, general_exception_handler) | |
| # Include routers | |
| app.include_router(auth.router) | |
| app.include_router(health.router) | |
| app.include_router(medical.router) | |
| app.include_router(export.router) | |
| # Root endpoint | |
| async def root(): | |
| """Root endpoint with API information""" | |
| return { | |
| "name": "Lung Cancer AI Advisor API", | |
| "version": "1.0.0", | |
| "description": "AI-powered advisor for lung cancer information and support", | |
| "docs": "/docs", | |
| "health": "/health", | |
| "endpoints": { | |
| "ask": "/ask", | |
| "ask_stream": "/ask/stream", | |
| "initialization_status": "/health/initialization", | |
| "export": "/export/{format}?session_id={session_id}" | |
| } | |
| } | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run( | |
| "api.app:app", | |
| host="127.0.0.1", | |
| port=8000, | |
| reload=True, | |
| log_level="info" | |
| ) | |