eeshanyaj commited on
Commit
c463ae7
Β·
1 Parent(s): e699f51

fix main.py printing

Browse files
Files changed (2) hide show
  1. app/main.py +65 -269
  2. app/main_backup.py +301 -0
app/main.py CHANGED
@@ -25,43 +25,47 @@ from app.db.mongodb import connect_to_mongo, close_mongo_connection
25
  # LIFESPAN MANAGER (Startup & Shutdown)
26
  # ============================================================================
27
 
 
 
 
28
  @asynccontextmanager
29
  async def lifespan(app: FastAPI):
30
  """
31
  Manage application lifespan events.
32
-
33
  Startup:
34
  - Connect to MongoDB Atlas
35
- - Create indexes for conversations
36
- - ML models load lazily on first use
37
-
38
- Shutdown:
39
- - Close MongoDB connection
40
- - Cleanup resources
41
  """
42
- # ========================================================================
43
- # STARTUP
44
- # ========================================================================
45
  print("\n" + "=" * 80)
46
  print("πŸš€ STARTING BANKING RAG CHATBOT API")
47
  print("=" * 80)
48
  print(f"Environment: {settings.ENVIRONMENT}")
49
  print(f"Debug Mode: {settings.DEBUG}")
50
  print("=" * 80)
51
-
52
- # Connect to MongoDB
 
53
  await connect_to_mongo()
54
-
55
- # Create indexes for conversations (async)
56
- try:
57
- from app.db.repositories.conversation_repository import conversation_repository
58
- await conversation_repository.create_indexes()
59
- except Exception as e:
60
- print(f"⚠️ Failed to create conversation indexes: {e}")
61
-
 
 
 
 
 
 
 
62
  print("\nπŸ’‘ ML Models Info:")
63
- print(" Policy Network: Loads on first chat request (lazy loading)")
64
- print(" Retriever Model: Loads on first retrieval (lazy loading)")
65
  print(" LLM: Groq (ChatGroq) with HuggingFace fallback")
66
  print("\nπŸ€– LLM Configuration:")
67
  print(f" Chat Model: {settings.GROQ_CHAT_MODEL} (Llama 3 8B)")
@@ -69,29 +73,25 @@ async def lifespan(app: FastAPI):
69
  print(f" Groq API Keys: {len(settings.get_groq_api_keys())} configured")
70
  print(f" HuggingFace Tokens: {len(settings.get_hf_tokens())} configured")
71
  print(f" Fallback: Groq β†’ HuggingFace")
72
-
73
  print("\nβœ… Backend startup complete!")
74
  print("=" * 80)
75
  print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
76
  print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
77
  print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
78
  print("=" * 80 + "\n")
79
-
80
- yield # Application runs here
81
-
82
- # ========================================================================
83
  # SHUTDOWN
84
- # ========================================================================
85
  print("\n" + "=" * 80)
86
  print("πŸ›‘ SHUTTING DOWN API")
87
  print("=" * 80)
88
-
89
- # Close MongoDB connection
90
  await close_mongo_connection()
91
-
92
  print("βœ… Shutdown complete")
93
  print("=" * 80 + "\n")
94
 
 
95
  # ============================================================================
96
  # CREATE FASTAPI APPLICATION
97
  # ============================================================================
@@ -333,30 +333,19 @@ if __name__ == "__main__":
333
  )
334
 
335
 
336
- # """
337
- # FastAPI Main Application Entry Point
 
 
338
 
339
- # Banking RAG Chatbot API with JWT Authentication
340
 
341
- # This file:
342
- # 1. Creates the FastAPI app
343
- # 2. Configures CORS middleware
344
- # 3. Connects to MongoDB on startup/shutdown
345
- # 4. Includes API routers (auth + chat)
346
- # 5. Provides health check endpoints
347
- # """
348
 
349
- # from fastapi import FastAPI, Request
350
- # from fastapi.middleware.cors import CORSMiddleware
351
- # from fastapi.responses import JSONResponse
352
- # from contextlib import asynccontextmanager
353
 
