File size: 2,775 Bytes
b6fa51d
 
 
 
 
 
 
 
 
 
c8f7f2e
b6fa51d
 
 
350b79e
 
 
 
 
b6fa51d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8f7f2e
 
 
 
 
 
 
 
 
 
 
 
b6fa51d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350b79e
 
 
 
 
b6fa51d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FastAPI Application - Main Entry Point

DocuMind AI - RAG-Powered Documentation Assistant API
"""

import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
from fastapi.middleware.cors import CORSMiddleware

from src.api.routes import query, ingest, health
from src.api.middleware.errors import (
    ErrorHandlerMiddleware,
    RequestLoggingMiddleware,
    RateLimitMiddleware,
)
from config.settings import settings

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Application lifespan manager.
    Handles startup and shutdown events.
    """
    # Startup
    logger.info("Starting DocuMind AI API...")
    logger.info(f"Environment: {settings.environment}")

    # Warm the embedding model now, in a worker thread, so the first ingest or
    # query request doesn't pay a multi-second (potentially download-bound)
    # stall while holding the event loop.
    try:
        from src.rag.embeddings import get_embeddings

        await run_in_threadpool(lambda: get_embeddings().embed_query("warmup"))
        logger.info("Embedding model warmed up")
    except Exception as e:  # noqa: BLE001 - startup must not hard-fail on this
        logger.warning(f"Embedding warmup skipped: {e}")

    yield
    
    # Shutdown
    logger.info("Shutting down DocuMind AI API...")


# Create FastAPI application
app = FastAPI(
    title="DocuMind AI",
    description="RAG-Powered Documentation Assistant API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Add custom middleware (order matters - first added = last executed)
app.add_middleware(ErrorHandlerMiddleware)
app.add_middleware(RequestLoggingMiddleware)
app.add_middleware(RateLimitMiddleware, requests_per_minute=60)

# Include routers
app.include_router(health.router, tags=["Health"])
app.include_router(query.router, prefix="/api", tags=["Query"])
app.include_router(ingest.router, prefix="/api", tags=["Ingest"])


@app.get("/")
async def root():
    """Root endpoint with API info."""
    return {
        "name": "DocuMind AI",
        "version": "1.0.0",
        "description": "RAG-Powered Documentation Assistant",
        "docs": "/docs",
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "src.api.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
    )