File size: 1,737 Bytes
d47e86b 9577d95 d47e86b 9577d95 ce2db9f 9577d95 d47e86b 9577d95 65127e8 9577d95 4febd8d | 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 | from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from api.routers import chats
from api.routers import memory
from db.session import create_db_and_tables
from core.config import get_settings
import time
settings = get_settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
print(f"INFO: Starting up {settings.APP_NAME} v{settings.APP_VERSION}...")
await create_db_and_tables()
print("INFO: Database tables checked/created.")
yield
print(f"INFO: Shutting down {settings.APP_NAME}...")
# FastAPI app instance
app = FastAPI(
title=settings.APP_NAME,
description=f"An API for interacting with {settings.APP_NAME}.",
version=settings.APP_VERSION,
lifespan=lifespan
)
# --- Middlewares ---
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
print(f"INFO: Request {request.method} {request.url.path} processed in {process_time:.4f} sec")
return response
app.add_middleware(
CORSMiddleware,
allow_origins=[settings.FRONTEND_URL, "http://127.0.0.1:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Routers ---
app.include_router(chats.router, prefix="/api/chats", tags=["Chats & Messages"])
app.include_router(memory.router, prefix="/api/memories", tags=["Memory Management"])
# --- Root Endpoint ---
@app.get("/", tags=["Health"])
async def read_root():
return {"status": "ok", "message": "Welcome to Makhfi AI API!"} |