354
- # from app.config import settings
355
- # from app.db.mongodb import connect_to_mongo, close_mongo_connection
356
 
357
- # # ============================================================================
358
- # # LIFESPAN MANAGER (Startup & Shutdown)
359
- # # ============================================================================
 
360
 
361
  # @asynccontextmanager
362
  # async def lifespan(app: FastAPI):
@@ -365,6 +354,7 @@ if __name__ == "__main__":
365
 
366
  # Startup:
367
  # - Connect to MongoDB Atlas
 
368
  # - ML models load lazily on first use
369
 
370
  # Shutdown:
@@ -382,7 +372,31 @@ if __name__ == "__main__":
382
  # print("=" * 80)
383
 
384
  # # Connect to MongoDB
 
 
 
 
 
 
 
 
 
385
  # await connect_to_mongo()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
 
387
  # print("\nπŸ’‘ ML Models Info:")
388
  # print(" Policy Network: Loads on first chat request (lazy loading)")
@@ -400,7 +414,6 @@ if __name__ == "__main__":
400
  # print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
401
  # print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
402
  # print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
403
- # # print(f"πŸ”‘ Login: POST http://localhost:8000/api/v1/auth/login")
404
  # print("=" * 80 + "\n")
405
 
406
  # yield # Application runs here
@@ -416,221 +429,4 @@ if __name__ == "__main__":
416
  # await close_mongo_connection()
417
 
418
  # print("βœ… Shutdown complete")
