|
|
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}...") |
|
|
|
|
|
|
|
|
app = FastAPI( |
|
|
title=settings.APP_NAME, |
|
|
description=f"An API for interacting with {settings.APP_NAME}.", |
|
|
version=settings.APP_VERSION, |
|
|
lifespan=lifespan |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
@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=["*"], |
|
|
) |
|
|
|
|
|
|
|
|
app.include_router(chats.router, prefix="/api/chats", tags=["Chats & Messages"]) |
|
|
app.include_router(memory.router, prefix="/api/memories", tags=["Memory Management"]) |
|
|
|
|
|
|
|
|
@app.get("/", tags=["Health"]) |
|
|
async def read_root(): |
|
|
return {"status": "ok", "message": "Welcome to Makhfi AI API!"} |