Files
ai-safety-platform/app/main.py
T
baozaotumao2025 14722be770 first commit
2026-07-18 21:00:26 +08:00

60 lines
2.1 KiB
Python

from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.router import api_router
from app.core.config import get_settings
from app.core.handlers import register_exception_handlers
from app.core.logging import configure_logging
from app.middleware.request_id import RequestIdMiddleware
from app.middleware.authentication import AuthenticationMiddleware
OPENAPI_TAGS = [
{"name": "system", "description": "服务存活与运行环境信息。"},
{"name": "authentication", "description": "本地用户登录与访问令牌。"},
{"name": "providers", "description": "模型提供商配置、连接检查和上游模型发现。"},
{"name": "runs", "description": "安全测试的执行、状态与逐样例结果。"},
{"name": "reports", "description": "测试运行的实时派生聚合报告。"},
]
@asynccontextmanager
async def lifespan(app: FastAPI):
configure_logging()
yield
def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(
title=settings.app_name,
version="6.0.0",
description=(
"AI模型内部安全测试平台。提供模型认证检查、模型发现、"
"能力探测、测试执行、裁判和报告 API。所有时间敏感或可能"
"触发模型调用的操作均在接口说明中明确标注;业务错误统一使用 `error` 对象返回。"
),
openapi_tags=OPENAPI_TAGS,
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
debug=settings.app_debug,
lifespan=lifespan,
)
app.add_middleware(AuthenticationMiddleware)
app.add_middleware(RequestIdMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=settings.cors_allow_credentials,
allow_methods=settings.cors_methods,
allow_headers=settings.cors_headers,
)
register_exception_handlers(app)
app.include_router(api_router, prefix=settings.app_api_prefix)
return app
app = create_app()