app.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 fastapi import FastAPI, HTTPException, Query
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from fastapi.staticfiles import StaticFiles
  8. from pydantic import BaseModel, Field
  9. from sqlalchemy import text
  10. from starlette.exceptions import HTTPException as StarletteHTTPException
  11. from api.routers.pipeline import router as pipeline_router
  12. from api.services.agent_catalog import (
  13. get_agent_detail,
  14. update_agent_document_injection,
  15. )
  16. from api.services.category_tree import build_category_tree
  17. from api.services.demand_belong_category import list_demand_belong_categories
  18. from api.services.demand_grade import list_demand_grades
  19. from api.services.demand_grade_videos import list_videos_for_demand_grade
  20. from api.services.demand_videos import list_videos_for_demand_belong
  21. from api.services.oss_logs import list_agent_oss_logs, list_demand_belong_oss_logs
  22. from api.services.scheduler import (
  23. get_scheduler_job_run,
  24. list_triggerable_jobs,
  25. run_scheduler_job,
  26. run_supply_pipeline,
  27. scheduler_status as get_persistent_scheduler_status,
  28. )
  29. from api.services.video_discovery import (
  30. get_video_discovery_demand,
  31. list_video_discovery_demands,
  32. )
  33. from supply_infra.config import get_infra_settings
  34. from supply_infra.db import dispose_engine, get_session, init_db
  35. class SPAStaticFiles(StaticFiles):
  36. """Serve index.html for browser routes handled by Vue Router."""
  37. async def get_response(self, path: str, scope):
  38. try:
  39. return await super().get_response(path, scope)
  40. except StarletteHTTPException as exc:
  41. is_backend_path = (
  42. path == "api"
  43. or path.startswith("api/")
  44. or path == "health"
  45. or path.startswith("health/")
  46. )
  47. if exc.status_code != 404 or is_backend_path or Path(path).suffix:
  48. raise
  49. return await super().get_response("index.html", scope)
  50. @asynccontextmanager
  51. async def lifespan(_app: FastAPI):
  52. if get_infra_settings().database_auto_create:
  53. init_db()
  54. yield
  55. dispose_engine()
  56. app = FastAPI(title="SupplyAgent API", version="0.1.0", lifespan=lifespan)
  57. app.include_router(pipeline_router)
  58. app.add_middleware(
  59. CORSMiddleware,
  60. allow_origins=[
  61. "http://localhost:5173",
  62. "http://127.0.0.1:5173",
  63. "http://localhost:4173",
  64. "http://127.0.0.1:4173",
  65. ],
  66. allow_credentials=True,
  67. allow_methods=["*"],
  68. allow_headers=["*"],
  69. )
  70. @app.get("/health")
  71. def health() -> dict[str, str]:
  72. return {"status": "ok"}
  73. @app.get("/health/live")
  74. def health_live() -> dict[str, str]:
  75. return {"status": "ok"}
  76. @app.get("/health/ready")
  77. def health_ready() -> dict[str, str]:
  78. try:
  79. with get_session() as session:
  80. session.execute(text("SELECT 1"))
  81. except Exception as exc:
  82. raise HTTPException(status_code=503, detail="database unavailable") from exc
  83. return {"status": "ready"}
  84. @app.get("/api/scheduler/status")
  85. def scheduler_status() -> dict:
  86. """Deprecated compatibility view backed by MySQL pipeline state."""
  87. return get_persistent_scheduler_status()
  88. class RunPipelineBody(BaseModel):
  89. biz_dt: str | None = Field(
  90. default=None,
  91. pattern=r"^\d{8}$",
  92. description="业务日 YYYYMMDD;省略则取当天",
  93. )
  94. class TriggerSchedulerJobBody(BaseModel):
  95. biz_dt: str | None = Field(
  96. default=None,
  97. pattern=r"^\d{8}$",
  98. description="业务日 YYYYMMDD;省略则取当天",
  99. )
  100. partition_date: str | None = Field(
  101. default=None,
  102. pattern=r"^\d{8}$",
  103. description="ODPS 分区日 YYYYMMDD;全局树默认取 biz_dt 前一日",
  104. )
  105. wait: bool = Field(
  106. default=False,
  107. description="是否同步等待执行完成;默认 false 表示后台执行",
  108. )
  109. class AgentDocumentInjectionBody(BaseModel):
  110. content: str = Field(
  111. default="",
  112. max_length=100_000,
  113. description="追加到 Agent System Prompt 后的业务文档",
  114. )
  115. enabled: bool = Field(
  116. default=True,
  117. description="是否在新建 Agent 时启用该文档注入",
  118. )
  119. @app.post("/api/pipeline/run", status_code=202)
  120. def run_pipeline(
  121. body: RunPipelineBody | None = None,
  122. biz_dt: str | None = Query(
  123. default=None,
  124. pattern=r"^\d{8}$",
  125. description="业务日 YYYYMMDD(与 body 二选一,body 优先)",
  126. ),
  127. ) -> dict:
  128. """
  129. 异步一键执行供给数据全流程,立即返回 run_id,后台串行执行:
  130. 全局树同步 → 需求池同步 → 需求分级 → 视频点位拓展 → find_agent 找片 → AIGC 发布。
  131. """
  132. resolved_biz_dt = body.biz_dt if body and body.biz_dt is not None else biz_dt
  133. return run_supply_pipeline(biz_dt=resolved_biz_dt)
  134. @app.get("/api/scheduler/jobs")
  135. def scheduler_jobs() -> dict:
  136. """Return jobs that can be triggered manually."""
  137. return {"items": list_triggerable_jobs()}
  138. @app.post("/api/scheduler/jobs/{job_id}/run")
  139. def trigger_scheduler_job(
  140. job_id: str,
  141. body: TriggerSchedulerJobBody | None = None,
  142. biz_dt: str | None = Query(
  143. default=None,
  144. pattern=r"^\d{8}$",
  145. description="业务日 YYYYMMDD(与 body 二选一,body 优先)",
  146. ),
  147. partition_date: str | None = Query(
  148. default=None,
  149. pattern=r"^\d{8}$",
  150. description="ODPS 分区日 YYYYMMDD(与 body 二选一,body 优先)",
  151. ),
  152. wait: bool = Query(
  153. default=False,
  154. description="是否同步等待执行完成",
  155. ),
  156. ) -> dict:
  157. """Manually trigger a scheduler job."""
  158. resolved_biz_dt = body.biz_dt if body and body.biz_dt is not None else biz_dt
  159. resolved_partition_date = (
  160. body.partition_date if body and body.partition_date is not None else partition_date
  161. )
  162. resolved_wait = body.wait if body is not None else wait
  163. try:
  164. return run_scheduler_job(
  165. job_id,
  166. biz_dt=resolved_biz_dt,
  167. partition_date=resolved_partition_date,
  168. wait=resolved_wait,
  169. )
  170. except KeyError:
  171. raise HTTPException(status_code=404, detail=f"scheduler job not found: {job_id}") from None
  172. except ValueError as exc:
  173. raise HTTPException(status_code=409, detail=str(exc)) from None
  174. @app.get("/api/scheduler/runs/{run_id}")
  175. def scheduler_job_run(run_id: str) -> dict:
  176. """Return durable pipeline run status."""
  177. result = get_scheduler_job_run(run_id)
  178. if result is None:
  179. raise HTTPException(status_code=404, detail="scheduler run not found")
  180. return result
  181. @app.get("/api/category-tree")
  182. def category_tree(
  183. biz_dt: str | None = Query(
  184. default=None,
  185. description="业务日 YYYYMMDD;省略则取 category_tree_weight 最新一日",
  186. ),
  187. ) -> dict:
  188. """Return nested global_tree_category with per-dim avg score."""
  189. return build_category_tree(biz_dt=biz_dt)
  190. @app.get("/api/demand-belong-category")
  191. def demand_belong_category() -> dict:
  192. """Return all active demand_belong_category rows in one response."""
  193. items = list_demand_belong_categories()
  194. return {"items": items}
  195. @app.get("/api/demand-belong-category/{belong_id}/videos")
  196. def demand_belong_videos(belong_id: int) -> dict:
  197. """Return videos linked to a demand_belong_category row (vid + title + points JSON)."""
  198. result = list_videos_for_demand_belong(belong_id)
  199. if result is None:
  200. raise HTTPException(status_code=404, detail="demand_belong_category not found")
  201. return result
  202. @app.get("/api/demand-grade")
  203. def demand_grade(
  204. biz_dt: str | None = Query(
  205. default=None,
  206. description="业务日 YYYYMMDD;省略则取 demand_grade 最新一日",
  207. ),
  208. ) -> dict:
  209. """Return demand_grade rows (one per category_id) for the given/latest biz_dt."""
  210. items = list_demand_grades(biz_dt=biz_dt)
  211. return {"items": items}
  212. @app.get("/api/demand-grade/{demand_grade_id}/videos")
  213. def demand_grade_videos(demand_grade_id: int) -> dict:
  214. """Return expansion videos/points for a demand_grade row (by its biz_dt)."""
  215. result = list_videos_for_demand_grade(demand_grade_id)
  216. if result is None:
  217. raise HTTPException(status_code=404, detail="demand_grade not found")
  218. return result
  219. @app.get("/api/video-discovery/demands")
  220. def video_discovery_demands(
  221. biz_dt: str | None = Query(
  222. default=None,
  223. description="业务日 YYYYMMDD;省略则取 demand_grade 最新一日",
  224. ),
  225. ) -> dict:
  226. """Return demand-first video discovery cards for the selected/latest day."""
  227. return list_video_discovery_demands(biz_dt=biz_dt)
  228. @app.get("/api/video-discovery/demands/{demand_grade_id}")
  229. def video_discovery_demand(demand_grade_id: int) -> dict:
  230. """Return one demand and its videos/points resolved from the source tables."""
  231. result = get_video_discovery_demand(demand_grade_id)
  232. if result is None:
  233. raise HTTPException(status_code=404, detail="demand_grade not found")
  234. return result
  235. @app.get("/api/demand-belong-oss-logs")
  236. def demand_belong_oss_logs() -> dict:
  237. """Return demand_belong_category_agent oss_logs ordered by create_time desc."""
  238. items = list_demand_belong_oss_logs()
  239. return {"items": items}
  240. @app.get("/api/agent-oss-logs")
  241. def agent_oss_logs(
  242. agent_name: str | None = Query(
  243. default=None,
  244. description="Agent 名称;省略则返回全部 Agent 日志",
  245. ),
  246. ) -> dict:
  247. """Return Agent oss_logs and the available Agent names."""
  248. return list_agent_oss_logs(agent_name=agent_name)
  249. @app.get("/api/agents/{agent_name}")
  250. def agent_detail(agent_name: str) -> dict:
  251. """Return one business Agent's current system prompt and tools."""
  252. result = get_agent_detail(agent_name)
  253. if result is None:
  254. raise HTTPException(status_code=404, detail=f"agent not found: {agent_name}")
  255. return result
  256. @app.put("/api/agents/{agent_name}/document-injection")
  257. def agent_document_injection(
  258. agent_name: str,
  259. body: AgentDocumentInjectionBody,
  260. ) -> dict:
  261. """Create or update the web-managed document injected into an Agent prompt."""
  262. result = update_agent_document_injection(
  263. agent_name,
  264. content=body.content,
  265. enabled=body.enabled,
  266. )
  267. if result is None:
  268. raise HTTPException(status_code=404, detail=f"agent not found: {agent_name}")
  269. return result
  270. _web_dist = Path(__file__).resolve().parent.parent / "web" / "dist"
  271. if _web_dist.is_dir():
  272. app.mount("/", SPAStaticFiles(directory=_web_dist, html=True), name="web")