55 lines
2.8 KiB
Python
55 lines
2.8 KiB
Python
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.api.controllers.admin import router as admin_router
|
|
from app.api.controllers.agent_runs import router as agent_runs_router
|
|
from app.api.controllers.conversations import router as conversations_router
|
|
from app.api.controllers.health import router as health_router
|
|
from app.api.controllers.knowledge import router as knowledge_router
|
|
from app.api.controllers.public_platform import router as public_platform_router
|
|
from app.api.controllers.risk import router as risk_router
|
|
from app.api.middleware import attach_trace_id
|
|
from app.core.config import get_settings
|
|
from app.core.errors import AgentError
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
settings = get_settings()
|
|
application = FastAPI(title=settings.app_name, version="0.1.0")
|
|
# 接口文档承诺的 X-Trace-ID 此前完全没实现;中间件对成功与错误响应都生效。
|
|
application.middleware("http")(attach_trace_id)
|
|
|
|
@application.exception_handler(AgentError)
|
|
async def agent_error_handler(request: Request, exc: AgentError) -> JSONResponse:
|
|
context = getattr(request.state, "request_context", None)
|
|
# 认证失败时请求上下文尚未建立(`build_request_context` 不会写 request_context),
|
|
# 按文档 §3.4 优先复用请求头里客户端带来的 `X-Trace-ID`;都没有就是空字符串,
|
|
# 绝不凭空生成 id——会让排障时把两个请求认成同一个。
|
|
trace_id = (getattr(context, "trace_id", None)
|
|
or getattr(request.state, "trace_id", None)
|
|
or request.headers.get("X-Trace-ID") or "")
|
|
# retryable 按文档 §3.6 逐码标注,不再简单按 5xx 推导
|
|
# (例如 RESOURCE_VERSION_CONFLICT 是 409 但文档标注可重试)。
|
|
headers: dict[str, str] = {}
|
|
retry_after = getattr(exc, "retry_after_seconds", None)
|
|
if isinstance(retry_after, int):
|
|
# 文档 §3.6 把 RATE_LIMITED 标注为可重试:只给 retryable=true 而不给
|
|
# Retry-After,客户端只能自己猜退避时长(或立刻重试再被拒)。
|
|
headers["Retry-After"] = str(retry_after)
|
|
return JSONResponse(status_code=exc.status_code, content={
|
|
"error": {"code": exc.code, "message": exc.message,
|
|
"retryable": exc.is_retryable, "field_errors": []},
|
|
"meta": {"trace_id": trace_id},
|
|
}, headers=headers or None)
|
|
application.include_router(agent_runs_router)
|
|
application.include_router(conversations_router)
|
|
application.include_router(public_platform_router)
|
|
application.include_router(risk_router)
|
|
application.include_router(knowledge_router)
|
|
application.include_router(health_router)
|
|
application.include_router(admin_router)
|
|
return application
|
|
|
|
|
|
app = create_app()
|