omgy commited on
Commit
48194e0
·
verified ·
1 Parent(s): 1c37d25

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +156 -155
app/main.py CHANGED
@@ -1,155 +1,156 @@
1
- """
2
- Main FastAPI application for FinAgent backend.
3
- Chat2Sanction - AI-powered loan processing platform.
4
- """
5
-
6
- import os
7
- from contextlib import asynccontextmanager
8
-
9
- from app.config import settings
10
- from app.routers import admin, auth, chat, loan
11
- from app.utils.logger import setup_logger
12
- from fastapi import FastAPI
13
- from fastapi.middleware.cors import CORSMiddleware
14
- from fastapi.responses import JSONResponse
15
-
16
- # Setup logger
17
- logger = setup_logger("finagent", log_file="finagent.log")
18
-
19
-
20
- @asynccontextmanager
21
- async def lifespan(app: FastAPI):
22
- """
23
- Lifespan context manager for startup and shutdown events.
24
- """
25
- # Startup
26
- logger.info("=" * 80)
27
- logger.info(f"Starting {settings.APP_NAME} v{settings.APP_VERSION}")
28
- logger.info("=" * 80)
29
- logger.info(f"Environment: {'Development' if settings.DEBUG else 'Production'}")
30
- logger.info(f"Firebase Project: {settings.FIREBASE_PROJECT_ID}")
31
- logger.info(f"Gemini Model: {settings.GEMINI_MODEL}")
32
-
33
- # Initialize services
34
- try:
35
- from app.agents.master_agent import master_agent
36
- from app.services.firebase_service import firebase_service
37
- from app.services.pdf_service import pdf_service
38
- from app.services.session_service import session_service
39
- from app.services.underwriting_service import underwriting_service
40
-
41
- logger.info("All services initialized successfully")
42
- except Exception as e:
43
- logger.error(f"Failed to initialize services: {str(e)}")
44
-
45
- # Create output directories
46
- os.makedirs(settings.PDF_OUTPUT_DIR, exist_ok=True)
47
- logger.info(f"PDF output directory: {settings.PDF_OUTPUT_DIR}")
48
-
49
- logger.info("✓ Application startup complete")
50
- logger.info("=" * 80)
51
-
52
- yield
53
-
54
- # Shutdown
55
- logger.info("=" * 80)
56
- logger.info("Shutting down application")
57
- logger.info("=" * 80)
58
-
59
-
60
- # Create FastAPI app
61
- app = FastAPI(
62
- title=settings.APP_NAME,
63
- description="AI-powered loan processing platform with conversational interface",
64
- version=settings.APP_VERSION,
65
- lifespan=lifespan,
66
- docs_url="/api/docs",
67
- redoc_url="/api/redoc",
68
- openapi_url="/api/openapi.json",
69
- )
70
-
71
- # Configure CORS
72
- app.add_middleware(
73
- CORSMiddleware,
74
- allow_origins=settings.ALLOWED_ORIGINS,
75
- allow_credentials=True,
76
- allow_methods=["*"],
77
- allow_headers=["*"],
78
- )
79
-
80
-
81
- # Health check endpoint
82
- @app.get("/")
83
- async def root():
84
- """Root endpoint with API information."""
85
- return {
86
- "name": settings.APP_NAME,
87
- "version": settings.APP_VERSION,
88
- "status": "running",
89
- "docs": "/api/docs",
90
- }
91
-
92
-
93
- @app.get("/health")
94
- async def health_check():
95
- """Health check endpoint."""
96
- from app.services.firebase_service import firebase_service
97
-
98
- return {
99
- "status": "healthy",
100
- "firebase": "connected" if firebase_service.initialized else "disconnected",
101
- "gemini": "configured" if settings.GOOGLE_API_KEY else "not configured",
102
- }
103
-
104
-
105
- # Include routers
106
- app.include_router(auth.router, prefix="/api/auth", tags=["Authentication"])
107
- app.include_router(chat.router, prefix="/api/chat", tags=["Chat"])
108
- app.include_router(loan.router, prefix="/api/loan", tags=["Loans"])
109
- app.include_router(admin.router, prefix="/api/admin", tags=["Admin"])
110
-
111
-
112
- # Global exception handler
113
- @app.exception_handler(Exception)
114
- async def global_exception_handler(request, exc):
115
- """Global exception handler for unhandled errors."""
116
- logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
117
- return JSONResponse(
118
- status_code=500,
119
- content={
120
- "error": "Internal server error",
121
- "detail": str(exc) if settings.DEBUG else "An unexpected error occurred",
122
- },
123
- )
124
-
125
-
126
- # Request logging middleware
127
- @app.middleware("http")
128
- async def log_requests(request, call_next):
129
- """Log all HTTP requests."""
130
- from time import time
131
-
132
- start_time = time()
133
-
134
- # Process request
135
- response = await call_next(request)
136
-
137
- # Log request
138
- duration = (time() - start_time) * 1000 # Convert to milliseconds
139
- logger.info(
140
- f"{request.method} {request.url.path} - {response.status_code} ({duration:.2f}ms)"
141
- )
142
-
143
- return response
144
-
145
-
146
- if __name__ == "__main__":
147
- import uvicorn
148
-
149
- uvicorn.run(
150
- "app.main:app",
151
- host=settings.HOST,
152
- port=settings.PORT,
153
- reload=settings.DEBUG,
154
- workers=settings.WORKERS,
155
- )
 
 
1
+ """
2
+ Main FastAPI application for FinAgent backend.
3
+ Chat2Sanction - AI-powered loan processing platform.
4
+ """
5
+
6
+ import os
7
+ from contextlib import asynccontextmanager
8
+
9
+ from app.config import settings
10
+ from app.routers import admin, auth, chat, loan
11
+ from app.utils.logger import setup_logger
12
+ from fastapi import FastAPI
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from fastapi.responses import JSONResponse
15
+
16
+ # Setup logger
17
+ logger = setup_logger("finagent", log_file="finagent.log")
18
+
19
+
20
+ @asynccontextmanager
21
+ async def lifespan(app: FastAPI):
22
+ """
23
+ Lifespan context manager for startup and shutdown events.
24
+ """
25
+ # Startup
26
+ logger.info("=" * 80)
27
+ logger.info(f"Starting {settings.APP_NAME} v{settings.APP_VERSION}")
28
+ logger.info("=" * 80)
29
+ logger.info(f"Environment: {'Development' if settings.DEBUG else 'Production'}")
30
+ logger.info(f"Firebase Project: {settings.FIREBASE_PROJECT_ID}")
31
+ logger.info(f"LLM Model: {getattr(settings, 'GEMINI_MODEL', 'Not configured')}")
32
+
33
+
34
+ # Initialize services
35
+ try:
36
+ from app.agents.master_agent import master_agent
37
+ from app.services.firebase_service import firebase_service
38
+ from app.services.pdf_service import pdf_service
39
+ from app.services.session_service import session_service
40
+ from app.services.underwriting_service import underwriting_service
41
+
42
+ logger.info("All services initialized successfully")
43
+ except Exception as e:
44
+ logger.error(f"Failed to initialize services: {str(e)}")
45
+
46
+ # Create output directories
47
+ os.makedirs(settings.PDF_OUTPUT_DIR, exist_ok=True)
48
+ logger.info(f"PDF output directory: {settings.PDF_OUTPUT_DIR}")
49
+
50
+ logger.info(" Application startup complete")
51
+ logger.info("=" * 80)
52
+
53
+ yield
54
+
55
+ # Shutdown
56
+ logger.info("=" * 80)
57
+ logger.info("Shutting down application")
58
+ logger.info("=" * 80)
59
+
60
+
61
+ # Create FastAPI app
62
+ app = FastAPI(
63
+ title=settings.APP_NAME,
64
+ description="AI-powered loan processing platform with conversational interface",
65
+ version=settings.APP_VERSION,
66
+ lifespan=lifespan,
67
+ docs_url="/api/docs",
68
+ redoc_url="/api/redoc",
69
+ openapi_url="/api/openapi.json",
70
+ )
71
+
72
+ # Configure CORS
73
+ app.add_middleware(
74
+ CORSMiddleware,
75
+ allow_origins=settings.ALLOWED_ORIGINS,
76
+ allow_credentials=True,
77
+ allow_methods=["*"],
78
+ allow_headers=["*"],
79
+ )
80
+
81
+
82
+ # Health check endpoint
83
+ @app.get("/")
84
+ async def root():
85
+ """Root endpoint with API information."""
86
+ return {
87
+ "name": settings.APP_NAME,
88
+ "version": settings.APP_VERSION,
89
+ "status": "running",
90
+ "docs": "/api/docs",
91
+ }
92
+
93
+
94
+ @app.get("/health")
95
+ async def health_check():
96
+ """Health check endpoint."""
97
+ from app.services.firebase_service import firebase_service
98
+
99
+ return {
100
+ "status": "healthy",
101
+ "firebase": "connected" if firebase_service.initialized else "disconnected",
102
+ "gemini": "configured" if settings.GOOGLE_API_KEY else "not configured",
103
+ }
104
+
105
+
106
+ # Include routers
107
+ app.include_router(auth.router, prefix="/api/auth", tags=["Authentication"])
108
+ app.include_router(chat.router, prefix="/api/chat", tags=["Chat"])
109
+ app.include_router(loan.router, prefix="/api/loan", tags=["Loans"])
110
+ app.include_router(admin.router, prefix="/api/admin", tags=["Admin"])
111
+
112
+
113
+ # Global exception handler
114
+ @app.exception_handler(Exception)
115
+ async def global_exception_handler(request, exc):
116
+ """Global exception handler for unhandled errors."""
117
+ logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
118
+ return JSONResponse(
119
+ status_code=500,
120
+ content={
121
+ "error": "Internal server error",
122
+ "detail": str(exc) if settings.DEBUG else "An unexpected error occurred",
123
+ },
124
+ )
125
+
126
+
127
+ # Request logging middleware
128
+ @app.middleware("http")
129
+ async def log_requests(request, call_next):
130
+ """Log all HTTP requests."""
131
+ from time import time
132
+
133
+ start_time = time()
134
+
135
+ # Process request
136
+ response = await call_next(request)
137
+
138
+ # Log request
139
+ duration = (time() - start_time) * 1000 # Convert to milliseconds
140
+ logger.info(
141
+ f"{request.method} {request.url.path} - {response.status_code} ({duration:.2f}ms)"
142
+ )
143
+
144
+ return response
145
+
146
+
147
+ if __name__ == "__main__":
148
+ import uvicorn
149
+
150
+ uvicorn.run(
151
+ "app.main:app",
152
+ host=settings.HOST,
153
+ port=settings.PORT,
154
+ reload=settings.DEBUG,
155
+ workers=settings.WORKERS,
156
+ )