api.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. from __future__ import annotations
  2. import os
  3. from fastapi import FastAPI, HTTPException, Query
  4. from fastapi.exceptions import RequestValidationError
  5. from fastapi.encoders import jsonable_encoder
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from fastapi.responses import JSONResponse
  8. from content_agent.dashboard_service import DashboardService
  9. from content_agent.errors import ErrorCode, error_response, sanitize_error_detail
  10. from content_agent.flow_ledger_service import FlowLedgerService
  11. from content_agent.run_service import RunService
  12. from content_agent.schemas import (
  13. ConfigFileResponse,
  14. ContentItemsResponse,
  15. DashboardResponse,
  16. FlowLedgerResponse,
  17. FlowLedgerVideoResponse,
  18. FlowLedgerVideoWalkResponse,
  19. FlowLedgerVideosResponse,
  20. FlowLedgerWalkResponse,
  21. JsonFileResponse,
  22. PlatformCatalogResponse,
  23. PlatformDescriptor,
  24. QueryListResponse,
  25. RecordsResponse,
  26. RunListResponse,
  27. RunStartRequest,
  28. RunStartResponse,
  29. RunSummaryResponse,
  30. RuntimeFileResponse,
  31. RuntimeFilesResponse,
  32. TimelineResponse,
  33. ValidationResponse,
  34. )
  35. app = FastAPI(title="Content Agent V1")
  36. service = RunService.from_env()
  37. def _load_project_env_value(key: str) -> str | None:
  38. if os.environ.get(key) is not None:
  39. return os.environ[key]
  40. env_path = os.environ.get("CONTENT_AGENT_ENV_FILE") or ".env"
  41. try:
  42. lines = open(env_path, encoding="utf-8").read().splitlines()
  43. except OSError:
  44. return None
  45. for line in lines:
  46. stripped = line.strip()
  47. if not stripped or stripped.startswith("#") or "=" not in stripped:
  48. continue
  49. name, value = stripped.split("=", 1)
  50. if name.strip() == key:
  51. return value.strip().strip('"').strip("'")
  52. return None
  53. _cors_origins = [
  54. origin.strip()
  55. for origin in (
  56. _load_project_env_value("CONTENT_AGENT_WEB_CORS_ORIGINS")
  57. or "http://localhost:3000,http://127.0.0.1:3000,http://localhost:3010,http://127.0.0.1:3010"
  58. ).split(",")
  59. if origin.strip()
  60. ]
  61. if _cors_origins:
  62. app.add_middleware(
  63. CORSMiddleware,
  64. allow_origins=_cors_origins,
  65. allow_credentials=False,
  66. allow_methods=["GET", "POST", "OPTIONS"],
  67. allow_headers=["*"],
  68. )
  69. @app.exception_handler(RequestValidationError)
  70. async def validation_exception_handler(request, exc: RequestValidationError):
  71. return JSONResponse(
  72. status_code=422,
  73. content={
  74. "detail": error_response(
  75. ErrorCode.INVALID_REQUEST,
  76. "invalid request",
  77. {"errors": jsonable_encoder(sanitize_error_detail(exc.errors()))},
  78. )
  79. },
  80. )
  81. @app.post("/runs", response_model=RunStartResponse)
  82. def start_run(request: RunStartRequest) -> RunStartResponse:
  83. state = service.start_run(request)
  84. if state["status"] not in {"success", "partial_success"}:
  85. detail = error_response(
  86. state.get("error_code", ErrorCode.RUN_START_FAILED),
  87. state.get("error_message", "run failed"),
  88. state.get("error_detail", {"errors": state.get("errors", [])}),
  89. )
  90. raise HTTPException(status_code=state.get("http_status_code", 500), detail=detail)
  91. run_id = state["run_id"]
  92. return RunStartResponse(
  93. run_id=run_id,
  94. policy_run_id=state["policy_run_id"],
  95. status=state["status"],
  96. policy_bundle_id=state["policy_bundle_id"],
  97. strategy_version=state["strategy_version"],
  98. platform=state["platform"],
  99. platform_mode=state["platform_mode"],
  100. output_dir=str(service.runtime.run_dir(run_id)),
  101. )
  102. @app.get("/runs", response_model=RunListResponse)
  103. def list_runs(
  104. status: str | None = None,
  105. platform: str | None = None,
  106. platform_mode: str | None = None,
  107. strategy_version: str | None = None,
  108. validation_status: str | None = None,
  109. error_code: str | None = None,
  110. page: int = Query(default=1, ge=1),
  111. page_size: int = Query(default=20, ge=1, le=100),
  112. ) -> RunListResponse:
  113. return RunListResponse(
  114. **_dashboard_service().list_runs(
  115. status=status,
  116. platform=platform,
  117. platform_mode=platform_mode,
  118. strategy_version=strategy_version,
  119. validation_status=validation_status,
  120. error_code=error_code,
  121. page=page,
  122. page_size=page_size,
  123. )
  124. )
  125. @app.get("/runs/{run_id}", response_model=RunSummaryResponse)
  126. def get_run(run_id: str) -> RunSummaryResponse:
  127. _ensure_run_exists(run_id)
  128. return RunSummaryResponse(**service.get_summary(run_id))
  129. _CONFIG_FILES = {
  130. "rule-packs": "product_documents/规则包/douyin_rule_packs.v1.json",
  131. "walk-strategy": "product_documents/抖音游走策略/douyin_walk_strategy.v1.json",
  132. "query-prompts": "product_documents/配置/query_prompts.v1.json",
  133. "walk-policy": "tech_documents/数据接口与来源/walk_policy.json",
  134. }
  135. def _config_file_response(key: str) -> ConfigFileResponse:
  136. from pathlib import Path
  137. from content_agent.integrations import config_store
  138. path = Path(_CONFIG_FILES[key])
  139. if not path.exists():
  140. raise HTTPException(status_code=404, detail=error_response(
  141. ErrorCode.RUN_NOT_FOUND, f"config file missing: {key}", {"source_file": str(path)}
  142. ))
  143. data, _ = config_store.load_json(path)
  144. return ConfigFileResponse(source_file=str(path), data=data)
  145. @app.get("/config/rule-packs", response_model=ConfigFileResponse)
  146. def get_config_rule_packs() -> ConfigFileResponse:
  147. return _config_file_response("rule-packs")
  148. @app.get("/config/walk-strategy", response_model=ConfigFileResponse)
  149. def get_config_walk_strategy() -> ConfigFileResponse:
  150. return _config_file_response("walk-strategy")
  151. @app.get("/config/query-prompts", response_model=ConfigFileResponse)
  152. def get_config_query_prompts() -> ConfigFileResponse:
  153. return _config_file_response("query-prompts")
  154. @app.get("/config/walk-policy", response_model=ConfigFileResponse)
  155. def get_config_walk_policy() -> ConfigFileResponse:
  156. # 返回原始 JSON 不解包 {value,provenance,tbd}:展示层保留拍板留痕,解包由前端做。
  157. return _config_file_response("walk-policy")
  158. _PLATFORM_PROFILE_DIR = "tech_documents/数据接口与来源/platform_profiles"
  159. @app.get("/config/platforms", response_model=PlatformCatalogResponse)
  160. def get_config_platforms() -> PlatformCatalogResponse:
  161. # 平台展示目录:从 platform_profiles/*.json 派生平台 label 与可观测字段。
  162. # heat_fields 是 V3 历史展示字段;observable_fields 才是 V4 平台表现解释字段。
  163. # 前端按此渲染平台名与互动数据——加平台只改 profile JSON,前端零改动。
  164. from pathlib import Path
  165. from content_agent.integrations import config_store
  166. catalog: dict[str, PlatformDescriptor] = {}
  167. profile_dir = Path(_PLATFORM_PROFILE_DIR)
  168. for path in sorted(profile_dir.glob("*.json")):
  169. try:
  170. data, _ = config_store.load_json(path)
  171. except (FileNotFoundError, OSError, ValueError):
  172. continue
  173. platform = str(data.get("platform") or path.stem)
  174. heat_fields = [
  175. str(sig["field"])
  176. for sig in ((data.get("heat") or {}).get("signals") or [])
  177. if isinstance(sig, dict) and sig.get("field")
  178. ]
  179. observable_fields = [
  180. str(item["field"])
  181. for item in (data.get("observable_fields") or [])
  182. if isinstance(item, dict) and item.get("field")
  183. ]
  184. catalog[platform] = PlatformDescriptor(
  185. platform=platform,
  186. label=str(data.get("platform_label") or platform),
  187. status=data.get("status"),
  188. heat_fields=heat_fields,
  189. observable_fields=observable_fields,
  190. )
  191. return PlatformCatalogResponse(platforms=catalog)
  192. @app.get("/runs/{run_id}/dashboard", response_model=DashboardResponse)
  193. def get_run_dashboard(run_id: str) -> DashboardResponse:
  194. _ensure_web_run_exists(run_id)
  195. return DashboardResponse(**_dashboard_service().dashboard(run_id))
  196. @app.get("/runs/{run_id}/queries", response_model=QueryListResponse)
  197. def get_run_queries(run_id: str) -> QueryListResponse:
  198. _ensure_web_run_exists(run_id)
  199. return QueryListResponse(**_dashboard_service().queries(run_id))
  200. @app.get("/runs/{run_id}/timeline", response_model=TimelineResponse)
  201. def get_run_timeline(run_id: str) -> TimelineResponse:
  202. _ensure_web_run_exists(run_id)
  203. return TimelineResponse(**_dashboard_service().timeline(run_id))
  204. @app.get("/runs/{run_id}/content-items", response_model=ContentItemsResponse)
  205. def get_run_content_items(run_id: str) -> ContentItemsResponse:
  206. _ensure_web_run_exists(run_id)
  207. return ContentItemsResponse(**_dashboard_service().content_items(run_id))
  208. @app.get("/runs/{run_id}/flow-ledger", response_model=FlowLedgerResponse)
  209. def get_flow_ledger(run_id: str, debug: bool = False) -> FlowLedgerResponse:
  210. _ensure_web_run_exists(run_id)
  211. return FlowLedgerResponse(**_flow_ledger_service().ledger(run_id, debug=debug))
  212. @app.get("/runs/{run_id}/flow-ledger/walk", response_model=FlowLedgerWalkResponse)
  213. def get_flow_ledger_run_walk(run_id: str, debug: bool = False) -> FlowLedgerWalkResponse:
  214. _ensure_web_run_exists(run_id)
  215. return FlowLedgerWalkResponse(**_flow_ledger_service().run_walk(run_id, debug=debug))
  216. @app.get("/runs/{run_id}/flow-ledger/queries/{query_id}/videos", response_model=FlowLedgerVideosResponse)
  217. def get_flow_ledger_query_videos(
  218. run_id: str,
  219. query_id: str,
  220. debug: bool = False,
  221. ) -> FlowLedgerVideosResponse:
  222. _ensure_web_run_exists(run_id)
  223. return FlowLedgerVideosResponse(
  224. **_flow_ledger_service().query_videos(run_id, query_id, debug=debug)
  225. )
  226. @app.get("/runs/{run_id}/flow-ledger/queries/{query_id}/walk", response_model=FlowLedgerWalkResponse)
  227. def get_flow_ledger_query_walk(
  228. run_id: str,
  229. query_id: str,
  230. debug: bool = False,
  231. ) -> FlowLedgerWalkResponse:
  232. _ensure_web_run_exists(run_id)
  233. return FlowLedgerWalkResponse(
  234. **_flow_ledger_service().query_walk(run_id, query_id, debug=debug)
  235. )
  236. @app.get("/runs/{run_id}/flow-ledger/videos/{content_id}", response_model=FlowLedgerVideoResponse)
  237. def get_flow_ledger_video(
  238. run_id: str,
  239. content_id: str,
  240. debug: bool = False,
  241. ) -> FlowLedgerVideoResponse:
  242. _ensure_web_run_exists(run_id)
  243. payload = _flow_ledger_service().video_detail(run_id, content_id, debug=debug)
  244. if payload.get("video") is None:
  245. raise HTTPException(
  246. status_code=404,
  247. detail=error_response(
  248. ErrorCode.RUN_NOT_FOUND,
  249. "video not found",
  250. {"run_id": run_id, "content_id": content_id},
  251. ),
  252. )
  253. return FlowLedgerVideoResponse(**payload)
  254. @app.get("/runs/{run_id}/flow-ledger/videos/{content_id}/walk", response_model=FlowLedgerVideoWalkResponse)
  255. def get_flow_ledger_video_walk(
  256. run_id: str,
  257. content_id: str,
  258. debug: bool = False,
  259. ) -> FlowLedgerVideoWalkResponse:
  260. _ensure_web_run_exists(run_id)
  261. payload = _flow_ledger_service().video_walk(run_id, content_id, debug=debug)
  262. if payload.get("root_video") is None:
  263. raise HTTPException(
  264. status_code=404,
  265. detail=error_response(
  266. ErrorCode.RUN_NOT_FOUND,
  267. "video not found",
  268. {"run_id": run_id, "content_id": content_id},
  269. ),
  270. )
  271. return FlowLedgerVideoWalkResponse(**payload)
  272. @app.get("/runs/{run_id}/runtime-files", response_model=RuntimeFilesResponse)
  273. def get_run_runtime_files(run_id: str) -> RuntimeFilesResponse:
  274. _ensure_web_run_exists(run_id)
  275. return RuntimeFilesResponse(**_dashboard_service().runtime_files(run_id))
  276. @app.get("/runs/{run_id}/runtime-files/{filename}", response_model=RuntimeFileResponse)
  277. def get_run_runtime_file(
  278. run_id: str,
  279. filename: str,
  280. limit: int = Query(default=100, ge=1, le=500),
  281. offset: int = Query(default=0, ge=0),
  282. ) -> RuntimeFileResponse:
  283. _ensure_web_run_exists(run_id)
  284. try:
  285. return RuntimeFileResponse(
  286. **_dashboard_service().runtime_file(
  287. run_id,
  288. filename,
  289. limit=limit,
  290. offset=offset,
  291. )
  292. )
  293. except ValueError:
  294. raise HTTPException(
  295. status_code=400,
  296. detail=error_response(
  297. ErrorCode.INVALID_REQUEST,
  298. "runtime filename is not allowed",
  299. {"filename": filename},
  300. ),
  301. )
  302. @app.get("/runs/{run_id}/discovered-content-items", response_model=RecordsResponse)
  303. def get_discovered_content_items(run_id: str) -> RecordsResponse:
  304. return _jsonl_response(run_id, "discovered_content_items.jsonl")
  305. @app.get("/runs/{run_id}/rule-decisions", response_model=RecordsResponse)
  306. def get_rule_decisions(run_id: str) -> RecordsResponse:
  307. return _jsonl_response(run_id, "rule_decisions.jsonl")
  308. @app.get("/runs/{run_id}/source-path-records", response_model=RecordsResponse)
  309. def get_source_path_records(run_id: str) -> RecordsResponse:
  310. return _jsonl_response(run_id, "source_path_records.jsonl")
  311. @app.get("/runs/{run_id}/final-output", response_model=JsonFileResponse)
  312. def get_final_output(run_id: str) -> JsonFileResponse:
  313. return _json_response(run_id, "final_output.json")
  314. @app.get("/runs/{run_id}/strategy-review", response_model=JsonFileResponse)
  315. def get_strategy_review(run_id: str) -> JsonFileResponse:
  316. _ensure_web_run_exists(run_id)
  317. return JsonFileResponse(run_id=run_id, data=service.strategy_review(run_id))
  318. @app.post("/runs/{run_id}/strategy-review/regenerate", response_model=JsonFileResponse)
  319. def regenerate_strategy_review(run_id: str) -> JsonFileResponse:
  320. _ensure_web_run_exists(run_id)
  321. return JsonFileResponse(run_id=run_id, data=service.regenerate_strategy_review(run_id))
  322. @app.get("/runs/{run_id}/validation", response_model=ValidationResponse)
  323. def get_validation(run_id: str) -> ValidationResponse:
  324. _ensure_web_run_exists(run_id)
  325. return ValidationResponse(**_dashboard_service()._validate_optional(run_id))
  326. def _jsonl_response(run_id: str, filename: str) -> RecordsResponse:
  327. _ensure_web_run_exists(run_id)
  328. return RecordsResponse(run_id=run_id, records=service.read_jsonl(run_id, filename))
  329. def _json_response(run_id: str, filename: str) -> JsonFileResponse:
  330. _ensure_web_run_exists(run_id)
  331. return JsonFileResponse(run_id=run_id, data=service.read_json(run_id, filename))
  332. def _ensure_run_exists(run_id: str) -> None:
  333. if not service.runtime.run_dir(run_id).exists():
  334. raise HTTPException(
  335. status_code=404,
  336. detail=error_response(
  337. ErrorCode.RUN_NOT_FOUND,
  338. "run not found",
  339. {"run_id": run_id},
  340. ),
  341. )
  342. def _ensure_web_run_exists(run_id: str) -> None:
  343. if not _dashboard_service().run_exists(run_id):
  344. raise HTTPException(
  345. status_code=404,
  346. detail=error_response(
  347. ErrorCode.RUN_NOT_FOUND,
  348. "run not found",
  349. {"run_id": run_id},
  350. ),
  351. )
  352. def _dashboard_service() -> DashboardService:
  353. return DashboardService.from_runtime(service.runtime)
  354. def _flow_ledger_service() -> FlowLedgerService:
  355. return FlowLedgerService(service.runtime)