from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from slowapi import _rate_limit_exceeded_handler from slowapi.errors import RateLimitExceeded import logging # Set up logging to stdout logging.basicConfig(level=logging.INFO) logger = logging.getLogger("ai_gateway") from app.api.router import api_router from app.core.config import settings from app.core.limiter import limiter from app.core.database import engine, Base from app.models import module # Ensure models are loaded # Create tables Base.metadata.create_all(bind=engine) from fastapi.staticfiles import StaticFiles from app.api.endpoints import auth from app.api import admin_backend def create_application() -> FastAPI: # Disable docs and redoc in production docs_url = "/docs" if settings.ENVIRONMENT == "development" else None redoc_url = "/redoc" if settings.ENVIRONMENT == "development" else None application = FastAPI( title=settings.PROJECT_NAME, docs_url=docs_url, redoc_url=redoc_url ) # Mount Static Files application.mount("/static", StaticFiles(directory="app/static"), name="static") # Debug Logger Middleware @application.middleware("http") async def log_requests(request: Request, call_next): logger.info(f"DEBUG: Incoming {request.method} {request.url}") logger.info(f"DEBUG: Origin: {request.headers.get('origin')}") response = await call_next(request) logger.info(f"DEBUG: Status Code: {response.status_code}") return response # Set up fully permissive CORS for standalone/tunnelling mode application.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Set up Rate Limiter application.state.limiter = limiter @application.exception_handler(RateLimitExceeded) async def custom_rate_limit_exceeded_handler(request, exc): from fastapi.responses import JSONResponse return JSONResponse( status_code=429, content={ "error": "Too Many Requests", "message": "Chill out! You've reached the rate limit. Please wait a moment before trying again." } ) # Include routes application.include_router(api_router, prefix="/api/v1") application.include_router(auth.router, prefix="/auth", tags=["auth"]) application.include_router(admin_backend.router, prefix="/internal/admin", tags=["internal-admin"]) return application app = create_application() from fastapi.responses import FileResponse import os @app.get("/admin") async def admin_panel(): return FileResponse("app/static/admin.html") @app.get("/api/v1/health") async def health_check(): return {"status": "ok", "message": "Global AI Gateway is reachable"} @app.get("/") async def root(): return FileResponse("app/static/index.html")