419
- # print("=" * 80 + "\n")
420
-
421
- # # ============================================================================
422
- # # CREATE FASTAPI APPLICATION
423
- # # ============================================================================
424
-
425
- # app = FastAPI(
426
- # title="Banking RAG Chatbot API",
427
- # description="""
428
- # πŸ€– AI-powered Banking Assistant with:
429
-
430
- # **Features:**
431
- # - πŸ” JWT Authentication (Sign up, Login, Protected routes)
432
- # - πŸ’¬ RAG (Retrieval-Augmented Generation)
433
- # - 🧠 RL-based Policy Network (BERT)
434
- # - πŸ” Custom E5 Retriever
435
- # - ⚑ Groq LLM with HuggingFace Fallback (Llama 3 models)
436
-
437
- # **Capabilities:**
438
- # - Intelligent document retrieval
439
- # - Context-aware responses
440
- # - Conversation history
441
- # - Real-time chat
442
- # - User authentication & authorization
443
- # - Multi-provider LLM with automatic fallback
444
- # """,
445
- # version="1.0.0",
446
- # docs_url="/docs",
447
- # redoc_url="/redoc",
448
- # lifespan=lifespan
449
- # )
450
-
451
- # # ============================================================================
452
- # # CORS MIDDLEWARE
453
- # # ============================================================================
454
-
455
- # allowed_origins = settings.get_allowed_origins()
456
- # print("\n🌐 CORS Configuration:")
457
- # print(f" Allowed Origins: {allowed_origins}")
458
-
459
- # app.add_middleware(
460
- # CORSMiddleware,
461
- # allow_origins=allowed_origins,
462
- # allow_credentials=True,
463
- # allow_methods=["*"],
464
- # allow_headers=["*"],
465
- # )
466
-
467
- # # ============================================================================
468
- # # INCLUDE API ROUTERS
469
- # # ============================================================================
470
-
471
- # from app.api.v1 import chat, auth
472
-
473
- # # Auth router (public endpoints - register, login)
474
- # app.include_router(
475
- # auth.router,
476
- # prefix="/api/v1/auth",
477
- # tags=["πŸ” Authentication"]
478
- # )
479
-
480
- # # Chat router (protected endpoints - requires JWT token)
481
- # app.include_router(
482
- # chat.router,
483
- # prefix="/api/v1/chat",
484
- # tags=["πŸ’¬ Chat"]
485
- # )
486
-
487
- # # ============================================================================
488
- # # ROOT ENDPOINTS
489
- # # ============================================================================
490
-
491
- # @app.get("/", tags=["πŸ“ Root"])
492
- # async def root():
493
- # """
494
- # Root endpoint - API information and available endpoints
495
- # """
496
- # return {
497
- # "message": "Banking RAG Chatbot API with Authentication",
498
- # "version": "1.0.0",
499
- # "status": "online",
500
- # "authentication": "JWT Bearer Token Required for chat endpoints",
501
- # "llm_provider": "Groq (ChatGroq) with HuggingFace fallback",
502
- # "models": {
503
- # "chat": settings.GROQ_CHAT_MODEL,
504
- # "evaluation": settings.GROQ_EVAL_MODEL
505
- # },
506
- # "documentation": {
507
- # "swagger_ui": "/docs",
508
- # "redoc": "/redoc"
509
- # },
510
- # "endpoints": {
511
- # "auth": {
512
- # "register": "POST /api/v1/auth/register",
513
- # "login": "POST /api/v1/auth/login",
514
- # "me": "GET /api/v1/auth/me (requires token)",
515
- # "logout": "POST /api/v1/auth/logout (requires token)"
516
- # },
517
- # "chat": {
518
- # "send_message": "POST /api/v1/chat/ (requires token)",
519
- # "get_history": "GET /api/v1/chat/history/{conversation_id} (requires token)",
520
- # "list_conversations": "GET /api/v1/chat/conversations (requires token)",
521
- # "delete_conversation": "DELETE /api/v1/chat/conversation/{conversation_id} (requires token)"
522
- # },
523
- # "health": "GET /health"
524
- # }
525
- # }
526
-
527
- # @app.get("/health", tags=["πŸ₯ Health"])
528
- # async def health_check():
529
- # """
530
- # Comprehensive health check endpoint
531
-
532
- # Checks status of:
533
- # - API service
534
- # - MongoDB connection
535
- # - ML models (lazy loaded)
536
- # - Authentication system
537
- # - LLM providers (Groq & HuggingFace)
538
-
539
- # Returns:
540
- # dict: Health status of all components
541
- # """
542
- # from app.db.mongodb import get_database
543
-
544
- # # Check MongoDB
545
- # mongodb_status = "connected" if get_database() is not None else "disconnected"
546
-
547
- # # Check ML models (don't load them, just check readiness)
548
- # ml_models_status = {
549
- # "policy_network": "ready (lazy load)",
550
- # "retriever": "ready (lazy load)",
551
- # "llm": "ready (API-based)"
552
- # }
553
-
554
- # # Check LLM providers
555
- # llm_providers = {
556
- # "groq": {
557
- # "enabled": settings.is_groq_enabled(),
558
- # "api_keys_configured": len(settings.get_groq_api_keys()),
559
- # "chat_model": settings.GROQ_CHAT_MODEL,
560
- # "eval_model": settings.GROQ_EVAL_MODEL
561
- # },
562
- # "huggingface": {
563
- # "enabled": settings.is_hf_enabled(),
564
- # "tokens_configured": len(settings.get_hf_tokens()),
565
- # "chat_model": settings.HF_CHAT_MODEL,
566
- # "eval_model": settings.HF_EVAL_MODEL
567
- # }
568
- # }
569
-
570
- # # Check authentication
571
- # auth_status = {
572
- # "jwt_enabled": bool(settings.SECRET_KEY and settings.SECRET_KEY != "your-secret-key-change-in-production"),
573
- # "algorithm": settings.ALGORITHM,
574
- # "token_expiry_minutes": settings.ACCESS_TOKEN_EXPIRE_MINUTES
575
- # }
576
-
577
- # # Overall health
578
- # is_healthy = (
579
- # mongodb_status == "connected" and
580
- # auth_status["jwt_enabled"] and
581
- # (llm_providers["groq"]["enabled"] or llm_providers["huggingface"]["enabled"])
582
- # )
583
-
584
- # return {
585
- # "status": "healthy" if is_healthy else "degraded",
586
- # "api": "online",
587
- # "mongodb": mongodb_status,
588
- # "authentication": auth_status,
589
- # "llm_providers": llm_providers,
590
- # "ml_models": ml_models_status,
591
- # "environment": settings.ENVIRONMENT,
592
- # "debug_mode": settings.DEBUG
593
- # }
594
-
595
- # # ============================================================================
596
- # # GLOBAL EXCEPTION HANDLER
597
- # # ============================================================================
598
-
599
- # @app.exception_handler(Exception)
600
- # async def global_exception_handler(request: Request, exc: Exception):
601
- # """
602
- # Global exception handler for unhandled errors
603
- # """
604
- # print(f"\n❌ Unhandled Exception:")
605
- # print(f" Path: {request.url.path}")
606
- # print(f" Error: {str(exc)}")
607
-
608
- # if settings.DEBUG:
609
- # import traceback
610
- # traceback.print_exc()
611
-
612
- # return JSONResponse(
613
- # status_code=500,
614
- # content={
615
- # "error": "Internal Server Error",
616
- # "detail": str(exc) if settings.DEBUG else "An unexpected error occurred",
617
- # "path": str(request.url.path)
618
- # }
619
- # )
620
-
621
- # # ============================================================================
622
- # # MAIN ENTRY POINT (for direct execution)
623
- # # ============================================================================
624
-
625
- # if __name__ == "__main__":
626
- # import uvicorn
627
-
628
- # print("\nπŸš€ Starting server directly...")
629
- # print(" Note: For production, use: uvicorn app.main:app --host 0.0.0.0 --port 8000")
630
-
631
- # uvicorn.run(
632
- # "app.main:app",
633
- # host="0.0.0.0",
634
- # port=8000,
635
- # reload=settings.DEBUG # Auto-reload only in debug mode
636
- # )
 
