api.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. """工具服务 HTTP 接口(FastAPI)。
  2. 这是“工具执行层”的唯一入口,BFF 与前端都通过它访问数据:
  3. =========================== ====================================================
  4. 接口 说明
  5. =========================== ====================================================
  6. ``GET /health`` 健康检查
  7. ``GET /meta`` 工具清单与版本(前端“关于”页使用)
  8. ``POST /workspaces`` 创建工作区
  9. ``GET /workspaces`` 工作区列表
  10. ``POST /workspaces/{id}/objects`` 上传原始文件(multipart)
  11. ``GET /objects/{id}`` 对象元数据(含表清单、行数、血缘)
  12. ``GET /objects/{id}/preview`` 预览某张表
  13. ``GET /objects/{id}/file`` 下载对象内的文件(xlsx / csv)
  14. ``POST /runs`` 起一个处理任务(前端数据处理工作区)
  15. ``GET /runs/{id}`` 查询进度
  16. ``POST /tools/data_read`` data_read 工具
  17. ``POST /tools/calculator`` calculator 工具
  18. ``POST /tools/customs_process`` 同步执行处理(Agent 工具)
  19. ``GET /ledger/...`` 台账查询与自检
  20. =========================== ====================================================
  21. """
  22. from __future__ import annotations
  23. import json
  24. from contextlib import asynccontextmanager
  25. from pathlib import Path
  26. from fastapi import Body, FastAPI, File, HTTPException, Query, UploadFile
  27. from fastapi.middleware.cors import CORSMiddleware
  28. from fastapi.responses import FileResponse, JSONResponse
  29. from pydantic import BaseModel, Field
  30. from . import __version__
  31. from .calc import CalcError, calculate
  32. from .config import settings
  33. from .customs import OPERATIONS, load_processor
  34. from .db import database
  35. from .ledger import ledger
  36. from .objects import store
  37. from .readers import ReadError, read_rows
  38. from .runs import build_options, runs
  39. @asynccontextmanager
  40. async def lifespan(_app: FastAPI):
  41. """启动时建目录、建表、保证有一个默认工作区。"""
  42. settings.ensure()
  43. database # 触发建表
  44. store.ensure_default_workspace()
  45. yield
  46. app = FastAPI(title="海关问数 Agent · 工具执行服务", version=__version__, lifespan=lifespan)
  47. app.add_middleware(
  48. CORSMiddleware,
  49. allow_origins=["*"],
  50. allow_credentials=False,
  51. allow_methods=["*"],
  52. allow_headers=["*"],
  53. )
  54. # ---------------------------------------------------------------------- 基础
  55. @app.get("/health")
  56. def health() -> dict:
  57. return {"ok": True, "service": "tools", "version": __version__, "data_dir": str(settings.data_dir)}
  58. @app.get("/meta")
  59. def meta() -> dict:
  60. processor = load_processor()
  61. with database.connect() as connection:
  62. workspaces = connection.execute("SELECT COUNT(*) FROM workspaces").fetchone()[0]
  63. objects = connection.execute("SELECT COUNT(*) FROM objects").fetchone()[0]
  64. return {
  65. "version": __version__,
  66. "processor": {"name": getattr(processor, "name", "custom"), "version": getattr(processor, "version", "0")},
  67. "operations": list(OPERATIONS),
  68. "tools": ["customs_process", "data_read", "calculator"],
  69. "workspaces": workspaces,
  70. "objects": objects,
  71. "ledger": ledger.stats(),
  72. }
  73. # ---------------------------------------------------------------------- 工作区
  74. class WorkspaceCreate(BaseModel):
  75. name: str = Field(min_length=1, max_length=80)
  76. description: str = ""
  77. @app.get("/workspaces")
  78. def list_workspaces() -> dict:
  79. return {"items": store.list_workspaces()}
  80. @app.post("/workspaces", status_code=201)
  81. def create_workspace(payload: WorkspaceCreate) -> dict:
  82. return store.create_workspace(payload.name, payload.description)
  83. @app.delete("/workspaces/{workspace_id}")
  84. def delete_workspace(workspace_id: str) -> dict:
  85. try:
  86. store.delete_workspace(workspace_id)
  87. except KeyError as error:
  88. raise HTTPException(status_code=404, detail=str(error)) from error
  89. return {"ok": True}
  90. # ---------------------------------------------------------------------- 对象
  91. @app.get("/workspaces/{workspace_id}/objects")
  92. def list_objects(workspace_id: str, kind: str | None = None) -> dict:
  93. return {"items": store.list_objects(workspace_id, kind)}
  94. @app.post("/workspaces/{workspace_id}/objects", status_code=201)
  95. async def upload_object(workspace_id: str, file: UploadFile = File(...)) -> dict:
  96. payload = await file.read()
  97. if len(payload) > settings.max_upload_bytes:
  98. raise HTTPException(status_code=413, detail=f"文件超过上限 {settings.max_upload_bytes // 1024 // 1024} MB")
  99. try:
  100. return store.register_upload(workspace_id, file.filename or "upload.csv", payload)
  101. except KeyError as error:
  102. raise HTTPException(status_code=404, detail=str(error)) from error
  103. except Exception as error: # noqa: BLE001
  104. raise HTTPException(status_code=400, detail=f"文件解析失败: {error}") from error
  105. @app.get("/objects/{object_id}")
  106. def get_object(object_id: str) -> dict:
  107. try:
  108. return store.get_object(object_id)
  109. except KeyError as error:
  110. raise HTTPException(status_code=404, detail=str(error)) from error
  111. @app.delete("/objects/{object_id}")
  112. def delete_object(object_id: str) -> dict:
  113. try:
  114. store.delete_object(object_id)
  115. except KeyError as error:
  116. raise HTTPException(status_code=404, detail=str(error)) from error
  117. return {"ok": True}
  118. @app.get("/objects/{object_id}/preview")
  119. def preview_object(
  120. object_id: str,
  121. table: str = "raw",
  122. limit: int = Query(20, ge=1, le=200),
  123. offset: int = Query(0, ge=0),
  124. ) -> dict:
  125. try:
  126. return store.preview(object_id, table, limit, offset)
  127. except KeyError as error:
  128. raise HTTPException(status_code=404, detail=str(error)) from error
  129. except ReadError as error:
  130. raise HTTPException(status_code=400, detail=str(error)) from error
  131. @app.get("/objects/{object_id}/row")
  132. def object_row(object_id: str, table: str = "raw", row: int = Query(..., ge=0)) -> dict:
  133. """按行号取一行(溯源 chip 点击后要看到"这一行原来是什么")。
  134. 返回该行的原文、行哈希,以及行级血缘(``source_rows`` 谓词,可据此下钻到原始记录)。
  135. """
  136. try:
  137. return store.read_row(object_id, table, row)
  138. except KeyError as error:
  139. raise HTTPException(status_code=404, detail=str(error)) from error
  140. except ReadError as error:
  141. raise HTTPException(status_code=400, detail=str(error)) from error
  142. @app.get("/objects/{object_id}/sheet_meta")
  143. def object_sheet_meta(object_id: str) -> dict:
  144. """结果表的自描述:每张表的行数、列名、行哈希数量(供前端"数据浏览"用)。"""
  145. try:
  146. item = store.get_object(object_id)
  147. except KeyError as error:
  148. raise HTTPException(status_code=404, detail=str(error)) from error
  149. return {
  150. "object_id": object_id,
  151. "name": item["name"],
  152. "kind": item["kind"],
  153. "rows": item["rows"],
  154. "tables": item["tables"],
  155. "lineage": item["meta"].get("lineage", {}),
  156. "parents": item["parents"],
  157. }
  158. @app.get("/objects/{object_id}/lineage")
  159. def object_lineage(object_id: str, table: str | None = None, row: int | None = None) -> dict:
  160. try:
  161. item = store.get_object(object_id)
  162. except KeyError as error:
  163. raise HTTPException(status_code=404, detail=str(error)) from error
  164. if table is not None and row is not None:
  165. entry = store.row_lineage(object_id, table, row)
  166. if not entry:
  167. raise HTTPException(status_code=404, detail="该行没有血缘记录")
  168. return entry
  169. return {"object_id": object_id, "parents": item["parents"], "lineage": item["meta"].get("lineage", {})}
  170. @app.get("/objects/{object_id}/file")
  171. def download_file(object_id: str, name: str = Query(..., description="对象目录内的相对文件名")):
  172. try:
  173. item = store.get_object(object_id)
  174. except KeyError as error:
  175. raise HTTPException(status_code=404, detail=str(error)) from error
  176. base = Path(item["path"]).parent if Path(item["path"]).is_file() else Path(item["path"])
  177. target = (base / name).resolve()
  178. try:
  179. target.relative_to(base.resolve())
  180. except ValueError as error:
  181. raise HTTPException(status_code=400, detail="非法路径") from error
  182. if not target.exists():
  183. raise HTTPException(status_code=404, detail=f"文件不存在: {name}")
  184. return FileResponse(target, filename=target.name)
  185. # ---------------------------------------------------------------------- 处理任务
  186. class RunCreate(BaseModel):
  187. workspace_id: str
  188. input_object_id: str
  189. operation: str = "full_pipeline"
  190. options: dict = Field(default_factory=dict)
  191. output_name: str | None = None
  192. @app.post("/runs", status_code=201)
  193. def create_run(payload: RunCreate) -> dict:
  194. if payload.operation not in OPERATIONS:
  195. raise HTTPException(status_code=400, detail=f"operation 只支持 {OPERATIONS}")
  196. try:
  197. build_options(payload.options).validate()
  198. except ValueError as error:
  199. raise HTTPException(status_code=400, detail=str(error)) from error
  200. try:
  201. return runs.create(payload.workspace_id, payload.input_object_id, payload.operation, payload.options, payload.output_name)
  202. except KeyError as error:
  203. raise HTTPException(status_code=404, detail=str(error)) from error
  204. except ValueError as error:
  205. raise HTTPException(status_code=400, detail=str(error)) from error
  206. @app.get("/runs")
  207. def list_runs(limit: int = Query(20, ge=1, le=100)) -> dict:
  208. return {"items": runs.list(limit)}
  209. @app.get("/runs/{run_id}")
  210. def get_run(run_id: str) -> dict:
  211. try:
  212. return runs.get(run_id)
  213. except KeyError as error:
  214. raise HTTPException(status_code=404, detail=str(error)) from error
  215. # ---------------------------------------------------------------------- 工具
  216. class DataReadRequest(BaseModel):
  217. object_id: str
  218. table: str = "raw"
  219. columns: list[str] | None = None
  220. filters: list[dict] | None = None
  221. order_by: list[dict] | None = None
  222. limit: int | None = None
  223. offset: int = 0
  224. aggregate: dict | None = None
  225. #: 由 BFF 传入:把本次调用登记进数据面台账,call_id 与溯源令牌一致
  226. call_id: str = ""
  227. session_id: str = ""
  228. @app.post("/tools/data_read")
  229. def tool_data_read(payload: DataReadRequest) -> dict:
  230. try:
  231. result = read_rows(
  232. payload.object_id,
  233. table=payload.table,
  234. filters=payload.filters,
  235. columns=payload.columns,
  236. order_by=payload.order_by,
  237. limit=payload.limit,
  238. offset=payload.offset,
  239. aggregate=payload.aggregate,
  240. )
  241. except KeyError as error:
  242. raise HTTPException(status_code=404, detail=str(error)) from error
  243. except ReadError as error:
  244. raise HTTPException(status_code=400, detail=str(error)) from error
  245. if payload.call_id:
  246. # 数据面台账:调用级记录 + 行级索引,供离线审计和"这个数从哪来"
  247. ledger.record(
  248. payload.call_id,
  249. "data_read",
  250. {
  251. "object_id": payload.object_id,
  252. "table": payload.table,
  253. "filters": payload.filters,
  254. "limit": payload.limit,
  255. "offset": payload.offset,
  256. "aggregate": payload.aggregate,
  257. },
  258. {
  259. "columns": result["columns"],
  260. "total": result.get("total"),
  261. "returned": len(result["rows"]),
  262. },
  263. object_ids=[payload.object_id],
  264. session_id=payload.session_id,
  265. rows=[
  266. {
  267. "values": row["values"],
  268. "_trace": {
  269. "object_id": row["_trace"].get("object_id", payload.object_id),
  270. "table": row["_trace"].get("table", payload.table),
  271. "row_index": row["_trace"].get("row_index", -1),
  272. "row_hash": row["_trace"].get("row_hash", ""),
  273. },
  274. }
  275. for row in result["rows"]
  276. ],
  277. )
  278. return result
  279. class CalcRequest(BaseModel):
  280. op: str = "sum"
  281. inputs: list[dict] | None = None
  282. expression: str | None = None
  283. session_id: str = ""
  284. label: str = ""
  285. @app.post("/tools/calculator")
  286. def tool_calculator(payload: CalcRequest) -> dict:
  287. try:
  288. return calculate(payload.op, payload.inputs, payload.expression, session_id=payload.session_id, label=payload.label)
  289. except CalcError as error:
  290. raise HTTPException(status_code=400, detail=str(error)) from error
  291. class ProcessRequest(BaseModel):
  292. workspace_id: str
  293. input_object_id: str
  294. operation: str = "full_pipeline"
  295. params: dict = Field(default_factory=dict)
  296. output_filename: str | None = None
  297. call_id: str = ""
  298. session_id: str = ""
  299. @app.post("/tools/customs_process")
  300. def tool_customs_process(payload: ProcessRequest) -> dict:
  301. if payload.operation not in OPERATIONS:
  302. raise HTTPException(status_code=400, detail=f"operation 只支持 {OPERATIONS}")
  303. try:
  304. run = runs.run_sync(payload.workspace_id, payload.input_object_id, payload.operation, payload.params, payload.output_filename)
  305. except KeyError as error:
  306. raise HTTPException(status_code=404, detail=str(error)) from error
  307. if run["status"] != "succeeded":
  308. return JSONResponse(
  309. status_code=422,
  310. content={"detail": run.get("error") or "处理失败", "run": run},
  311. )
  312. item = store.get_object(run["object_id"])
  313. if payload.call_id:
  314. ledger.record(
  315. payload.call_id,
  316. "customs_process",
  317. {
  318. "workspace_id": payload.workspace_id,
  319. "input_object_id": payload.input_object_id,
  320. "operation": payload.operation,
  321. "params": payload.params,
  322. },
  323. {
  324. "run_id": run["id"],
  325. "object_id": item["id"],
  326. "sheet_count": len(item["tables"]),
  327. "rows": item["rows"],
  328. "lineage": item["meta"].get("lineage", {}),
  329. },
  330. object_ids=[payload.input_object_id, item["id"]],
  331. session_id=payload.session_id,
  332. )
  333. return {
  334. "run_id": run["id"],
  335. "object_id": item["id"],
  336. "name": item["name"],
  337. "sheets": item["tables"],
  338. "lineage": item["meta"].get("lineage", {}),
  339. "stats": item["meta"].get("stats", {}),
  340. "warnings": item["meta"].get("warnings", []),
  341. "files": _object_files(item),
  342. }
  343. def _object_files(item: dict) -> list[str]:
  344. base = Path(item["path"])
  345. directory = base.parent if base.is_file() else base
  346. files = []
  347. for path in sorted(directory.rglob("*")):
  348. if path.is_file() and path.suffix.lower() in {".xlsx", ".csv", ".json", ".sqlite"}:
  349. files.append(str(path.relative_to(directory)).replace("\\", "/"))
  350. return files[:200]
  351. # ---------------------------------------------------------------------- 台账
  352. @app.get("/ledger/calls")
  353. def ledger_calls(session_id: str = "") -> dict:
  354. return {"items": ledger.session_calls(session_id)}
  355. @app.get("/ledger/value")
  356. def ledger_value(value: str, session_id: str = "") -> dict:
  357. return {"items": ledger.find_value(value, session_id)}
  358. @app.get("/ledger/stats")
  359. def ledger_stats() -> dict:
  360. return ledger.stats()
  361. @app.get("/ledger/call/{call_id}")
  362. def ledger_call(call_id: str) -> dict:
  363. item = ledger.get(call_id)
  364. if not item:
  365. raise HTTPException(status_code=404, detail="调用不存在")
  366. return item
  367. @app.get("/ledger/export")
  368. def ledger_export() -> dict:
  369. """导出 JSONL 台账(离线审计)。"""
  370. if not settings.ledger_path.exists():
  371. return {"items": []}
  372. lines = settings.ledger_path.read_text(encoding="utf-8").strip().splitlines()
  373. return {"items": [json.loads(line) for line in lines if line.strip()]}
  374. @app.exception_handler(Exception)
  375. def unhandled_error(_request, error: Exception): # noqa: ANN001
  376. return JSONResponse(status_code=500, content={"detail": f"{type(error).__name__}: {error}"})