rag_qavanin_api/main.py
2025-11-29 20:11:27 +00:00

59 lines
1.6 KiB
Python
Executable File

from fastapi import FastAPI
from routers.rag_base import router as rag_base
from contextlib import asynccontextmanager
from fastapi.middleware.cors import CORSMiddleware
# --- Lifespan manager ---
@asynccontextmanager
async def lifespan(app: FastAPI):
# 🚀 Startup
print("🚀 Starting up RAG system...")
# ایجاد OSS client و ذخیره در app.state
# --- نکته مهم: اگر elastic_client هم می‌خوای توی startup درست کنی، اینجا اضافه کن ---
# elastic_client = get_elastic_client()
# app.state.elastic_client = elastic_client
yield # برنامه در این حالت اجرا می‌شود
# 🛑 Shutdown
print("🛑 Shutting down RAG system...")
# بستن اتصال‌های باز
client = getattr(app.state, "elastic_client", None)
if client is not None:
await client.close()
# --- ساخت اپلیکیشن ---
def create_app() -> FastAPI:
app = FastAPI(
title="qachat2 Backend",
version="0.1.0",
lifespan=lifespan, # ✅ اینجا lifespan رو متصل می‌کنیم
)
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def simple():
return "ai rag chat qanon OK"
@app.get("/ping")
async def ping():
return "ai rag chat qanon OK"
app.include_router(rag_base, prefix="")
return app
# ✅ نمونه‌سازی نهایی
app = create_app()