main.py 4.17 KB
import json
import os
from contextlib import asynccontextmanager
from pathlib import Path

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 SessionLocal, engine
from app.model.session import Base
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.service.agent_hub import AgentHub
from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService
from app.service.session_service import SessionService
from app.service.skill_scanner import update_skills_json

agent_hub_instance = None


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

    Base.metadata.create_all(bind=engine)

    skills_dir = Path(__file__).parent.parent / "skills"
    config_dir = Path(__file__).parent.parent / "config"
    update_skills_json(skills_dir, config_dir)

    config_loader = ConfigLoader()
    db = SessionLocal()
    session_service = SessionService(db)

    if os.getenv("USE_CONSOLE_IM", "true").lower() == "true":
        im_service = ConsoleIMService()
    else:
        im_service = IMService(
            base_url=os.getenv("IM_BASE_URL", "http://localhost:8080"),
            api_key=os.getenv("IM_API_KEY", "your-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 = payload
    else:
        wrapped = 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

    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)