25
  # LIFESPAN MANAGER (Startup & Shutdown)
26
  # ============================================================================
27
 
28
+ from contextlib import asynccontextmanager
29
+ import asyncio
30
+
31
  @asynccontextmanager
32
  async def lifespan(app: FastAPI):
33
  """
34
  Manage application lifespan events.
35
+
36
  Startup:
37
  - Connect to MongoDB Atlas
38
+ - Create indexes for conversations after DB ready (retry logic)
39
+ - ML models lazy loaded
 
 
 
 
40
  """
 
 
 
41
  print("\n" + "=" * 80)
42
  print("πŸš€ STARTING BANKING RAG CHATBOT API")
43
  print("=" * 80)
44
  print(f"Environment: {settings.ENVIRONMENT}")
45
  print(f"Debug Mode: {settings.DEBUG}")
46
  print("=" * 80)
47
+
48
+ # STEP 1 β€” Connect to MongoDB
49
+ print("\nπŸ”Œ Connecting to MongoDB Atlas...")
50
  await connect_to_mongo()
51
+
52
+ # STEP 2 β€” Retry index creation until DB is ready
53
+ from app.db.repositories.conversation_repository import conversation_repository
54
+
55
+ for attempt in range(5):
56
+ try:
57
+ await conversation_repository.create_indexes()
58
+ print("βœ… MongoDB indexes created successfully!")
59
+ break
60
+ except Exception as e:
61
+ print(f"⚠️ Index creation failed (Attempt {attempt + 1}/5): {e}")
62
+ await asyncio.sleep(2)
63
+ else:
64
+ print("❌ Could not create MongoDB indexes after multiple retries")
65
+
66
  print("\nπŸ’‘ ML Models Info:")
67
+ print(" Policy Network: Loads on first chat request (lazy load)")
68
+ print(" Retriever Model: Loads on first retrieval (lazy load)")
69
  print(" LLM: Groq (ChatGroq) with HuggingFace fallback")
