mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-24 01:49:19 +08:00
56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
"""Agent FastAPI 入口。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from api.response import fail
|
|
from api.routers import chat, memories, sessions
|
|
from config.settings import get_settings
|
|
from infrastructure.persistence.mongo.client import close_mongo, ensure_indexes, get_db
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI):
|
|
settings = get_settings()
|
|
db = await get_db(settings)
|
|
await ensure_indexes(db)
|
|
yield
|
|
await close_mongo()
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
settings = get_settings()
|
|
app = FastAPI(title=settings.app_name, lifespan=lifespan)
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.cors_origin_list,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
app.include_router(sessions.router, prefix="/api/agent")
|
|
app.include_router(chat.router, prefix="/api/agent")
|
|
app.include_router(memories.router, prefix="/api/agent")
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(_request: Request, exc: HTTPException):
|
|
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=fail(detail, code=exc.status_code),
|
|
)
|
|
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"ok": True, "service": settings.app_name}
|
|
|
|
return app
|
|
|
|
|
|
app = create_app()
|