main.py 4.75 KB
import json
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response

from app.api.v1.router import api_router
from app.config.loader import ConfigLoader
from app.infrastructure.database import engine
from app.infrastructure.response_format import format_response_datetimes
from app.infrastructure.schema_patch import ensure_runtime_schema
from app.infrastructure.database import Base

# Register all model tables with Base.metadata so create_all works
from app.model.agent import Agent, AgentPosition, AgentSkill  # noqa: F401
from app.model.position_tag import PositionTag, OfficialTab  # noqa: F401
from app.model.skill import Skill  # noqa: F401
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.service.agent_hub import AgentHub
from app.service.active_session_service import ActiveSessionService
from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService

agent_hub_instance = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    global agent_hub_instance

    Base.metadata.create_all(bind=engine)
    ensure_runtime_schema(engine)

    config_loader = ConfigLoader()
    settings = config_loader.load_settings()
    session_service = ActiveSessionService()

    use_console_im = os.getenv("USE_CONSOLE_IM")
    if use_console_im is None:
        use_console = settings.im.use_console
    else:
        use_console = use_console_im.lower() == "true"

    if use_console:
        im_service = ConsoleIMService()
    else:
        im_service = IMService(
            base_url=os.getenv("IM_BASE_URL", settings.im.base_url),
            api_key=os.getenv("IM_API_KEY", settings.im.api_key),
        )

    agent_hub_instance = AgentHub(
        config_loader=config_loader,
        session_service=session_service,
        im_service=im_service,
    )

    yield

    if agent_hub_instance:
        await agent_hub_instance.close()


app = FastAPI(title="Agent Admin API", version="1.0.0", lifespan=lifespan)


@app.exception_handler(HTTPException)
async def http_exception_handler(_: Request, exc: HTTPException):
    message = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
    return JSONResponse(
        status_code=exc.status_code,
        content=error_response_payload(exc.status_code, message),
    )


@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(_: Request, exc: RequestValidationError):
    first_error = exc.errors()[0] if exc.errors() else {}
    loc = ".".join(str(part) for part in first_error.get("loc", []) if part != "body")
    msg = first_error.get("msg", "请求参数不合法")
    detail = f"参数校验失败:{loc} {msg}".strip()
    return JSONResponse(
        status_code=400,
        content=error_response_payload(400, detail),
    )


@app.exception_handler(Exception)
async def unhandled_exception_handler(_: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content=error_response_payload(500, str(exc) or "服务器内部错误"),
    )


@app.middleware("http")
async def wrap_json_response(request: Request, call_next):
    response = await call_next(request)

    if request.url.path in {"/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"}:
        return response

    content_type = response.headers.get("content-type", "")
    if "application/json" not in content_type.lower():
        return response

    if response.status_code >= 400:
        return response

    body = b""
    async for chunk in response.body_iterator:
        body += chunk

    if not body:
        return Response(
            content=body,
            status_code=response.status_code,
            headers=dict(response.headers),
            media_type=response.media_type,
        )

    payload = json.loads(body)
    if is_wrapped_payload(payload):
        wrapped = format_response_datetimes(payload)
    else:
        wrapped = format_response_datetimes(success_response_payload(response.status_code, payload))

    headers = {
        key: value
        for key, value in response.headers.items()
        if key.lower() != "content-length"
    }
    return JSONResponse(
        status_code=response.status_code,
        content=wrapped,
        headers=headers,
    )


app.include_router(api_router)


@app.get("/health")
def health_check():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    runtime_settings = ConfigLoader().load_settings()
    uvicorn.run(
        "app.main:app",
        host=runtime_settings.server.host,
        port=runtime_settings.server.port,
        reload=runtime_settings.server.reload,
    )