api.py 14 KB

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