main.py
8.57 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import json
import os
from contextlib import asynccontextmanager
import logging
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import FileResponse, JSONResponse, Response
logger = logging.getLogger(__name__)
from app.api.v1.router import api_router
from app.config.loader import ConfigLoader
from app.infrastructure.database import engine, SessionLocal
from app.infrastructure.logging import configure_logging
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.agent_group import QrcodeChannel, WeComEmployeeQrcode # noqa: F401
from app.model.analytics import ( # noqa: F401
AnalyticsEvent,
AnalyticsStatistic,
ConversationLog,
GroupJoinEvent,
PageView,
ScanEvent,
)
from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep # noqa: F401
from app.model.official_site_agent_display import OfficialSiteAgentDisplay # noqa: F401
from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser # noqa: F401
from app.model.skill import Skill # noqa: F401
from app.model.wecom_sync import ( # noqa: F401
WeComBot,
WeComCustomerGroup,
WeComGroupCreateRequest,
WeComJobConfig,
WeComMessage,
WeComSyncCheckpoint,
)
from app.customer_info.model import CustomerGroupPhone # noqa: F401
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.agent_core.agent_hub import AgentHub
from app.agent_core.active_session_service import ActiveSessionService
from app.agent_core.console_im_service import ConsoleIMService
from app.agent_core.im_service import IMService
agent_hub_instance = None
message_gate_instance = None
configure_logging("backend", logging.INFO)
runtime_settings = ConfigLoader().load_settings()
base_path = (runtime_settings.server.base_path or "").rstrip("/")
docs_url = f"{base_path}/docs" if base_path else "/docs"
redoc_url = f"{base_path}/redoc" if base_path else "/redoc"
openapi_url = f"{base_path}/openapi.json" if base_path else "/openapi.json"
oauth2_redirect_url = f"{base_path}/docs/oauth2-redirect" if base_path else "/docs/oauth2-redirect"
# 运维面板静态产物目录(operation-panel/dist),通过 /panel 由后端托管
PANEL_DIST_DIR = Path(__file__).resolve().parents[1] / "operation-panel" / "dist"
@asynccontextmanager
async def lifespan(app: FastAPI):
global agent_hub_instance, message_gate_instance
Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine)
config_loader = ConfigLoader()
settings = config_loader.load_settings()
db_factory = SessionLocal
# 从数据库加载 Agent 配置
with db_factory() as db:
agents = config_loader.load_agents_from_db(db)
logger.info(
"Agent 配置已从 DB 加载: %d 个, steward=%s",
len(agents),
next((k for k, v in agents.items() if v.is_steward), None),
)
session_service = ActiveSessionService(db_factory=db_factory)
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),
)
app.state.im_service = im_service
agent_hub_instance = AgentHub(
config_loader=config_loader,
session_service=session_service,
im_service=im_service,
preloaded_agents=agents,
db_factory=db_factory,
)
# ── MessageGate 实例化 ──
from app.agent_core.message_gate import MessageGate
from app.hooks.post_reply import PostReplyHook
main_agent_key = next((k for k, v in agents.items() if v.is_steward), "main")
post_reply_hook = PostReplyHook(im_service=im_service)
message_gate_instance = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub_instance,
main_agent_key=main_agent_key,
)
yield
if agent_hub_instance:
await agent_hub_instance.close()
if message_gate_instance:
await message_gate_instance.close()
# db_factory 是 class,不需要 close;短 session 由 with 自动管理
app = FastAPI(
title="Agent Admin API",
version="1.0.0",
lifespan=lifespan,
docs_url=docs_url,
redoc_url=redoc_url,
openapi_url=openapi_url,
swagger_ui_oauth2_redirect_url=oauth2_redirect_url,
)
@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_url, docs_url, oauth2_redirect_url, redoc_url}:
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, prefix=base_path)
@app.get(f"{base_path}/health" if base_path else "/health")
def health_check():
return {"status": "ok"}
def _serve_panel_file(full_path: str) -> FileResponse:
"""提供运维面板静态文件:命中 dist 内真实文件则返回该文件,否则 SPA fallback 到 index.html。"""
dist_root = PANEL_DIST_DIR.resolve()
index_file = dist_root / "index.html"
if not dist_root.is_dir():
raise HTTPException(status_code=404, detail="operation-panel dist 未构建")
full_path = (full_path or "").lstrip("/")
if full_path:
candidate = (dist_root / full_path).resolve()
if candidate.is_file() and candidate.is_relative_to(dist_root):
return FileResponse(candidate)
return FileResponse(index_file)
@app.get(f"{base_path}/panel" if base_path else "/panel", include_in_schema=False)
async def panel_index():
return _serve_panel_file("index.html")
@app.get(f"{base_path}/panel/{{full_path:path}}" if base_path else "/panel/{full_path:path}", include_in_schema=False)
async def panel_spa(full_path: str):
return _serve_panel_file(full_path)
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,
)