70
  print("\nπŸ€– LLM Configuration:")
71
  print(f" Chat Model: {settings.GROQ_CHAT_MODEL} (Llama 3 8B)")
 
73
  print(f" Groq API Keys: {len(settings.get_groq_api_keys())} configured")
74
  print(f" HuggingFace Tokens: {len(settings.get_hf_tokens())} configured")
75
  print(f" Fallback: Groq β†’ HuggingFace")
76
+
77
  print("\nβœ… Backend startup complete!")
78
  print("=" * 80)
79
  print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
80
  print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
81
  print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
82
  print("=" * 80 + "\n")
83
+
84
+ yield
85
+
 
86
  # SHUTDOWN
 
87
  print("\n" + "=" * 80)
88
  print("πŸ›‘ SHUTTING DOWN API")
89
  print("=" * 80)
 
 
90
  await close_mongo_connection()
 
91
  print("βœ… Shutdown complete")
92
  print("=" * 80 + "\n")
93
 
94
+
95
  # ============================================================================
96
  # CREATE FASTAPI APPLICATION
97
  # ============================================================================
 
333
  )
334
 
335
 
336
+ # ============================================================================================================================
337
+ # OLD CODE - KEEP FOR REFERENCE
338
+ # ============================================================================================================================
339
+
340
 
 
341
 
 
 
 
 
 
 
 
342
 
 
 
 
 
343
 
 
 
344
 
345
+
346
+ # ============================================================================
347
+ # LIFESPAN MANAGER (Startup & Shutdown)
348
+ # ============================================================================
349
 
350
  # @asynccontextmanager
351
  # async def lifespan(app: FastAPI):
 
354
 
355
  # Startup:
356
  # - Connect to MongoDB Atlas
357
+ # - Create indexes for conversations
358
  # - ML models load lazily on first use
359
 
360
  # Shutdown:
 
372
  # print("=" * 80)
373
 
374
  # # Connect to MongoDB
375
+ # # await connect_to_mongo()
376
+
377
+ # # # Create indexes for conversations (async)
378
+ # # try:
379
+ # # from app.db.repositories.conversation_repository import conversation_repository
380
+ # # await conversation_repository.create_indexes()
381
+ # # except Exception as e:
382
+ # # print(f"⚠️ Failed to create conversation indexes: {e}")
383
+ # # Connect to MongoDB first
384
  # await connect_to_mongo()
385
+
386
+ # # Create indexes after connection success
387
+ # from app.db.repositories.conversation_repository import conversation_repository
388
+
389
+ # for attempt in range(5):
390
+ # try:
391
+ # await conversation_repository.create_indexes()
392
+ # print("βœ… Conversation indexes created successfully")
393
+ # break
394
+ # except Exception as e:
395
+ # print(f"⚠️ Index creation failed (Attempt {attempt + 1}/5): {e}")
396
+ # await asyncio.sleep(2)
397
+ # else:
398
+ # print("❌ Failed to create indexes after retries")
399
+
400
 
401
  # print("\nπŸ’‘ ML Models Info:")
402
  # print(" Policy Network: Loads on first chat request (lazy loading)")
 
414
  # print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
415
  # print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
416
  # print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
 
417
  # print("=" * 80 + "\n")
418
 
419
  # yield # Application runs here
 
429
  # await close_mongo_connection()
430
 
431
  # print("βœ… Shutdown complete")
