app.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. """FastAPI application — category tree API on port 8080."""
  2. from __future__ import annotations
  3. from contextlib import asynccontextmanager
  4. from pathlib import Path
  5. from typing import Literal
  6. from fastapi import FastAPI, HTTPException, Query, Request, status
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from fastapi.staticfiles import StaticFiles
  9. from pydantic import BaseModel, Field
  10. from sqlalchemy import text
  11. from starlette.exceptions import HTTPException as StarletteHTTPException
  12. from api.auth_middleware import AuthenticationMiddleware
  13. from api.routers.auth import router as auth_router
  14. from api.routers.business_harness import router as business_harness_router
  15. from api.routers.pipeline import router as pipeline_router
  16. from api.schemas.demand_feedback import CreateDemandFeedbackBody
  17. from api.services.agent_catalog import (
  18. get_agent_detail,
  19. update_agent_document_injection,
  20. )
  21. from api.services.auth import ensure_bootstrap_admin
  22. from api.services.category_tree import build_category_tree
  23. from api.services.demand_belong_category import list_demand_belong_categories
  24. from api.services.demand_grade import list_demand_grades
  25. from api.services.demand_grade_videos import list_videos_for_demand_grade
  26. from api.services.demand_feedback import (
  27. FeedbackRequestConflictError,
  28. FeedbackTargetConflictError,
  29. FeedbackTargetNotFoundError,
  30. create_demand_feedback,
  31. list_demand_feedback,
  32. )
  33. from api.services.demand_videos import list_videos_for_demand_belong
  34. from api.services.oss_logs import list_agent_oss_logs, list_demand_belong_oss_logs
  35. from api.services.scheduler import (
  36. get_scheduler_job_run,
  37. list_triggerable_jobs,
  38. run_scheduler_job,
  39. run_supply_pipeline,
  40. scheduler_status as get_persistent_scheduler_status,
  41. )
  42. from api.services.video_discovery import (
  43. get_video_discovery_demand,
  44. list_video_discovery_demands,
  45. )
  46. from api.services.video_discovery_records import (
  47. get_video_discovery_run,
  48. list_video_discovery_candidates,
  49. list_video_discovery_runs,
  50. list_video_discovery_searches,
  51. )
  52. from supply_infra.config import get_infra_settings
  53. from supply_infra.db import dispose_engine, get_session, init_db
  54. from supply_infra.pipeline.health import pipeline_health_snapshot
  55. class SPAStaticFiles(StaticFiles):
  56. """Serve index.html for browser routes handled by Vue Router."""
  57. async def get_response(self, path: str, scope):
  58. try:
  59. return await super().get_response(path, scope)
  60. except StarletteHTTPException as exc:
  61. is_backend_path = (
  62. path == "api"
  63. or path.startswith("api/")
  64. or path == "health"
  65. or path.startswith("health/")
  66. )
  67. if exc.status_code != 404 or is_backend_path or Path(path).suffix:
  68. raise
  69. return await super().get_response("index.html", scope)
  70. @asynccontextmanager
  71. async def lifespan(_app: FastAPI):
  72. if get_infra_settings().database_auto_create:
  73. init_db()
  74. ensure_bootstrap_admin()
  75. yield
  76. dispose_engine()
  77. app = FastAPI(title="SupplyAgent API", version="0.1.0", lifespan=lifespan)
  78. app.include_router(auth_router)
  79. app.include_router(pipeline_router)
  80. app.include_router(business_harness_router)
  81. app.add_middleware(
  82. CORSMiddleware,
  83. allow_origins=[
  84. "http://localhost:5173",
  85. "http://127.0.0.1:5173",
  86. "http://localhost:4173",
  87. "http://127.0.0.1:4173",
  88. ],
  89. allow_credentials=True,
  90. allow_methods=["*"],
  91. allow_headers=["*"],
  92. )
  93. app.add_middleware(AuthenticationMiddleware)
  94. @app.get("/health")
  95. def health() -> dict[str, str]:
  96. return {"status": "ok"}
  97. @app.get("/health/live")
  98. def health_live() -> dict[str, str]:
  99. return {"status": "ok"}
  100. @app.get("/health/ready")
  101. def health_ready() -> dict:
  102. try:
  103. with get_session() as session:
  104. session.execute(text("SELECT 1"))
  105. runtime = pipeline_health_snapshot()
  106. except Exception as exc:
  107. raise HTTPException(status_code=503, detail="database unavailable") from exc
  108. if not runtime["runtime_components_ready"]:
  109. raise HTTPException(
  110. status_code=503,
  111. detail={
  112. "message": "pipeline runtime components unavailable",
  113. "scheduler_running": runtime["scheduler_running"],
  114. "worker_active_count": runtime["worker_active_count"],
  115. "worker_expected_count": runtime["worker_expected_count"],
  116. "reconciler_running": runtime["reconciler_running"],
  117. },
  118. )
  119. return {
  120. "status": "ready",
  121. "scheduler_running": runtime["scheduler_running"],
  122. "worker_active_count": runtime["worker_active_count"],
  123. "reconciler_running": runtime["reconciler_running"],
  124. }
  125. @app.get("/api/scheduler/status")
  126. def scheduler_status() -> dict:
  127. """Deprecated compatibility view backed by MySQL pipeline state."""
  128. return get_persistent_scheduler_status()
  129. class RunPipelineBody(BaseModel):
  130. biz_dt: str | None = Field(
  131. default=None,
  132. pattern=r"^\d{8}$",
  133. description="业务日 YYYYMMDD;省略则取当天",
  134. )
  135. class TriggerSchedulerJobBody(BaseModel):
  136. biz_dt: str | None = Field(
  137. default=None,
  138. pattern=r"^\d{8}$",
  139. description="业务日 YYYYMMDD;省略则取当天",
  140. )
  141. class AgentDocumentInjectionBody(BaseModel):
  142. content: str = Field(
  143. default="",
  144. max_length=100_000,
  145. description="追加到 Agent System Prompt 后的业务文档",
  146. )
  147. enabled: bool = Field(
  148. default=True,
  149. description="是否在新建 Agent 时启用该文档注入",
  150. )
  151. @app.post("/api/pipeline/run", status_code=202)
  152. def run_pipeline(
  153. body: RunPipelineBody | None = None,
  154. biz_dt: str | None = Query(
  155. default=None,
  156. pattern=r"^\d{8}$",
  157. description="业务日 YYYYMMDD(与 body 二选一,body 优先)",
  158. ),
  159. ) -> dict:
  160. """
  161. 异步一键执行供给数据全流程,立即返回 run_id,后台串行执行:
  162. 全局树同步 → 需求池同步 → 需求分级 → 视频点位拓展 → find_agent 找视频 → AIGC 发布。
  163. """
  164. resolved_biz_dt = body.biz_dt if body and body.biz_dt is not None else biz_dt
  165. return run_supply_pipeline(biz_dt=resolved_biz_dt)
  166. @app.get("/api/scheduler/jobs")
  167. def scheduler_jobs() -> dict:
  168. """Return jobs that can be triggered manually."""
  169. return {"items": list_triggerable_jobs()}
  170. @app.post("/api/scheduler/jobs/{job_id}/run")
  171. def trigger_scheduler_job(
  172. job_id: str,
  173. body: TriggerSchedulerJobBody | None = None,
  174. biz_dt: str | None = Query(
  175. default=None,
  176. pattern=r"^\d{8}$",
  177. description="业务日 YYYYMMDD(与 body 二选一,body 优先)",
  178. ),
  179. ) -> dict:
  180. """Manually trigger a scheduler job."""
  181. resolved_biz_dt = body.biz_dt if body and body.biz_dt is not None else biz_dt
  182. try:
  183. return run_scheduler_job(job_id, biz_dt=resolved_biz_dt)
  184. except KeyError:
  185. raise HTTPException(status_code=404, detail=f"scheduler job not found: {job_id}") from None
  186. @app.get("/api/scheduler/runs/{run_id}")
  187. def scheduler_job_run(run_id: str) -> dict:
  188. """Return durable pipeline run status."""
  189. result = get_scheduler_job_run(run_id)
  190. if result is None:
  191. raise HTTPException(status_code=404, detail="scheduler run not found")
  192. return result
  193. @app.get("/api/category-tree")
  194. def category_tree(
  195. biz_dt: str | None = Query(
  196. default=None,
  197. description="业务日 YYYYMMDD;省略则取 category_tree_weight 最新一日",
  198. ),
  199. ) -> dict:
  200. """Return nested global_tree_category with per-dim avg score."""
  201. return build_category_tree(biz_dt=biz_dt)
  202. @app.get("/api/demand-belong-category")
  203. def demand_belong_category() -> dict:
  204. """Return all active demand_belong_category rows in one response."""
  205. items = list_demand_belong_categories()
  206. return {"items": items}
  207. @app.get("/api/demand-belong-category/{belong_id}/videos")
  208. def demand_belong_videos(belong_id: int) -> dict:
  209. """Return videos linked to a demand_belong_category row (vid + title + points JSON)."""
  210. result = list_videos_for_demand_belong(belong_id)
  211. if result is None:
  212. raise HTTPException(status_code=404, detail="demand_belong_category not found")
  213. return result
  214. @app.get("/api/demand-grade")
  215. def demand_grade(
  216. biz_dt: str | None = Query(
  217. default=None,
  218. description="业务日 YYYYMMDD;省略则取 demand_grade 最新一日",
  219. ),
  220. ) -> dict:
  221. """Return demand_grade rows (one per category_id) for the given/latest biz_dt."""
  222. items = list_demand_grades(biz_dt=biz_dt)
  223. return {"items": items}
  224. @app.get("/api/demand-grade/{demand_grade_id}/videos")
  225. def demand_grade_videos(demand_grade_id: int) -> dict:
  226. """Return expansion videos/points for a demand_grade row (by its biz_dt)."""
  227. result = list_videos_for_demand_grade(demand_grade_id)
  228. if result is None:
  229. raise HTTPException(status_code=404, detail="demand_grade not found")
  230. return result
  231. @app.get("/api/video-discovery/demands")
  232. def video_discovery_demands(
  233. biz_dt: str | None = Query(
  234. default=None,
  235. description="业务日 YYYYMMDD;省略则取 demand_grade 最新一日",
  236. ),
  237. ) -> dict:
  238. """Return demand-first video discovery cards for the selected/latest day."""
  239. return list_video_discovery_demands(biz_dt=biz_dt)
  240. @app.get("/api/video-discovery/runs")
  241. def video_discovery_runs(
  242. biz_dt: str | None = Query(default=None, pattern=r"^\d{8}$"),
  243. status: Literal["running", "finished", "failed"] | None = None,
  244. keyword: str | None = Query(default=None, max_length=256),
  245. limit: int = Query(default=20, ge=1, le=100),
  246. offset: int = Query(default=0, ge=0),
  247. ) -> dict:
  248. """Return paged find-agent runs for the records workspace."""
  249. return list_video_discovery_runs(
  250. biz_dt=biz_dt,
  251. status=status,
  252. keyword=keyword,
  253. limit=limit,
  254. offset=offset,
  255. )
  256. @app.get("/api/video-discovery/runs/{run_id}")
  257. def video_discovery_run(run_id: str) -> dict:
  258. """Return one find-agent run and its aggregate counts."""
  259. result = get_video_discovery_run(run_id)
  260. if result is None:
  261. raise HTTPException(status_code=404, detail="video discovery run not found")
  262. return result
  263. @app.get("/api/video-discovery/runs/{run_id}/searches")
  264. def video_discovery_searches(
  265. run_id: str,
  266. keyword: str | None = Query(default=None, max_length=256),
  267. limit: int = Query(default=20, ge=1, le=100),
  268. offset: int = Query(default=0, ge=0),
  269. ) -> dict:
  270. """Return paged search-page records for one find-agent run."""
  271. result = list_video_discovery_searches(
  272. run_id,
  273. keyword=keyword,
  274. limit=limit,
  275. offset=offset,
  276. )
  277. if result is None:
  278. raise HTTPException(status_code=404, detail="video discovery run not found")
  279. return result
  280. @app.get("/api/video-discovery/runs/{run_id}/candidates")
  281. def video_discovery_candidates(
  282. run_id: str,
  283. bucket: str | None = Query(default=None, max_length=24),
  284. keyword: str | None = Query(default=None, max_length=256),
  285. limit: int = Query(default=20, ge=1, le=100),
  286. offset: int = Query(default=0, ge=0),
  287. ) -> dict:
  288. """Return paged candidate records for one find-agent run."""
  289. result = list_video_discovery_candidates(
  290. run_id,
  291. bucket=bucket,
  292. keyword=keyword,
  293. limit=limit,
  294. offset=offset,
  295. )
  296. if result is None:
  297. raise HTTPException(status_code=404, detail="video discovery run not found")
  298. return result
  299. @app.get("/api/video-discovery/demands/{demand_grade_id}")
  300. def video_discovery_demand(demand_grade_id: int) -> dict:
  301. """Return one demand and its videos/points resolved from the source tables."""
  302. result = get_video_discovery_demand(demand_grade_id)
  303. if result is None:
  304. raise HTTPException(status_code=404, detail="demand_grade not found")
  305. return result
  306. @app.post(
  307. "/api/video-discovery/feedback",
  308. status_code=status.HTTP_201_CREATED,
  309. )
  310. def submit_video_discovery_feedback(
  311. body: CreateDemandFeedbackBody,
  312. request: Request,
  313. ) -> dict:
  314. """Append feedback for one demand, video or hit-content record."""
  315. try:
  316. return create_demand_feedback(body, request.state.current_user)
  317. except FeedbackTargetNotFoundError as exc:
  318. raise HTTPException(status_code=404, detail=str(exc)) from exc
  319. except (FeedbackTargetConflictError, FeedbackRequestConflictError) as exc:
  320. raise HTTPException(status_code=409, detail=str(exc)) from exc
  321. @app.get("/api/video-discovery/feedback")
  322. def video_discovery_feedback_history(
  323. target_type: Literal["demand", "video", "hit_content"],
  324. demand_grade_id: int = Query(gt=0),
  325. video_id: str | None = Query(default=None, max_length=64),
  326. demand_video_expansion_id: int | None = Query(default=None, gt=0),
  327. limit: int = Query(default=50, ge=1, le=100),
  328. offset: int = Query(default=0, ge=0),
  329. ) -> dict:
  330. """Return feedback records and feedback people for one target."""
  331. try:
  332. return list_demand_feedback(
  333. target_type=target_type,
  334. demand_grade_id=demand_grade_id,
  335. video_id=video_id,
  336. demand_video_expansion_id=demand_video_expansion_id,
  337. limit=limit,
  338. offset=offset,
  339. )
  340. except FeedbackTargetNotFoundError as exc:
  341. raise HTTPException(status_code=404, detail=str(exc)) from exc
  342. except FeedbackTargetConflictError as exc:
  343. raise HTTPException(status_code=409, detail=str(exc)) from exc
  344. @app.get("/api/demand-belong-oss-logs")
  345. def demand_belong_oss_logs() -> dict:
  346. """Return demand_belong_category_agent oss_logs ordered by create_time desc."""
  347. items = list_demand_belong_oss_logs()
  348. return {"items": items}
  349. @app.get("/api/agent-oss-logs")
  350. def agent_oss_logs(
  351. agent_name: str | None = Query(
  352. default=None,
  353. description="Agent 名称;省略则返回全部 Agent 日志",
  354. ),
  355. ) -> dict:
  356. """Return Agent oss_logs and the available Agent names."""
  357. return list_agent_oss_logs(agent_name=agent_name)
  358. @app.get("/api/agents/{agent_name}")
  359. def agent_detail(agent_name: str) -> dict:
  360. """Return one business Agent's current system prompt and tools."""
  361. result = get_agent_detail(agent_name)
  362. if result is None:
  363. raise HTTPException(status_code=404, detail=f"agent not found: {agent_name}")
  364. return result
  365. @app.put("/api/agents/{agent_name}/document-injection")
  366. def agent_document_injection(
  367. agent_name: str,
  368. body: AgentDocumentInjectionBody,
  369. ) -> dict:
  370. """Create or update the web-managed document injected into an Agent prompt."""
  371. result = update_agent_document_injection(
  372. agent_name,
  373. content=body.content,
  374. enabled=body.enabled,
  375. )
  376. if result is None:
  377. raise HTTPException(status_code=404, detail=f"agent not found: {agent_name}")
  378. return result
  379. _web_dist = Path(__file__).resolve().parent.parent / "web" / "dist"
  380. if _web_dist.is_dir():
  381. app.mount("/", SPAStaticFiles(directory=_web_dist, html=True), name="web")