rag-chatbot / app /main.py
Abeshith's picture
RAG Chatbot with LangChain, FastAPI, and service layer architecture
64d7fdf
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from app.api.routes import chat, documents, health
from app.api.middleware.cors import setup_cors
from app.api.middleware.error_handler import error_handler_middleware
from app.api.middleware.logging import logging_middleware
from app.db.redis_client import RedisClient
from app.db.mongodb import MongoDB
from app.db.vector_store import vector_store
from app.utils.logger import logger
from app.config import config
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting RAG Chatbot application...")
redis_client = RedisClient()
await redis_client.connect()
logger.info("Redis connected")
mongodb = MongoDB()
try:
await mongodb.connect()
logger.info("MongoDB connected")
except Exception as e:
logger.warning(f"MongoDB connection failed: {str(e)}")
try:
vector_store.create_collection()
logger.info("Qdrant collection ready")
except Exception as e:
logger.warning(f"Qdrant setup warning: {str(e)}")
yield
await redis_client.disconnect()
logger.info("Redis disconnected")
try:
await mongodb.disconnect()
logger.info("MongoDB disconnected")
except:
pass
logger.info("Application shutdown complete")
app = FastAPI(
title=config["app"]["app"]["name"],
version=config["app"]["app"]["version"],
description="Enterprise RAG Chatbot with LangChain and LangGraph",
lifespan=lifespan
)
setup_cors(app)
app.middleware("http")(error_handler_middleware)
app.middleware("http")(logging_middleware)
app.include_router(chat.router)
app.include_router(documents.router)
app.include_router(health.router)
app.mount("/static", StaticFiles(directory="frontend/static"), name="static")
templates = Jinja2Templates(directory="frontend/templates")
@app.get("/")
async def root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host=config["app"]["server"]["host"],
port=config["app"]["server"]["port"],
reload=config["app"]["app"]["debug"]
)