main.py
4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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,
)