432
+ # print("=" * 80 + "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/main_backup.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # """
2
+ # FastAPI Main Application Entry Point
3
+
4
+ # Banking RAG Chatbot API with JWT Authentication
5
+
6
+ # This file:
7
+ # 1. Creates the FastAPI app
8
+ # 2. Configures CORS middleware
9
+ # 3. Connects to MongoDB on startup/shutdown
10
+ # 4. Includes API routers (auth + chat)
11
+ # 5. Provides health check endpoints
12
+ # """
13
+
14
+ # from fastapi import FastAPI, Request
15
+ # from fastapi.middleware.cors import CORSMiddleware
16
+ # from fastapi.responses import JSONResponse
17
+ # from contextlib import asynccontextmanager
18
+
19
+ # from app.config import settings
20
+ # from app.db.mongodb import connect_to_mongo, close_mongo_connection
21
+
22
+ # # ============================================================================
23
+ # # LIFESPAN MANAGER (Startup & Shutdown)
24
+ # # ============================================================================
25
+
26
+ # @asynccontextmanager
27
+ # async def lifespan(app: FastAPI):
28
+ # """
29
+ # Manage application lifespan events.
30
+
31
+ # Startup:
32
+ # - Connect to MongoDB Atlas
33
+ # - ML models load lazily on first use
34
+
35
+ # Shutdown:
36
+ # - Close MongoDB connection
37
+ # - Cleanup resources
38
+ # """
39
+ # # ========================================================================
40
+ # # STARTUP
41
+ # # ========================================================================
42
+ # print("\n" + "=" * 80)
43
+ # print("πŸš€ STARTING BANKING RAG CHATBOT API")
44
+ # print("=" * 80)
45
+ # print(f"Environment: {settings.ENVIRONMENT}")
46
+ # print(f"Debug Mode: {settings.DEBUG}")
47
+ # print("=" * 80)
48
+
49
+ # # Connect to MongoDB
50
+ # await connect_to_mongo()
51
+
52
+ # print("\nπŸ’‘ ML Models Info:")
53
+ # print(" Policy Network: Loads on first chat request (lazy loading)")
54
+ # print(" Retriever Model: Loads on first retrieval (lazy loading)")
55
+ # print(" LLM: Groq (ChatGroq) with HuggingFace fallback")
56
+ # print("\nπŸ€– LLM Configuration:")
57
+ # print(f" Chat Model: {settings.GROQ_CHAT_MODEL} (Llama 3 8B)")
58
+ # print(f" Eval Model: {settings.GROQ_EVAL_MODEL} (Llama 3 70B)")
59
+ # print(f" Groq API Keys: {len(settings.get_groq_api_keys())} configured")
60
+ # print(f" HuggingFace Tokens: {len(settings.get_hf_tokens())} configured")
61
+ # print(f" Fallback: Groq β†’ HuggingFace")
62
+
63
+ # print("\nβœ… Backend startup complete!")
64
+ # print("=" * 80)
65
+ # print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
66
+ # print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
67
+ # print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
68
+ # # print(f"πŸ”‘ Login: POST http://localhost:8000/api/v1/auth/login")
69
+ # print("=" * 80 + "\n")
70
+
71
+ # yield # Application runs here
72
+
73
+ # # ========================================================================
74
+ # # SHUTDOWN
75
+ # # ========================================================================
76
+ # print("\n" + "=" * 80)
77
+ # print("πŸ›‘ SHUTTING DOWN API")
78
+ # print("=" * 80)
79
+
80
+ # # Close MongoDB connection
81
+ # await close_mongo_connection()
82
+
83
+ # print("βœ… Shutdown complete")
84
+ # print("=" * 80 + "\n")
85
+
86
+ # # ============================================================================
87
+ # # CREATE FASTAPI APPLICATION
88
+ # # ============================================================================
89
+
90
+ # app = FastAPI(
91
+ # title="Banking RAG Chatbot API",
92
+ # description="""
93
+ # πŸ€– AI-powered Banking Assistant with:
94
+
95
+ # **Features:**
96
+ # - πŸ” JWT Authentication (Sign up, Login, Protected routes)
97
+ # - πŸ’¬ RAG (Retrieval-Augmented Generation)
98
+ # - 🧠 RL-based Policy Network (BERT)
99
+ # - πŸ” Custom E5 Retriever
100
+ # - ⚑ Groq LLM with HuggingFace Fallback (Llama 3 models)
101
+
102
+ # **Capabilities:**
103
+ # - Intelligent document retrieval
104
+ # - Context-aware responses
105
+ # - Conversation history
106
+ # - Real-time chat
107
+ # - User authentication & authorization
108
+ # - Multi-provider LLM with automatic fallback
109
+ # """,
110
+ # version="1.0.0",
111
+ # docs_url="/docs",
112
+ # redoc_url="/redoc",
113
+ # lifespan=lifespan
114
+ # )
115
+
116
+ # # ============================================================================
117
+ # # CORS MIDDLEWARE
118
+ # # ============================================================================
119
+
120
+ # allowed_origins = settings.get_allowed_origins()
121
+ # print("\n🌐 CORS Configuration:")
122
+ # print(f" Allowed Origins: {allowed_origins}")
123
+
124
+ # app.add_middleware(
125
+ # CORSMiddleware,
126
+ # allow_origins=allowed_origins,
127
+ # allow_credentials=True,
128
+ # allow_methods=["*"],
129
+ # allow_headers=["*"],
130
+ # )
131
+
132
+ # # ============================================================================
133
+ # # INCLUDE API ROUTERS
134
+ # # ============================================================================
135
+
136
+ # from app.api.v1 import chat, auth
137
+
138
+ # # Auth router (public endpoints - register, login)
139
+ # app.include_router(
140
+ # auth.router,
141
+ # prefix="/api/v1/auth",
142
+ # tags=["πŸ” Authentication"]
143
+ # )
144
+
145
+ # # Chat router (protected endpoints - requires JWT token)
146
+ # app.include_router(
147
+ # chat.router,
148
+ # prefix="/api/v1/chat",
149
+ # tags=["πŸ’¬ Chat"]
150
+ # )
151
+
152
+ # # ============================================================================
153
+ # # ROOT ENDPOINTS
154
+ # # ============================================================================
155
+
156
+ # @app.get("/", tags=["πŸ“ Root"])
157
+ # async def root():
158
+ # """
159
+ # Root endpoint - API information and available endpoints
160
+ # """
161
+ # return {
162
+ # "message": "Banking RAG Chatbot API with Authentication",
163
+ # "version": "1.0.0",
164
+ # "status": "online",
165
+ # "authentication": "JWT Bearer Token Required for chat endpoints",
166
+ # "llm_provider": "Groq (ChatGroq) with HuggingFace fallback",
167
+ # "models": {
168
+ # "chat": settings.GROQ_CHAT_MODEL,
169
+ # "evaluation": settings.GROQ_EVAL_MODEL
170
+ # },
171
+ # "documentation": {
172
+ # "swagger_ui": "/docs",
173
+ # "redoc": "/redoc"
174
+ # },
175
+ # "endpoints": {
176
+ # "auth": {
177
+ # "register": "POST /api/v1/auth/register",
178
+ # "login": "POST /api/v1/auth/login",
179
+ # "me": "GET /api/v1/auth/me (requires token)",
180
+ # "logout": "POST /api/v1/auth/logout (requires token)"
181
+ # },
182
+ # "chat": {
183
+ # "send_message": "POST /api/v1/chat/ (requires token)",
184
+ # "get_history": "GET /api/v1/chat/history/{conversation_id} (requires token)",
185
+ # "list_conversations": "GET /api/v1/chat/conversations (requires token)",
186
+ # "delete_conversation": "DELETE /api/v1/chat/conversation/{conversation_id} (requires token)"
187
+ # },
188
+ # "health": "GET /health"
189
+ # }
190
+ # }
191
+
192
+ # @app.get("/health", tags=["πŸ₯ Health"])
193
+ # async def health_check():
194
+ # """
195
+ # Comprehensive health check endpoint
196
+
197
+ # Checks status of:
198
+ # - API service
199
+ # - MongoDB connection
200
+ # - ML models (lazy loaded)
201
+ # - Authentication system
202
+ # - LLM providers (Groq & HuggingFace)
203
+
204
+ # Returns:
205
+ # dict: Health status of all components
206
+ # """
207
+ # from app.db.mongodb import get_database
208
+
209
+ # # Check MongoDB
210
+ # mongodb_status = "connected" if get_database() is not None else "disconnected"
211
+
212
+ # # Check ML models (don't load them, just check readiness)
213
+ # ml_models_status = {
214
+ # "policy_network": "ready (lazy load)",
215
+ # "retriever": "ready (lazy load)",
216
+ # "llm": "ready (API-based)"
217
+ # }
218
+
219
+ # # Check LLM providers
220
+ # llm_providers = {
221
+ # "groq": {
222
+ # "enabled": settings.is_groq_enabled(),
223
+ # "api_keys_configured": len(settings.get_groq_api_keys()),
224
+ # "chat_model": settings.GROQ_CHAT_MODEL,
225
+ # "eval_model": settings.GROQ_EVAL_MODEL
226
+ # },
227
+ # "huggingface": {
228
+ # "enabled": settings.is_hf_enabled(),
229
+ # "tokens_configured": len(settings.get_hf_tokens()),
230
+ # "chat_model": settings.HF_CHAT_MODEL,
231
+ # "eval_model": settings.HF_EVAL_MODEL
232
+ # }
233
+ # }
234
+
235
+ # # Check authentication
236
+ # auth_status = {
237
+ # "jwt_enabled": bool(settings.SECRET_KEY and settings.SECRET_KEY != "your-secret-key-change-in-production"),
238
+ # "algorithm": settings.ALGORITHM,
239
+ # "token_expiry_minutes": settings.ACCESS_TOKEN_EXPIRE_MINUTES
240
+ # }
241
+
242
+ # # Overall health
243
+ # is_healthy = (
244
+ # mongodb_status == "connected" and
245
+ # auth_status["jwt_enabled"] and
246
+ # (llm_providers["groq"]["enabled"] or llm_providers["huggingface"]["enabled"])
247
+ # )
248
+
249
+ # return {
250
+ # "status": "healthy" if is_healthy else "degraded",
251
+ # "api": "online",
252
+ # "mongodb": mongodb_status,
253
+ # "authentication": auth_status,
254
+ # "llm_providers": llm_providers,
255
+ # "ml_models": ml_models_status,
256
+ # "environment": settings.ENVIRONMENT,
257
+ # "debug_mode": settings.DEBUG
258
+ # }
259
+
260
+ # # ============================================================================
261
+ # # GLOBAL EXCEPTION HANDLER
262
+ # # ============================================================================
263
+
264
+ # @app.exception_handler(Exception)
265
+ # async def global_exception_handler(request: Request, exc: Exception):
266
+ # """
267
+ # Global exception handler for unhandled errors
268
+ # """
269
+ # print(f"\n❌ Unhandled Exception:")
270
+ # print(f" Path: {request.url.path}")
271
+ # print(f" Error: {str(exc)}")
272
+
273
+ # if settings.DEBUG:
274
+ # import traceback
275
+ # traceback.print_exc()
276
+
277
+ # return JSONResponse(
278
+ # status_code=500,
279
+ # content={
280
+ # "error": "Internal Server Error",
281
+ # "detail": str(exc) if settings.DEBUG else "An unexpected error occurred",
282
+ # "path": str(request.url.path)
283
+ # }
284
+ # )
285
+
286
+ # # ============================================================================
287
+ # # MAIN ENTRY POINT (for direct execution)
288
+ # # ============================================================================
289
+
290
+ # if __name__ == "__main__":
291
+ # import uvicorn
292
+
293
+ # print("\nπŸš€ Starting server directly...")
294
+ # print(" Note: For production, use: uvicorn app.main:app --host 0.0.0.0 --port 8000")
295
+
296
+ # uvicorn.run(
297
+ # "app.main:app",
298
+ # host="0.0.0.0",
299
+ # port=8000,
300
+ # reload=settings.DEBUG # Auto-reload only in debug mode
301
+ # )