diff --git a/backend/app/api/copilot.py b/backend/app/api/copilot.py index 91022193..61707fc7 100644 --- a/backend/app/api/copilot.py +++ b/backend/app/api/copilot.py @@ -116,7 +116,8 @@ async def _look_service(session: AsyncSession, payload: GenerateIn, sources: lis spec = await copilot_model_spec(session, payload, max_tokens=copilot_context.PICK_MAX_TOKENS) return await copilot_context.look_service(sources, spec=spec, graph=graph, kinds=kinds, answer=payload.intent == "answer", catalog_view=catalog_view, - trail={"conversation_id": getattr(payload, "conversation_id", None)}) + trail={"conversation_id": getattr(payload, "conversation_id", None)}, + session=session) NODE_REFERENCE = """\ @@ -816,7 +817,9 @@ def _graph_system(sources: list[Any], scope: set[str] | None, datasources: str, "5. 能用 3 个节点解决就别堆 8 个" f"{_CHAT_USER_PROMPT if chat_user else ''}\n\n" f"{_STREAM_PROTOCOL}" - + (f"\n\n{looks.guide()}\n{copilot_context.LOOK_WHEN_PROMPT}" if looks.kinds else "") + # 问数据里能选用已发布口径时(next-round 02 做法 4):协议多一段 use_caliber,「什么时候该看」换成问数据那一份 + + (f"\n{copilot_context.USE_CALIBER_PROMPT}" if copilot_context.composing(looks) else "") + + (f"\n\n{looks.guide()}\n{copilot_context.look_when(looks)}" if looks.kinds else "") ) @@ -1830,12 +1833,16 @@ async def answer_ops(payload: GenerateIn, *, catalog_view: Any = None): # 比对工具绑定的基准:画布上是改之前的图;问数据页是上一轮的图(沿用它的节点 id) baseline = copy.deepcopy( (payload.base_graph or {}).get("nodes") or (prev_graph or {}).get("nodes") or []) - # 查看服务:读目录、读能力登记在开流之前做完。现有工作流(画布上的原图、问数据追问时上一轮的图)查过的表列在概览里 + # 查看服务:读目录、读能力登记在开流之前做完。现有工作流(画布上的原图、问数据追问时上一轮的图)查过的表列在概览里。 + # 问数据另看已发布口径、可以 use_caliber 选用(next-round 02 做法 4):只给搭建者及以上——使用者的图里看得到拷进来的 + # 取数 SQL(口径的 SQL 可能写着遮罩值),这一波不给 + kinds = ("table", "capability", "caliber") if payload.intent == "answer" and not chat_user \ + else ("table", "capability") looks = await _look_service(session, payload, sources, graph=payload.base_graph if ( - payload.base_graph or {}).get("nodes") else prev_graph, catalog_view=view) + payload.base_graph or {}).get("nodes") else prev_graph, catalog_view=view, kinds=kinds) # 这一份 system 一直用到最后:接着写、自查修正都沿用,不换 system = _graph_system(sources, scope, await copilot_context.section(looks), looks, chat_user=chat_user) - applier = GraphApplier(nodes, edges) + applier = GraphApplier(nodes, edges, composer=copilot_context.composer(looks)) started = time.monotonic() gen = Generation(model, system=system, applier=applier, looks=looks, started=started, checker=GraphChecker(applier, scope=scope, sources=sources, baseline=baseline, checkers=checkers, diff --git a/backend/app/api/copilot_context.py b/backend/app/api/copilot_context.py index 92621802..71f90fab 100644 --- a/backend/app/api/copilot_context.py +++ b/backend/app/api/copilot_context.py @@ -10,7 +10,10 @@ 模型,数据类请求一次查看到位。 **各入口看什么**(总方案 §5.3):画布、问数据看表和能力(问数据只列只读能力);发布前修复、升级证据看表,由系统按要修 -的 SQL 代为查看(look 文档 D5);应用润色看工作流版本和能力(在 copilot.py 里组装)。 +的 SQL 代为查看(look 文档 D5);应用润色看工作流版本和能力(在 copilot.py 里组装)。问数据另看已发布口径(next-round 02 +做法 4:搭建者及以上;使用者发起的图里看得到拷进来的取数 SQL,这一波不给):助手可以 use_caliber 选用一份口径做骨架, +「什么时候该看」换成 LOOK_WHEN_ANSWER_PROMPT,输出协议多 USE_CALIBER_PROMPT 一段。运行时写 SQL 的 Agent 不看口径(拍板 +L2:保持独立解读,「等价已证明」才有意义)。 这里提供:look_service(按入口组装查看服务,开流之前调:读目录、读能力登记要用会话)、section(system 里数据源那一节)、 system_look(系统代为查看)、写 SQL 的硬性要求和「什么时候该看」的判断标准。 @@ -59,6 +62,23 @@ LOOK_WHEN_PROMPT = """\ · 用户说了一条数据事实:先看那张表的现有目录,再提目录修改 · 要看就先看,看完再规划,不要先搭节点再回头看;这次对话里已经看过的表直接点名看,不要只给需求""" +#: 问数据里(能看已发布口径时)的「什么时候该看」:问数据那一条按口径账本改写(next-round 02 做法 4 ④),别的照旧 +LOOK_WHEN_ANSWER_PROMPT = LOOK_WHEN_PROMPT.replace( + """ · 问数据:查库交给 agent 节点,它运行时会自己查表结构。只有从概览看不出该用哪个库、用户点了表名、用户说了口径时 + 才看一次,把看到的表名写进 agent 的提示词,运行时少走弯路""", + """ · 问数据:先看已发布口径(kind 写 caliber)。问法和口径的定义完全对得上时用 use_caliber 选用它;口径只覆盖问题的 + 一部分时 use_caliber 选用那一部分,其余交给 agent 补;问法多了口径没有的条件(比如「含退款」「只看新客」)时不要套 + 口径,交给 agent 去查,系统会自动拿它的 SQL 和口径对账。查库交给 agent 时它运行时会自己查表结构:只有从概览看不出 + 该用哪个库、用户点了表名时才看表,把看到的表名写进 agent 的提示词""") + +#: 问数据里输出协议多的一段:选用口径(ledger/compose.py)。只在这一轮能看已发布口径时接在协议后面 +USE_CALIBER_PROMPT = """- 选用已发布口径(只在问数据里、look 过 caliber 之后): + {"op":"use_caliber","id":"c1","workflow_id":"…","version":3,"card":"口径卡节点 id","metrics":["指标id"],"inputs":{"字段":"值"}} + 照抄查看结果里给的写法,只改 id、metrics、inputs。系统按那一版生成取数节点(c1_<原 id>)和口径卡(节点 id 就是 c1), + 并把入口连到取数、取数连到口径卡;你**不要**自己写这几个节点,也不要改它们。接下来只需把口径卡连到报告 + (add_edge c1 → report),报告里用 [[m:指标id]] 引用。inputs 按口径的入口字段填(日期、门店这类问题里给出的条件), + 填不对会被拒收、原因会交回给你改;口径对不上问法时不要选用""" + #: 系统代为查看时写进记录的需求(界面上显示) SYSTEM_LOOK_FIX_NEED = "要修的工作流里,查库节点的 SQL 用到的表" SYSTEM_LOOK_UPGRADE_NEED = "要升级的工作流里,查库节点的 SQL 用到的表" @@ -66,22 +86,48 @@ SYSTEM_LOOK_UPGRADE_NEED = "要升级的工作流里,查库节点的 SQL 用 async def look_service(sources: list[Any], *, spec: ModelSpec | None, graph: Mapping[str, Any] | None = None, kinds: tuple[str, ...] = ("table", "capability"), answer: bool = False, - catalog_view: Any = None, trail: Mapping[str, Any] | None = None) -> LookService: + catalog_view: Any = None, trail: Mapping[str, Any] | None = None, + session: Any = None) -> LookService: """按入口组装这一轮的查看服务。读目录、读能力登记都用各自的短会话,开流前后都能调。 spec 是助手的模型规格:挑选模型第一次要用时才按它拿(关思考、额度按 look/pick.PICK_MAX_TOKENS)。graph 是现有工作流,概览里列出它查过的表。 answer:问数据(意图为回答),能力只列只读的。catalog_view:表详情里给哪一份数据目录(data/catalog_view.py),不给是当前目录。 trail:按需加入探查范围时的留痕(哪一轮对话:{conversation_id};谁取这次请求的身份)。 + kinds 里有 caliber 时用 session(调用方开流之前的会话)读已发布口径,问数据里另判能不能组合(look/calibers 的 compose)。 """ + from app.look.calibers import CaliberKind + picker = Picker(spec) made: list[Any] = [] if "table" in kinds: made.append(await TableKind.load(sources, graph=graph, picker=picker, catalog_view=catalog_view, trail=trail)) if "capability" in kinds: made.append(await CapabilityKind.load(picker=picker, read_only=answer)) + if "caliber" in kinds and session is not None: + made.append(await CaliberKind.load(session, picker=picker, compose=answer)) return LookService(made) +def composing(looks: LookService) -> bool: + """这一轮能不能选用已发布口径(问数据里读好了能组合的口径卡)。""" + kind = looks.kinds.get("caliber") + return kind is not None and getattr(kind, "options", None) is not None + + +def look_when(looks: LookService) -> str: + """「什么时候该看」:能选用已发布口径的问数据用改写过的那一份。""" + return LOOK_WHEN_ANSWER_PROMPT if composing(looks) else LOOK_WHEN_PROMPT + + +def composer(looks: LookService) -> Any | None: + """GraphApplier 用的组合器(ledger/compose.Composer);这一轮不能选用口径时为 None。""" + if not composing(looks): + return None + from app.ledger.compose import Composer + + return Composer(list(looks.kinds["caliber"].options)) + + async def section(looks: LookService) -> str: """system 里数据源那一节:各类对象的概览,有数据源时再加写 SQL 的硬性要求。什么都没有时是空串,不占提示词。""" overview = await looks.overview() @@ -105,6 +151,6 @@ async def system_look(looks: LookService, graph: Mapping[str, Any] | None, sourc __all__ = [ - "LOOK_WHEN_PROMPT", "SQL_RULES_PROMPT", "SYSTEM_LOOK_FIX_NEED", "SYSTEM_LOOK_UPGRADE_NEED", "graph_tables", - "look_service", "section", "system_look", + "LOOK_WHEN_ANSWER_PROMPT", "LOOK_WHEN_PROMPT", "SQL_RULES_PROMPT", "SYSTEM_LOOK_FIX_NEED", "SYSTEM_LOOK_UPGRADE_NEED", + "USE_CALIBER_PROMPT", "composer", "composing", "graph_tables", "look_service", "look_when", "section", "system_look", ] diff --git a/backend/app/api/copilot_gen.py b/backend/app/api/copilot_gen.py index e88c1b41..2acbeab4 100644 --- a/backend/app/api/copilot_gen.py +++ b/backend/app/api/copilot_gen.py @@ -255,14 +255,30 @@ class GraphApplier: - skipped_types:模型编出来的节点类型,收尾时说出来 patches:目录修改提案转不转(只有用户亲口说了数据事实的画布、问数据才转)。 + + composer:问数据里能选用已发布口径时(ledger/compose.Composer,next-round 02 做法 4)。use_caliber 由它按那一版确定性 + 实例化成取数节点和口径卡,这里落地:节点、连线照 add_node / add_edge 记进 seen(兜底重放照样重放得出来),入口连到 + 第一个取数节点(入口还没加的话,等入口加了再接);转给界面的只是那一条 use_caliber,带上 result(选用了哪一版、生成了 + 哪几个节点)。不合规的拒收:result 写原因、照样转给界面(过程里照实写一行),原因记进 refused,自查时交回模型改 + (GraphChecker.issues)。没有 composer 的入口(画布、发布前修复、升级)use_caliber 不认,照旧当认不出的操作丢掉。 """ def __init__(self, nodes: dict[str, dict[str, Any]], edges: list[dict[str, Any]], *, patches: bool = True, - questions: bool = False) -> None: + questions: bool = False, composer: Any = None) -> None: self.nodes = nodes self.edges = edges self.patches = patches self.questions_mode = questions + self.composer = composer + #: 选用口径实例化出来的段:[(第一个取数节点, 全部节点 id)],接入口用 + self.composed: list[tuple[str, list[str]]] = [] + #: 已经落地的 use_caliber(ledger/compose.signature),接着写时重发的同一个不再落地 + self._composed_ops: set[str] = set() + #: 系统接上的连线(入口 → 取数):模型再发一条一模一样的不重复加 + self._wired: list[dict[str, Any]] = [] + #: 拒收的 use_caliber:[{op, message}],自查时交回模型 + self.refused: list[dict[str, Any]] = [] + self._reported = 0 self.seen: list[dict[str, Any]] = [] self.tried: list[dict[str, Any]] = [] self.effective: list[dict[str, Any]] = [] @@ -305,11 +321,18 @@ class GraphApplier: self.autorun = op.get("run") is not False self.seen.append(op) return Applied(False, True) + if kind == "use_caliber" and self.composer is not None: + return self._use_caliber(op) + if kind == "add_edge" and self._was_wired(op.get("edge") or {}): + # 入口 → 取数这条系统已经接上了 + return Applied(False, False) if self._continuing and self._repeats(op): return Applied(False, False) self.seen.append(op) self.tried.append(op) changed = _apply_op(self.nodes, self.edges, op) + if changed and kind == "add_node": + self._wire() if changed: self.effective.append(op) nid = (op.get("node") or {}).get("id") if kind == "add_node" else op.get("id") @@ -321,6 +344,56 @@ class GraphApplier: self.skipped_types.append(str(bad)) return Applied(changed, changed) + def _use_caliber(self, op: dict[str, Any]) -> Applied: + """选用一份已发布口径(见类说明)。op 原地写上 result,原样转给界面。""" + from app.ledger.compose import ComposeRefused, signature + + sig = signature(op) + if sig in self._composed_ops: + return Applied(False, False) + try: + composed = self.composer.compose(op, taken=set(self.nodes)) + except ComposeRefused as e: + op["result"] = {"status": "refused", "reason": e.message} + self.refused.append({"op": {k: v for k, v in op.items() if k != "result"}, "message": e.message}) + return Applied(False, True, e.message) + self._composed_ops.add(sig) + primitive = [{"op": "add_node", "node": {"id": n["id"], "type": n["type"], "label": n["data"].get("label") or "", + "config": n["data"].get("config") or {}}} for n in composed.nodes] + primitive += [{"op": "add_edge", "edge": e} for e in composed.edges] + for item in primitive: + self.seen.append(item) + self.tried.append(item) + if _apply_op(self.nodes, self.edges, item): + self.effective.append(item) + ids = [str(n["id"]) for n in composed.nodes] + self.composed.append((ids[0], ids)) + if composed.op_id not in self._landed: + self._landed.append(composed.op_id) + self._wire() + op["result"] = composed.result() + return Applied(True, True) + + def _wire(self) -> None: + """选用口径生成的取数节点还没有上游、图里已经有入口的:系统把入口连到第一个取数节点。""" + entry = next((nid for nid, n in self.nodes.items() if n.get("type") == "input"), None) + if entry is None: + return + for first, _ in self.composed: + if first in self.nodes and not any(e["target"] == first for e in self.edges): + edge = {"source": entry, "target": first, "sourceHandle": None} + self.edges.append(edge) + self._wired.append(edge) + + def _was_wired(self, edge: dict[str, Any]) -> bool: + return any(w["source"] == edge.get("source") and w["target"] == edge.get("target") for w in self._wired) + + def unreported(self) -> list[dict[str, Any]]: + """还没交回过模型的拒收的选用,取走即算交回过(同 AppApplier.unreported)。""" + out = self.refused[self._reported:] + self._reported = len(self.refused) + return out + def _repeats(self, op: dict[str, Any]) -> bool: """接着写时和已落地完全相同的操作(look §2.5.5):已有的同一条连线、和已落地节点一模一样的节点、重发的同一个操作。""" kind = op.get("op") @@ -355,6 +428,7 @@ class GraphApplier: for e in graph.get("edges") or []] for op in self.seen: _apply_op(self.nodes, self.edges, op) + self._wire() class GraphChecker: @@ -387,8 +461,9 @@ class GraphChecker: async def issues(self) -> list[dict[str, Any]]: errors = self.blocking() + refused = _refused_issues(self.applier) if self.known is None: - return errors or [] + return [*refused, *(errors or [])] from app.engine.autofix import _sig if not self.applier.effective: @@ -405,6 +480,22 @@ class GraphChecker: # 应用的落地 # ========================================================================== +#: 选用口径被拒时交回模型的说法 +_REFUSED_FOR_MODEL = ("上一次的 use_caliber 被拒收:{message}。按原因改正后重新输出 use_caliber(id 可以沿用);这份口径对不上" + "问法的话就不要选用,交给 agent 查") + + +def _refused_issues(applier: Any) -> list[dict[str, Any]]: + """拒收的 use_caliber 还没交回过模型的那几条,形状同自查的问题(error 级:不改就少了这一块)。""" + if not isinstance(applier, GraphApplier): + return [] + from app.ledger.compose import REFUSED + + return [{"level": "error", "node_id": None, "edge_id": None, "field": None, "code": REFUSED, + "message": f"没有选用口径:{r['message']}", "for_model": _REFUSED_FOR_MODEL.format(message=r["message"])} + for r in applier.unreported()] + + APP_REPAIR_PROMPT = ( "这是你刚改好的应用草稿:\n{spec}\n\n" "应用检查(和发布同一套规则)发现下面这些问题:\n{issues}\n\n" diff --git a/backend/app/ledger/compose.py b/backend/app/ledger/compose.py new file mode 100644 index 00000000..15ff186d --- /dev/null +++ b/backend/app/ledger/compose.py @@ -0,0 +1,242 @@ +"""组合式问数:口径做骨架,Agent 填缺口(docs/design/next-round/02-口径账本.md 做法 4,拍板 L3)。 + +问数据的助手看到已发布口径(look 的 caliber,问数据里另给入口字段和「能不能组合」,不给 SQL)之后,可以输出一行 + + {"op":"use_caliber","id":"c1","workflow_id":"…","version":3,"card":"card","metrics":["gmv"],"inputs":{"start":"…"}} + +选用一份口径。**取数节点不让模型写**:由服务端按那一版确定性地内联实例化(ledger/derive.caliber_block,全站唯一的 +派生图生成器)——口径卡读的取数节点照抄,节点 id 加前缀「c1_」,模板里的 {{ input.字段 }} 按 inputs 渲染成字面 SQL +(和运行时同一个渲染器);口径卡 id 就是 c1,caliber_from 固定到那一版的那张卡、带改名映射 {原 id: c1_原 id} +(metrics 运行时按它改写式子)。取数节点首尾相接、最后一个接口径卡;入口连到第一个取数节点(GraphApplier 接上)。 +模型只管把口径卡 c1 接到报告、报告里引用 [[m:指标 id]]。 + +**为什么不用子图节点。** 子图的证据不交回父图(报告引用不到子图里的数),使用者也用不了子工作流(auth/chat_policy)。 +内联实例化只用到 tool 和 metrics 两种已放行的节点,证据照常封存,比对也照常复证(ledger/match 认出这些查询是助手 +选用的,标 composed「助手选用」,不标「等价已证明」:选哪份口径是助手凭问法判断的)。 + +**参数校验**(不合规拒收,原因交回模型改,GraphApplier.refusals): +- 只能选这一轮 look 能看到的那一版(每个工作流最新的已发布、未退役版本),而且那张卡能组合(derive.load_pinned:卡是 + 源头、每个输入都是取数节点第一行的格、取数模板只引用入口字段); +- inputs 只认口径入口声明的字段,没写的补缺省值,再过 apps/forms 同一套表单校验(类型、可选值、必填、格式); +- 参数要渲染进 SQL:写在引号里的不能带引号、反斜杠、换行;裸写的只能是数;写在注释里的不能带换行和注释结束符—— + 否则渲染出来的就不是那一版口径的 SQL 了; +- metrics 只能是这张卡上的指标 id;id 不能和图里已有的节点撞。 + +实例化是确定的:同样的版本、同样的操作得到一模一样的节点(测试锁住)。这里只是纯计算:版本快照由 look/calibers 的 +CaliberKind 在开流之前用会话读好(GraphApplier.apply 是同步的,流里不碰库)。 +""" +from __future__ import annotations + +import copy +import json +import re +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any + +from app.ledger.derive import Pinned, caliber_block + +#: 操作名 +OP = "use_caliber" +#: 拒收时的问题编号(自查交回模型、过程里照实写一行) +REFUSED = "ledger.use_caliber_refused" +#: 操作 id:口径卡的节点 id,取数节点加它做前缀。简短英文小写下划线(同节点 id 的约定) +_OP_ID = re.compile(r"^[a-z][a-z0-9_]{0,23}$") +_NUMBER = re.compile(r"^\s*-?\d+(?:\.\d+)?\s*$") + +#: 写给模型的拒收说明(也上界面:过程里那一行) +NOT_LISTED = "只能选用这一轮查看到的已发布口径:「{workflow}」v{version} 不在里面(口径要先 look,版本以查看结果为准)" +WRONG_VERSION = "「{workflow}」这一轮能选用的是 v{latest}(最新的已发布版本),不是 v{version}" +CARD_UNKNOWN = "「{workflow}」v{version} 里没有口径卡「{card}」(有:{cards})" +CARD_AMBIGUOUS = "「{workflow}」v{version} 有几张口径卡({cards}),请在 card 里写选用哪一张" +NOT_COMPOSABLE = "「{workflow}」v{version} 的口径卡「{card}」不能组合:{reason}" +BAD_ID = "use_caliber 的 id 要写成简短的英文小写加下划线(例如 c1),它就是口径卡的节点 id,当前为「{id}」" +ID_TAKEN = "use_caliber 的 id「{id}」和图里已有的节点「{node}」撞了,请换一个" +NO_METRICS = "use_caliber 的 metrics 要写这张口径卡上要用的指标 id(有:{metrics})" +METRIC_UNKNOWN = "口径卡「{card}」上没有指标「{metric}」(有:{metrics})" +FIELD_UNKNOWN = "口径「{workflow}」的入口没有字段「{name}」(有:{fields})" +INPUTS_NOT_OBJECT = "use_caliber 的 inputs 要写成字段和值的对照(JSON 对象)" +QUOTED_VALUE = "参数「{name}」写在 SQL 的引号里,值里不能有引号、反斜杠或换行" +BARE_VALUE = "参数「{name}」直接写在 SQL 里(没有引号),只能是数,当前为「{value}」" +COMMENT_VALUE = "参数「{name}」写在 SQL 的注释里,值里不能有换行或注释结束符" +TEMPLATE_UNREADABLE = "取数节点的 SQL 模板认不出参数写在哪:{reason}" + + +class ComposeRefused(Exception): + """不实例化这次选用:message 给模型看、也写进过程里那一行。""" + + def __init__(self, message: str) -> None: + super().__init__(message) + self.message = message + + +@dataclass(frozen=True) +class Option: + """这一轮能选用的一张口径卡:读好的那一版(pinned),或者不能组合的原因(reason)。""" + + workflow_id: str + workflow_name: str + version: int + level: str + node_id: str + card: str + pinned: Pinned | None = None + reason: str | None = None + + @property + def composable(self) -> bool: + return self.pinned is not None and self.reason is None + + +@dataclass +class Composed: + """一次选用实例化出来的东西:要加的节点、连线(取数首尾相接、最后接口径卡),交给界面和模型的结果。""" + + op_id: str + option: Option + nodes: list[dict[str, Any]] + edges: list[dict[str, Any]] + metrics: list[dict[str, Any]] + inputs: dict[str, Any] = field(default_factory=dict) + + @property + def fetch_ids(self) -> list[str]: + return [str(n["id"]) for n in self.nodes if n.get("type") != "metrics"] + + def result(self) -> dict[str, Any]: + """交给界面(过程里那一行)、记进这一轮的操作流的结果。不放 SQL、不放参数值(参数值助手自己写的,界面不必再给)。""" + from app.ledger.labels import LEVEL_TEXT + + return {"status": "ok", "workflow_id": self.option.workflow_id, "workflow_name": self.option.workflow_name, + "version": self.option.version, "level": self.option.level, + "level_text": LEVEL_TEXT.get(self.option.level, ""), "card": self.option.card, "card_id": self.op_id, + "fetches": self.fetch_ids, "metrics": [{"id": m["id"], "name": m["name"]} for m in self.metrics], + "nodes": len(self.nodes)} + + +def signature(op: Mapping[str, Any]) -> str: + """一次选用的身份(接着写时重发的同一个操作认得出来):去掉服务端写上的结果。""" + return json.dumps({k: v for k, v in op.items() if k != "result"}, ensure_ascii=False, sort_keys=True, default=str) + + +def _names(items: list[str]) -> str: + return "、".join(items[:12]) or "无" + + +def _slot_contexts(pinned: Pinned) -> dict[str, set[str]]: + """取数 SQL 模板里每个入口字段写在哪:{字段: {quoted / bare / comment}}。认不出的抛 ComposeRefused。""" + from app.data.sql_semantics import _NotComparable, _template_slots + + out: dict[str, set[str]] = {} + for node in pinned.fetches: + args = ((node.get("data") or {}).get("config") or {}).get("args") + sql = args.get("sql") if isinstance(args, dict) else None + if not isinstance(sql, str): + continue + try: + spans, _ = _template_slots(sql) + except _NotComparable as e: + raise ComposeRefused(TEMPLATE_UNREADABLE.format(reason=str(e))) from None + for _, _, slot in spans: + out.setdefault(slot.field, set()).add(slot.context) + return out + + +def _value_problem(name: str, value: Any, contexts: set[str]) -> str | None: + text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) \ + if isinstance(value, (dict, list)) else str(value) + if "quoted" in contexts and any(ch in text for ch in ("'", "\\", "\n", "\r")): + return QUOTED_VALUE.format(name=name) + if "bare" in contexts and not (isinstance(value, (int, float)) and not isinstance(value, bool)) \ + and not (isinstance(value, str) and _NUMBER.match(value)): + return BARE_VALUE.format(name=name, value=text[:40]) + if "comment" in contexts and ("\n" in text or "\r" in text or "*/" in text): + return COMMENT_VALUE.format(name=name) + return None + + +def check_inputs(pinned: Pinned, inputs: Any) -> dict[str, Any]: + """按口径入口的字段校验助手给的参数,补缺省值,交回要渲染进模板的那一份。不合规抛 ComposeRefused(一句一处)。""" + from app.apps.forms import input_schema, validate_form + + if inputs is None: + inputs = {} + if not isinstance(inputs, dict): + raise ComposeRefused(INPUTS_NOT_OBJECT) + fields = {str(f.get("name")).strip(): f for f in pinned.entry_fields if isinstance(f.get("name"), str)} + if unknown := [k for k in inputs if k not in fields]: + raise ComposeRefused(FIELD_UNKNOWN.format(workflow=pinned.workflow_name, name=unknown[0], + fields=_names(list(fields)))) + values = {name: copy.deepcopy(f.get("default")) for name, f in fields.items() + if f.get("default") not in (None, "")} + values.update({k: v for k, v in inputs.items() if v is not None and v != ""}) + if errors := validate_form(input_schema(list(pinned.entry_fields)), values): + raise ComposeRefused(";".join(e["message"] for e in errors)) + contexts = _slot_contexts(pinned) + for name, value in values.items(): + if problem := _value_problem(name, value, contexts.get(name, set())): + raise ComposeRefused(problem) + return values + + +def instantiate(option: Option, op: Mapping[str, Any], *, taken: set[str]) -> Composed: + """按选用的那一版确定性地实例化(见模块说明)。taken 是图里已有的节点 id。不合规抛 ComposeRefused。""" + pinned = option.pinned + if pinned is None or option.reason is not None: + raise ComposeRefused(NOT_COMPOSABLE.format(workflow=option.workflow_name, version=option.version, + card=option.card, reason=option.reason or "读不到这一版")) + op_id = str(op.get("id") or "").strip() + if not _OP_ID.match(op_id): + raise ComposeRefused(BAD_ID.format(id=op_id)) + wanted = [str(m) for m in op.get("metrics") or [] if isinstance(m, (str, int))] \ + if isinstance(op.get("metrics"), list) else [] + on_card = {str(m["id"]): m for m in pinned.metrics} + if not wanted: + raise ComposeRefused(NO_METRICS.format(metrics=_names(list(on_card)))) + if missing := [m for m in wanted if m not in on_card]: + raise ComposeRefused(METRIC_UNKNOWN.format(card=option.card, metric=missing[0], metrics=_names(list(on_card)))) + values = check_inputs(pinned, op.get("inputs")) + block = caliber_block(pinned, prefix=f"{op_id}_", card_id=op_id, inputs=values) + if clash := next((str(n["id"]) for n in block.nodes if str(n["id"]) in taken), None): + raise ComposeRefused(ID_TAKEN.format(id=op_id, node=clash)) + nodes = block.nodes + edges = [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])] + metrics = [{"id": m, "name": str(on_card[m].get("name") or m)} for m in wanted] + return Composed(op_id=op_id, option=option, nodes=nodes, edges=edges, metrics=metrics, inputs=values) + + +class Composer: + """GraphApplier 用的:这一轮能选用的口径卡(CaliberKind 在开流之前读好),按 use_caliber 实例化。""" + + def __init__(self, options: list[Option]) -> None: + self.options = options + + def pick(self, op: Mapping[str, Any]) -> Option: + workflow_id = str(op.get("workflow_id") or "").strip() + version = op.get("version") + cards = [o for o in self.options if o.workflow_id == workflow_id] + if not cards: + named = str(op.get("workflow_name") or workflow_id or "(没写工作流)") + raise ComposeRefused(NOT_LISTED.format(workflow=named, version=version)) + name = cards[0].workflow_name + latest = cards[0].version + if str(version) != str(latest): + raise ComposeRefused(WRONG_VERSION.format(workflow=name, latest=latest, version=version)) + card = str(op.get("card") or "").strip() + listed = [f"{o.card}({o.node_id})" for o in cards] + if card: + hit = next((o for o in cards if card in (o.node_id, o.card)), None) + if hit is None: + raise ComposeRefused(CARD_UNKNOWN.format(workflow=name, version=latest, card=card, + cards=_names(listed))) + return hit + if len(cards) > 1: + raise ComposeRefused(CARD_AMBIGUOUS.format(workflow=name, version=latest, cards=_names(listed))) + return cards[0] + + def compose(self, op: Mapping[str, Any], *, taken: set[str]) -> Composed: + return instantiate(self.pick(op), op, taken=taken) + + +__all__ = ["OP", "REFUSED", "ComposeRefused", "Composed", "Composer", "Option", "check_inputs", "instantiate", + "signature"] diff --git a/backend/app/ledger/derive.py b/backend/app/ledger/derive.py index 835fabfa..b3c41202 100644 --- a/backend/app/ledger/derive.py +++ b/backend/app/ledger/derive.py @@ -16,7 +16,8 @@ cell(nodes.X, 0, '列')、X 是查库的调用工具节点(look/calibers.card_ 模板只引用入口字段({{ input.字段 }})——引用 vars.、nodes.、模板函数(file_text……)的,拷出来就拿不到同样的值,照实 拒收、给原因(NotDerivable)。工作流、版本、节点不在了也照实说。 -**这一波实现的**:caliber_probe —— 一份口径的取数 + 口径卡(评测口径题的期望)。 +**已实现的**:caliber_probe —— 一份口径的取数 + 口径卡(评测口径题的期望);reconcile —— 口径对账(第 3 波, +reconcile_graph);组合式问数用的 caliber_block(card_id, inputs)(第 3 波)。 **扩展点**(第 3 波的账本按这里扩,不另写生成器): - 口径对账(02 做法 6):assemble("reconcile", [ours, caliber_block(pinned)], tail=[对账卡])。ours 是「这次的取数」 @@ -24,9 +25,10 @@ cell(nodes.X, 0, '列')、X 是查库的调用工具节点(look/calibers.card_ 相对差,式子引用 cell(nodes.ours_q1, 0, '列') 和口径卡的指标,on_missing=null),出口的契约写 metrics_from。 - 口径召回(02 做法 7):assemble("recall", [caliber_block(old, prefix="old_"), caliber_block(new, prefix="new_")], tail=[召回卡])。同一张图里放两份口径,取数节点 id 会撞:caliber_block 带 prefix 时把拷出来的节点改名,口径卡的 - caliber_from 带上改名映射 nodes={原 id: 新 id}。**运行时认这个映射是 02 做法 4(metrics._pinned_caliber 按 AST 改写 - 式子里的 cell(nodes.X…) 和 nodes.X),归第 3 波的账本包**;在那之前带前缀的段跑起来口径卡取不到输入(缺输入,照实 - 失败,不会算错),这一波只有不带前缀的 caliber_probe 有调用方。 + caliber_from 带上改名映射 nodes={原 id: 新 id},运行时 metrics._pinned_caliber 按语法树改写式子里的 cell(nodes.X…) + 和 nodes.X(第 3 波起)。 +- 组合式问数(02 做法 4,ledger/compose.py):不经 assemble(拷进的是问数据那张图),只用 caliber_block(prefix=…, + card_id=…, inputs=…):取数节点改名、模板按助手给的参数渲染成字面 SQL,口径卡带改名映射。 - 新的派生种类登记进 KINDS,入口字段、出口、首尾相接都走 assemble,不在调用方拼节点。 派生图都是探索运行(正式运行只从已发布未退役的版本发起);来源(origin_kind)由调用方定:评测 eval、对账 reconcile、 @@ -42,7 +44,7 @@ from typing import Any from sqlalchemy.ext.asyncio import AsyncSession -#: 派生图的种类。这一波实现 caliber_probe;reconcile、recall 归第 3 波的账本(见模块说明的扩展点) +#: 派生图的种类。caliber_probe、reconcile 已实现;recall 归第 4 波(见模块说明的扩展点) KINDS = ("caliber_probe", "reconcile", "recall") #: 不能派生的原因的机器码 @@ -242,19 +244,39 @@ def _node(nid: str, ntype: str, label: str, **config: Any) -> dict[str, Any]: return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label, "config": config}} -def caliber_block(pinned: Pinned, *, prefix: str = "", upgrade_policy: str | None = None) -> Block: +def render_inputs(value: Any, inputs: Mapping[str, Any]) -> Any: + """配置里每一段字的 {{ input.字段 }} 按 inputs 渲染成字面值(和运行时同一个渲染器 engine/expressions.render_template)。 + load_pinned 已经保证取数节点的模板只引用入口字段。别的值原样。""" + from app.engine.expressions import render_template + + if isinstance(value, str): + return render_template(value, {"input": dict(inputs)}) if "{{" in value else value + if isinstance(value, dict): + return {k: render_inputs(v, inputs) for k, v in value.items()} + if isinstance(value, list): + return [render_inputs(v, inputs) for v in value] + return value + + +def caliber_block(pinned: Pinned, *, prefix: str = "", upgrade_policy: str | None = None, + card_id: str | None = None, inputs: Mapping[str, Any] | None = None) -> Block: """一份口径:拷出取数节点(id、配置原样;prefix 不为空时改名为 prefix + 原 id)+ 一张 caliber_from 固定到那一版的 口径卡(id 同原卡,带前缀时同样改名;「缺输入时」照抄原卡)。 upgrade_policy:钉住的版本有了新的已发布版本时这一段怎么处置(recompute / dual / incomparable,没有缺省)。写在 本地口径卡上,判断走和正式运行同一个 engine/governance.unresolved_caliber_upgrades;不给就不写(有新版本时那个 - 判断报「待处置」)。prefix 的改名映射要等 metrics 运行时认 caliber_from.nodes(见模块说明)。""" + 判断报「待处置」)。带前缀时口径卡的 caliber_from 带改名映射 nodes(metrics 运行时按它改写式子,见模块说明)。 + + 组合式问数(ledger/compose.py)另给两项:card_id 是口径卡在新图里的 id(缺省 prefix + 原卡 id);inputs 给了的话, + 取数节点配置里的 {{ input.字段 }} 按它渲染成字面值——拷进问数据的图里,那张图的入口没有口径的入口字段。""" rename = {str(n["id"]): f"{prefix}{n['id']}" for n in pinned.fetches} if prefix else {} nodes: list[dict[str, Any]] = [] for original in pinned.fetches: node = copy.deepcopy(original) node["id"] = rename.get(str(node["id"]), str(node["id"])) node["position"] = {"x": 0, "y": 0} + if inputs is not None and isinstance(node.get("data"), dict): + node["data"]["config"] = render_inputs(node["data"].get("config") or {}, inputs) nodes.append(node) source = pinned.ref() if rename: @@ -265,7 +287,7 @@ def caliber_block(pinned: Pinned, *, prefix: str = "", upgrade_policy: str | Non config["on_missing"] = on_missing if upgrade_policy: config["upgrade_policy"] = upgrade_policy - card_id = f"{prefix}{pinned.node_id}" + card_id = card_id or f"{prefix}{pinned.node_id}" nodes.append(_node(card_id, "metrics", pinned.card_title, **config)) return Block(nodes=nodes, card_id=card_id, rename=rename, source=pinned.describe()) diff --git a/backend/app/ledger/labels.py b/backend/app/ledger/labels.py index 5511ca6d..7b791abc 100644 --- a/backend/app/ledger/labels.py +++ b/backend/app/ledger/labels.py @@ -2,7 +2,7 @@ 标签四种(KINDS): - caliber:来自口径「X」vN。how 是怎么认的:independent「等价已证明」(这次 Agent 自己写的 SQL 被证明和口径的取数等价)、 - composed「助手选用」(助手按口径组合出来的;组合在第 3 波,这一波只留这个值)。 + composed「助手选用」(助手 use_caliber 按口径组合出来的取数,证明了和那一版一致:ledger/match 的 composed)。 - related:相关口径——同一个数据源、查了同样的表的已发布口径,但不等价;附差在哪(explain_sql_diff 的条目)。 - reasoning:这次的推理——没有相关的已发布口径。 - unknown:没比对、比对没做完(超时、解析失败)、快照读不出来。 @@ -72,7 +72,8 @@ def _related(query: Mapping[str, Any], *, reason: str | None = None) -> dict[str def _caliber(cand: Mapping[str, Any], **extra: Any) -> dict[str, Any]: - return {"kind": "caliber", "how": "independent", "caliber": cand.get("caliber"), + return {"kind": "caliber", "how": "composed" if cand.get("how") == "composed" else "independent", + "caliber": cand.get("caliber"), "workflow_id": cand.get("workflow_id"), "version": cand.get("version"), "level": cand.get("level"), "binding": dict(cand.get("binding") or {}), **extra} @@ -183,13 +184,15 @@ def metric_label(card: Mapping[str, Any] | None, metric_id: Any, queries: Mappin common = set.intersection(*proven_keys) if proven_keys else set() nearby = _brief([c for q in queries_found for c in q.get("candidates") or [] if c.get("status") in ("proven", "related")]) + queried = {"queries": [str(i["artifact"]) for i in from_queries]} if len(from_queries) < len(inputs): - return {"kind": "related", "related": nearby, "reason": INPUTS_ELSEWHERE} if nearby else {"kind": "reasoning"} + return {"kind": "related", "related": nearby, "reason": INPUTS_ELSEWHERE, **queried} if nearby \ + else {"kind": "reasoning", **queried} if not common: if all(proven_keys): - return {"kind": "related", "related": nearby, "reason": MIXED_CALIBERS} + return {"kind": "related", "related": nearby, "reason": MIXED_CALIBERS, **queried} related = next((q for q in queries_found if q.get("status") == "related"), None) - return _related(related) if related is not None else {"kind": "reasoning"} + return {**_related(related), **queried} if related is not None else {"kind": "reasoning", **queried} reason = FORMULA_DIFFERS for key in sorted(common): chosen = [next(c for c in _proven(q) if c.get("caliber") == key) for q in queries_found] @@ -218,9 +221,14 @@ def metric_label(card: Mapping[str, Any] | None, metric_id: Any, queries: Mappin if theirs == mine), None) if hit is None: continue - return {**_caliber(chosen[0], card=hit[0], metric=hit[1]), "binding": binding} + label = {**_caliber(chosen[0], card=hit[0], metric=hit[1]), "binding": binding, + "queries": [str(i["artifact"]) for i in from_queries]} + if any(c.get("how") == "composed" for c in chosen): + # 几个输入里有一个是助手选用的,整个指标就按助手选用说(不能说成都是独立写出来的) + label["how"] = "composed" + return label return {"kind": "related", "related": _brief([c for q in queries_found for c in _proven(q) - if c.get("caliber") in common]), "reason": reason} + if c.get("caliber") in common]), "reason": reason, **queried} def _brief(cands: list[Mapping[str, Any]]) -> list[dict[str, Any]]: diff --git a/backend/app/ledger/match.py b/backend/app/ledger/match.py index 109d37d8..96605533 100644 --- a/backend/app/ledger/match.py +++ b/backend/app/ledger/match.py @@ -10,6 +10,12 @@ version 记。系统派生的运行(评测、对账、召回)不比:它们 MAX_CANDIDATES 份(按工作流、版本、节点排好的先后)。 **怎么比。** data/sql_semantics.match_template:先绑定参数(只是启发),再按绑定渲染口径的取数 SQL 交 explain_sql_diff 证明。 + +**助手选用的(composed)。** 问数据的助手 use_caliber 选用口径时,取数节点是服务端照那一版拷进来的(ledger/compose.py), +口径卡的 caliber_from 带着改名映射 {原 id: 新 id}。这几个节点交回的查询照样要证明:证明了的那一份记 how=composed,查询 +状态记 composed——数确实来自口径,但「这份口径答的就是这个问题」是助手凭问法判断的,不能说成「等价已证明」(拍板 L1: +自动正式出具只给独立等价的)。没能证明的(拷进来之后在画布上被改过)照常是相关口径,另写一句为什么。映射从这次运行 +封存的图里读(composed_nodes),比对时把那一份口径排在最前面,不会因为候选太多被挤掉。 schema 用这条查询当时冻结的表结构(表结构快照),列的中文名取同一份快照里冻结的数据目录。只读封存范围内的快照(api/evidence 的 _sealed 读法),读不出、被改过的快照不比,记 skipped。 @@ -68,6 +74,7 @@ SNAPSHOT_MISSING = "查询快照读不出来,不比对" NO_SQL = "查询快照里没有 SQL,不比对" PARSE_FAILED = "这次的 SQL 无法解析,没有比对" MERGED = "合并查询的格不和口径比对(它的数来自各个输入的查询)" +COMPOSED_UNPROVEN = "这条查询出自助手选用的口径,但和口径的取数没能证明一致(可能被改过)" MORE_CANDIDATES = "另有 {n} 份相关口径没有比对(每条查询最多比 {max} 份)" #: 不比对的原因(GET 账本时照实说) @@ -304,11 +311,32 @@ def _skipped(caliber: Caliber, fetch: Fetch, reason: str) -> dict[str, Any]: "level": caliber.level, "node_id": fetch.node_id, "status": "skipped", "reason": reason} -def compare_queries(queries: list[Query], calibers: list[Caliber], *, deadline: float | None = None - ) -> list[dict[str, Any]]: +def composed_nodes(graph: Any) -> dict[str, tuple[str, str]]: + """这次运行的图里助手选用口径拷进来的取数节点:{这张图里的节点 id: (「工作流@版本」, 那一版里的原 id)}。从口径卡的 + caliber_from.nodes 读(ledger/compose.py 实例化时写的);没有改名映射的口径卡不算(蓝图复用口径时取数是模型写的)。""" + out: dict[str, tuple[str, str]] = {} + for node in (graph or {}).get("nodes") or [] if isinstance(graph, dict) else []: + if not isinstance(node, dict) or node.get("type") != "metrics": + continue + cfg = (node.get("data") or {}).get("config") if isinstance(node.get("data"), dict) else None + ref = cfg.get("caliber_from") if isinstance(cfg, dict) else None + rename = ref.get("nodes") if isinstance(ref, dict) else None + version = ref.get("workflow_version") if isinstance(ref, dict) else None + if not isinstance(rename, dict) or not ref.get("workflow_id") or not str(version or "").isdigit(): + continue + key = ledger_labels.caliber_key(str(ref["workflow_id"]), int(version)) + for old, new in rename.items(): + if isinstance(old, str) and isinstance(new, str): + out.setdefault(new, (key, old)) + return out + + +def compare_queries(queries: list[Query], calibers: list[Caliber], *, deadline: float | None = None, + composed: dict[str, tuple[str, str]] | None = None) -> list[dict[str, Any]]: """每条查询和预筛出来的口径取数逐个比(match_template),给出 [{artifact, node_id, source, tables, status, reason?, - candidates}]。status:proven(和某一份等价)/ related(有同源同表的口径,都不等价)/ none(没有相关的口径)/ skipped - (没比完:超时、解析失败、快照读不出)。纯计算,从不抛异常。评测逐题比 SQL 也调它。""" + candidates}]。status:proven(和某一份等价)/ composed(助手选用的那一份,证明了)/ related(有同源同表的口径,都不 + 等价)/ none(没有相关的口径)/ skipped(没比完:超时、解析失败、快照读不出)。composed 是 composed_nodes 的结果, + 不给就没有助手选用的。纯计算,从不抛异常。评测逐题比 SQL 也调它。""" from app.data.sql_semantics import match_template, normalize_sql out: list[dict[str, Any]] = [] @@ -318,7 +346,11 @@ def compare_queries(queries: list[Query], calibers: list[Caliber], *, deadline: if query.problem: out.append({**row, "status": "skipped", "reason": query.problem, "candidates": []}) continue + chosen = (composed or {}).get(str(query.node_id or "")) pool = [(c, f) for c in calibers for f in c.fetches if f.source == query.source and f.tables & query.tables] + if chosen is not None: + # 助手选用的那一份排最前面:候选多的时候也一定比到它 + pool.sort(key=lambda cf: (cf[0].key, cf[1].node_id) != chosen) if not pool: out.append({**row, "status": "none", "candidates": []}) continue @@ -337,9 +369,18 @@ def compare_queries(queries: list[Query], calibers: list[Caliber], *, deadline: logger.exception("口径比对出错(运行查询 %s,口径 %s)", query.artifact[:12], caliber.key) candidates.append(_skipped(caliber, fetch, "比对出错")) continue - candidates.append(_candidate(caliber, fetch, m)) + cand = _candidate(caliber, fetch, m) + if chosen is not None and (caliber.key, fetch.node_id) == chosen: + if cand["status"] == "proven": + cand["how"] = "composed" + else: + cand.setdefault("reason", COMPOSED_UNPROVEN) + candidates.append(cand) statuses = {c["status"] for c in candidates} status = "proven" if "proven" in statuses else "skipped" if "skipped" in statuses else "related" + if status == "proven" and any(c.get("how") == "composed" for c in candidates): + # 证明了的是助手选用的那一份:数来自口径,但不是这次独立写出来的(见模块说明)。同时和别的口径等价的也按选用的算 + status = "composed" if len(pool) > MAX_CANDIDATES: row["note"] = MORE_CANDIDATES.format(n=len(pool) - MAX_CANDIDATES, max=MAX_CANDIDATES) if status == "skipped": @@ -359,7 +400,7 @@ def compute(sealed: Any, calibers: list[Caliber], kinds: dict[str, str | None], results = [{"artifact": q.artifact, "node_id": q.node_id, "source": q.source, "tables": sorted(q.tables), "status": "skipped", "reason": SEAL_BROKEN, "candidates": []} for q in queries] else: - results = compare_queries(queries, calibers, deadline=deadline) + results = compare_queries(queries, calibers, deadline=deadline, composed=composed_nodes(sealed.graph)) used = {c["caliber"] for q in results for c in q["candidates"]} considered = [c for c in calibers if c.key in used] by_key = {c.key: {"level": c.level, "fields": c.summary()["fields"], "expressions": list(c.expressions)} @@ -558,5 +599,5 @@ async def shutdown() -> None: __all__ = ["BACKFILL_DAYS", "CONCURRENCY", "EXPLORE_ORIGINS", "TIMEOUT_S", "Caliber", "Fetch", "Query", "backfill", - "caliber_of", "compare_queries", "compute", "drain", "ineligible", "load_calibers", "match_run", "pending", - "read_queries", "schedule", "shutdown", "start_backfill", "wanted"] + "caliber_of", "compare_queries", "composed_nodes", "compute", "drain", "ineligible", "load_calibers", + "match_run", "pending", "read_queries", "schedule", "shutdown", "start_backfill", "wanted"] diff --git a/backend/app/ledger/store.py b/backend/app/ledger/store.py index 3fd3aff2..5846eb51 100644 --- a/backend/app/ledger/store.py +++ b/backend/app/ledger/store.py @@ -28,8 +28,10 @@ from app.db.models import Run, RunEvent #: 工件的种类和内容格式 KIND = "caliber_match" FORMAT = "agentlab.caliber_match/1" -#: 比对算法的版本:绑定、证明、标签的规则改了就加一,界面和统计据此分得清是哪一版算法比的 -ALGO = "1" +#: 比对算法的版本:绑定、证明、标签的规则改了就加一,界面和统计据此分得清是哪一版算法比的。 +#: 2(第 3 波):认出助手选用的口径(查询 composed、标签 how=composed),指标的标签记它取自哪几条查询(queries,认证队列 +#: 认「被报告引用的查询」用) +ALGO = "2" #: 触发方式(见模块说明) TRIGGERS = ("sealed", "backfill", "on_demand") diff --git a/backend/app/ledger/view.py b/backend/app/ledger/view.py index 5e827e04..6bfec90c 100644 --- a/backend/app/ledger/view.py +++ b/backend/app/ledger/view.py @@ -73,6 +73,8 @@ def _query_view(query: dict[str, Any], hider: _Hide, names: dict[str, str]) -> d for cand in query.get("candidates") or []: item = ledger_labels.related_view(cand, hide=hider.hide, shown=hider.shown, names=names) item["status"] = cand.get("status") + if cand.get("how"): + item["how"] = cand["how"] if cand.get("columns") is not None: item["columns"] = cand["columns"] cands.append(item) diff --git a/backend/app/look/calibers.py b/backend/app/look/calibers.py index fce2daf4..3a5ea8f0 100644 --- a/backend/app/look/calibers.py +++ b/backend/app/look/calibers.py @@ -9,6 +9,11 @@ 读别的(整形、沙箱、模型写的、按别的行号取)的卡照实说不能复用,请按表重新对。 点名写法:source 写工作流名(或 id),name 写指标名(或指标 id);只写 source 列那个工作流的全部指标。 + +**问数据里**(compose=True,next-round 02 做法 4):同一套口径,另给每张卡的入口字段(类型、必填、可选值、格式、缺省值, +同 apps/describe 的写法)和「能不能组合」,能组合的写出 use_caliber 的写法;仍然不给 SQL(SQL 里可能写着遮罩值,组合 +时取数节点由服务端照抄,见 ledger/compose.py)。能不能组合由 ledger/derive.load_pinned 判(和对账、评测同一个认法), +读好的版本快照交给 GraphApplier(流里不碰库)。蓝图助手不走这一支,行为不变。 """ from __future__ import annotations @@ -32,6 +37,13 @@ DETAIL_REUSE_PROMPT = (" 复用写法(「看哪些数」这一项的 reuse " 这张卡读:{inputs}。实例化时那个库的取数节点就叫这个名字、交出这几列,复用才算得出来") DETAIL_INPUT_PROMPT = "{node}({tool})的列 {columns}" DETAIL_NOT_REUSABLE_PROMPT = " 不能复用:{reason}。请按表重新对" +#: 问数据里(compose)每张卡写一次:入口字段、能不能组合 +DETAIL_FIELDS_PROMPT = " 口径「{workflow}」v{version} 的入口字段:{fields}" +DETAIL_FIELD_PROMPT = "{name}({bits}){desc}" +DETAIL_NO_FIELDS_PROMPT = " 口径「{workflow}」v{version} 的入口没有字段" +DETAIL_COMPOSE_PROMPT = (" 能组合:选用写法 {op}(id 自己起,它就是口径卡的节点 id;inputs 按上面的入口字段填,没写的取缺省值;" + "metrics 写要用的指标 id)") +DETAIL_NOT_COMPOSABLE_PROMPT = " 不能组合:{reason}。这份口径只能作为参考,查库交给 agent" BRIEF_PROMPT = "· {name}({workflow} v{version}):字数超过上限,只列名字,要看指标式时点名再 look" MISSING_PROMPT = "没找到口径:{items}(只能查看已发布且未退役的版本里的口径卡;别拿名字相近的顶替)" INDEX_LINE_PROMPT = "{workflow}|{card}|{name}({metric})|{unit}" @@ -145,17 +157,36 @@ def views_of(workflow_id: str, workflow_name: str, version: Any) -> list[Caliber return out +def field_text(f: dict[str, Any]) -> str: + """入口字段写给模型的一段:名字(类型,必填,可选值,格式,缺省值):说明。同 apps/describe 的写法,多写缺省值。""" + bits = [str(f.get("type") or "string")] + if f.get("required") and f.get("default") in (None, ""): + bits.append("必填") + if isinstance(f.get("enum"), list): + bits.append("可选值 " + " / ".join(str(v) for v in f["enum"][:10])) + if f.get("format"): + bits.append(f"格式 {f['format']}") + if f.get("default") not in (None, ""): + bits.append(f"缺省 {f['default']}") + desc = f":{f['description']}" if f.get("description") else "" + return DETAIL_FIELD_PROMPT.format(name=f.get("name"), bits=",".join(bits), desc=desc) + + class CaliberKind: kind = "caliber" label = "口径" - def __init__(self, items: list[CaliberView], *, picker: Picker | None = None) -> None: + def __init__(self, items: list[CaliberView], *, picker: Picker | None = None, + options: list[Any] | None = None) -> None: self.items = items self.picker = picker + #: 问数据里(compose):每张卡能不能组合(ledger/compose.Option),没开组合时为 None + self.options = options @classmethod - async def load(cls, session: Any, *, picker: Picker | None = None) -> CaliberKind: - """读每个工作流最新的已发布且未退役的版本里的口径卡。用调用方的会话,开流之前读好。""" + async def load(cls, session: Any, *, picker: Picker | None = None, compose: bool = False) -> CaliberKind: + """读每个工作流最新的已发布且未退役的版本里的口径卡。用调用方的会话,开流之前读好。compose:问数据里,另把每张卡 + 的那一版读好、判能不能组合(见模块说明)。""" from sqlalchemy import select from app.apps import versions as app_versions @@ -166,7 +197,13 @@ class CaliberKind: latest = await app_versions.latest_published(session, wf.id) if latest is not None: items += views_of(wf.id, wf.name, latest) - return cls(items, picker=picker) + return cls(items, picker=picker, options=await _options(session, items) if compose else None) + + def option_of(self, item: CaliberView) -> Any | None: + if self.options is None: + return None + return next((o for o in self.options if (o.workflow_id, o.version, o.node_id) == + (item.workflow_id, item.version, item.node_id)), None) def _workflows(self) -> dict[str, list[CaliberView]]: out: dict[str, list[CaliberView]] = {} @@ -243,14 +280,18 @@ class CaliberKind: missing: list[LookTarget] = ()) -> tuple[str, list[dict[str, Any]]]: lines: list[str] = [] used = 0 + #: 问数据里每张卡的入口字段、组合写法只写一次(同一张卡的几个指标挨着列) + seen: set[tuple[str, int, str]] = set() for item, _how in objects: block = [DETAIL_HEAD_PROMPT.format(name=item.name, metric=item.metric_id, unit=f",单位 {item.unit}" if item.unit else "", workflow=item.workflow_name, version=item.version, card=item.card, caliber=item.caliber), DETAIL_EXPR_PROMPT.format(expression=item.expression)] - reuse = item.reuse() - if reuse is not None: + option = self.option_of(item) + if option is not None: + block += _compose_lines(item, option, seen) + elif (reuse := item.reuse()) is not None: block.append(DETAIL_REUSE_PROMPT.format( reuse=json.dumps({k: v for k, v in reuse.items() if k != "inputs"}, ensure_ascii=False), inputs=";".join(DETAIL_INPUT_PROMPT.format(node=n, tool=t, columns="、".join(cols)) @@ -281,6 +322,50 @@ class CaliberKind: return None, "只能复用已发布且未退役的版本里的口径卡(look 给出的那一版)" +async def _options(session: Any, items: list[CaliberView]) -> list[Any]: + """每张卡(工作流、版本、卡)读一次那一版、判能不能组合:ledger/derive.load_pinned(和对账、评测同一个认法),再看 + 取数 SQL 模板里的参数认不认得出写在哪(ledger/compose 校验参数要用)。""" + from app.ledger.compose import ComposeRefused, Option, _slot_contexts + from app.ledger.derive import NotDerivable, load_pinned + + out: list[Any] = [] + for item in items: + if any((o.workflow_id, o.version, o.node_id) == (item.workflow_id, item.version, item.node_id) for o in out): + continue + base = {"workflow_id": item.workflow_id, "workflow_name": item.workflow_name, "version": item.version, + "level": item.level, "node_id": item.node_id, "card": item.card} + try: + pinned = await load_pinned(session, item.workflow_id, item.version, item.node_id) + _slot_contexts(pinned) + except NotDerivable as e: + out.append(Option(**base, reason=e.message)) + continue + except ComposeRefused as e: + out.append(Option(**base, reason=e.message)) + continue + out.append(Option(**base, pinned=pinned)) + return out + + +def _compose_lines(item: CaliberView, option: Any, seen: set[tuple[str, int, str]]) -> list[str]: + """问数据里一张卡的入口字段和组合写法(同一张卡只写一次)。""" + key = (item.workflow_id, item.version, item.node_id) + if key in seen: + return [] + seen.add(key) + if not option.composable: + return [DETAIL_NOT_COMPOSABLE_PROMPT.format(reason=option.reason)] + fields = [f for f in option.pinned.entry_fields if f.get("name")] + lines = [DETAIL_FIELDS_PROMPT.format(workflow=item.workflow_name, version=item.version, + fields=";".join(field_text(f) for f in fields)) + if fields else DETAIL_NO_FIELDS_PROMPT.format(workflow=item.workflow_name, version=item.version)] + example = {"op": "use_caliber", "id": "c1", "workflow_id": item.workflow_id, "version": item.version, + "card": item.node_id, "metrics": [m["id"] for m in option.pinned.metrics][:6], + "inputs": {str(f["name"]): "…" for f in fields}} + lines.append(DETAIL_COMPOSE_PROMPT.format(op=json.dumps(example, ensure_ascii=False))) + return lines + + async def verify_reuse(session: Any, ref: dict[str, Any]) -> dict[str, Any]: """蓝图存的时候按库里那一版核对复用的口径卡:已发布且未退役、是源头的口径卡、有这个指标、能复用。交回补上 inputs 的 reuse;不行抛 BpRefused(bp.data_unmapped)。用户在卡片上选的、助手提的都过这一道。""" diff --git a/backend/tests/test_ledger_compose.py b/backend/tests/test_ledger_compose.py new file mode 100644 index 00000000..0c3405b0 --- /dev/null +++ b/backend/tests/test_ledger_compose.py @@ -0,0 +1,294 @@ +"""组合式问数:use_caliber 选用已发布口径,服务端按那一版确定性内联实例化(next-round 02 做法 4,ledger/compose.py)。 + +- 实例化是确定的:同一版、同一个操作得到一模一样的节点;取数节点照抄、id 加前缀、模板按参数渲染成字面 SQL,口径卡 id + 就是操作 id、caliber_from 带改名映射;取数首尾相接再接口径卡,入口连到第一个取数节点; +- 参数按口径入口的字段校验(未知字段、缺必填、类型、引号里的值带引号、裸写的值不是数),不合规拒收、原因交回模型; + 只能选这一轮查看到的那一版、能组合的卡、卡上的指标,id 不能撞; +- 问数据的查看对象多了口径:给入口字段和「能不能组合」,不给 SQL;「什么时候该看」换成问数据那一份;使用者不给; +- 走一遍问数据的生成(剧本模型)再真跑出来:比对器把这些数标成 composed「助手选用」,整题 how=composed。 +数据是虚构店铺库。 +""" +from __future__ import annotations + +import json + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.api import copilot_context +from app.api.copilot_gen import GraphApplier, GraphChecker +from app.db.base import SessionLocal +from app.engine.runner import run_manager +from app.engine.schema import GraphSpec, validate_graph +from app.ledger import compose +from app.ledger import match as ledger_match +from app.ledger import store +from app.look.calibers import CaliberKind +from app.main import app +from tests import ledger_samples as S + + +@pytest.fixture(autouse=True) +async def engine_up(tmp_path): + await run_manager.setup() + await S.fresh_source(tmp_path / "shop.db") + yield + await ledger_match.drain() + await run_manager.shutdown() + + +@pytest.fixture +async def client(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + + +def use(wf: str, **extra) -> dict: + return {"op": "use_caliber", "id": "c1", "workflow_id": wf, "version": 1, "metrics": ["gmv"], + "inputs": {"start": "2026-09-01", "end": "2026-09-08"}, **extra} + + +async def composer() -> compose.Composer: + async with SessionLocal() as session: + kind = await CaliberKind.load(session, compose=True) + return compose.Composer(list(kind.options)) + + +# -------------------------------------------------------------------------- +# 实例化 +# -------------------------------------------------------------------------- + + +async def test_instantiation_is_deterministic_and_copies_the_pinned_fetch(): + wf = await S.publish() + made = (await composer()).compose(use(wf), taken={"start"}) + again = (await composer()).compose(use(wf), taken={"start"}) + assert made.nodes == again.nodes and made.edges == again.edges + fetch, card = made.nodes + assert fetch["id"] == "c1_fetch" and fetch["type"] == "tool" + assert fetch["data"]["config"]["tool"] == S.tool() + assert fetch["data"]["config"]["args"]["sql"] == S.TEMPLATE.replace("{{ input.start }}", "2026-09-01").replace( + "{{ input.end }}", "2026-09-08") + assert card["id"] == "c1" and card["type"] == "metrics" and card["data"]["label"] == "card" + assert card["data"]["config"]["caliber_from"] == {"workflow_id": wf, "workflow_version": 1, "node_id": "card", + "nodes": {"fetch": "c1_fetch"}} + assert made.edges == [{"source": "c1_fetch", "target": "c1"}] + # 缺省值补上了(store 有缺省 all),不进结果 + assert made.inputs == {"start": "2026-09-01", "end": "2026-09-08", "store": "all"} + result = made.result() + assert result["status"] == "ok" and result["card_id"] == "c1" and result["fetches"] == ["c1_fetch"] + assert result["level_text"] == "受管" and result["metrics"] == [{"id": "gmv", "name": "销售额"}] + assert "sql" not in json.dumps(result).lower() + + +@pytest.mark.parametrize(("change", "words"), [ + ({"workflow_id": "nope"}, "只能选用这一轮查看到的已发布口径"), + ({"version": 2}, "能选用的是 v1"), + ({"card": "other"}, "没有口径卡「other」"), + ({"id": "C 1"}, "简短的英文小写"), + ({"metrics": []}, "metrics 要写"), + ({"metrics": ["profit"]}, "没有指标「profit」"), + ({"inputs": {"start": "2026-09-01", "end": "2026-09-08", "city": "x"}}, "入口没有字段「city」"), + ({"inputs": {"start": "2026-09-01"}}, "请填写「end」"), + ({"inputs": {"start": "2026-09-01' OR '1'='1", "end": "2026-09-08"}}, "引号里,值里不能有引号"), + ({"inputs": "start=2026-09-01"}, "inputs 要写成"), +]) +async def test_bad_choices_are_refused_with_a_reason(change, words): + wf = await S.publish() + op = use(wf, **change) if change.get("workflow_id") != "nope" else {**use(wf), **change} + with pytest.raises(compose.ComposeRefused) as e: + (await composer()).compose(op, taken={"start"}) + assert words in e.value.message, e.value.message + + +async def test_bare_slots_take_numbers_only_and_ids_must_not_clash(): + graph = S.caliber_graph(sql="SELECT SUM(amount) AS gmv FROM orders WHERE status = 'paid' AND id > {{ input.after }}") + # 字段没写类型(按文字收):表单校验放行,裸写进 SQL 的只能是数 + graph["nodes"][0]["data"]["config"]["fields"] = [{"name": "after", "default": "0"}] + wf = await S.publish(graph=graph) + pool = await composer() + with pytest.raises(compose.ComposeRefused, match="只能是数"): + pool.compose({**use(wf), "inputs": {"after": "1 OR 1=1"}}, taken=set()) + made = pool.compose({**use(wf), "inputs": {"after": "3"}}, taken=set()) + assert made.nodes[0]["data"]["config"]["args"]["sql"].endswith("id > 3") + with pytest.raises(compose.ComposeRefused, match="撞了"): + pool.compose({**use(wf), "inputs": {"after": "3"}}, taken={"c1"}) + + +async def test_a_card_that_reads_model_output_is_listed_but_not_composable(): + graph = S.chain(S.node("start", "input"), S.node("ask", "agent", tools=[S.tool()], assign_to="kpi"), + S.node("card", "metrics", caliber="周销售", metrics=[{"id": "gmv", "expression": "vars.kpi.gmv"}]), + S.node("out", "output", fields=[{"name": "r", "value": "{{ nodes.card.text }}"}])) + wf = await S.publish(graph=graph) + async with SessionLocal() as session: + kind = await CaliberKind.load(session, compose=True) + [option] = [o for o in kind.options if o.workflow_id == wf] + assert not option.composable and "不能复用" in option.reason + text, _ = await kind.detail([(i, "named") for i in kind.items if i.workflow_id == wf], 4000) + assert "不能组合" in text + with pytest.raises(compose.ComposeRefused, match="不能组合"): + compose.Composer(list(kind.options)).compose(use(wf), taken=set()) + + +# -------------------------------------------------------------------------- +# 查看:入口字段、能不能组合,不给 SQL +# -------------------------------------------------------------------------- + + +async def test_the_answer_look_shows_fields_and_how_to_compose_but_no_sql(): + wf = await S.publish() + async with SessionLocal() as session: + kind = await CaliberKind.load(session, compose=True) + plain = await CaliberKind.load(session) + objects = [(i, "named") for i in kind.items if i.workflow_id == wf] + text, [record] = await kind.detail(objects, 4000) + assert "入口字段:start(string,必填);end(string,必填);store(string,缺省 all)" in text + assert '"op": "use_caliber"' in text and f'"workflow_id": "{wf}"' in text and '"card": "card"' in text + assert "SELECT" not in text.upper() and "orders" not in text + assert record["kind"] == "caliber" and record["named"] + # 蓝图助手那一支(不组合)照旧给复用写法,没有组合写法 + plain_text, _ = await plain.detail([(i, "named") for i in plain.items if i.workflow_id == wf], 4000) + assert "复用写法" in plain_text and "use_caliber" not in plain_text + + +async def test_the_answer_prompt_switches_only_when_calibers_can_be_composed(): + from app.look.service import LookService + + assert copilot_context.LOOK_WHEN_ANSWER_PROMPT != copilot_context.LOOK_WHEN_PROMPT + assert "use_caliber" in copilot_context.LOOK_WHEN_ANSWER_PROMPT and "含退款" in copilot_context.LOOK_WHEN_ANSWER_PROMPT + async with SessionLocal() as session: + composing = LookService([await CaliberKind.load(session, compose=True)]) + plain = LookService([await CaliberKind.load(session)]) + assert copilot_context.look_when(composing) == copilot_context.LOOK_WHEN_ANSWER_PROMPT + assert copilot_context.look_when(plain) == copilot_context.LOOK_WHEN_PROMPT + assert copilot_context.composer(plain) is None and copilot_context.composer(composing) is not None + + +# -------------------------------------------------------------------------- +# 落地:GraphApplier +# -------------------------------------------------------------------------- + + +async def test_the_applier_lands_the_nodes_wires_the_entry_and_reports_refusals(): + wf = await S.publish() + nodes: dict = {} + edges: list = [] + applier = GraphApplier(nodes, edges, composer=await composer()) + op = use(wf) + applied = applier.apply(op) + assert applied.changed and applied.forward and op["result"]["status"] == "ok" + assert set(nodes) == {"c1_fetch", "c1"} and edges == [{"source": "c1_fetch", "target": "c1", "sourceHandle": None}] + # 入口后加的:加上时接到第一个取数节点;模型再发一条同样的连线不重复 + applier.apply({"op": "add_node", "node": {"id": "start", "type": "input", "label": "入口", "config": {}}}) + assert {"source": "start", "target": "c1_fetch", "sourceHandle": None} in edges + assert not applier.apply({"op": "add_edge", "edge": {"source": "start", "target": "c1_fetch"}}).changed + assert len([e for e in edges if e["target"] == "c1_fetch"]) == 1 + # 接着写时重发同一个选用:不再落地 + applier.continuing() + assert not applier.apply(use(wf)).changed + assert "c1" in applier.landed() + + bad = use(wf, id="c2", inputs={"start": "2026-09-01"}) + refused = applier.apply(bad) + assert not refused.changed and refused.forward and bad["result"]["status"] == "refused" + checker = GraphChecker(applier) + first = await checker.issues() + assert [i["code"] for i in first if i["code"] == compose.REFUSED] == [compose.REFUSED] + assert "请填写「end」" in first[0]["message"] and "重新输出 use_caliber" in first[0]["for_model"] + # 交回过一次就不再交 + assert not [i for i in await checker.issues() if i["code"] == compose.REFUSED] + + # 兜底重放到上一轮的图上:拷进来的节点和接线照样在 + applier.replay_onto({"nodes": [{"id": "start", "type": "input", "data": {"config": {}}}], "edges": []}) + assert {"c1_fetch", "c1"} <= set(nodes) and any(e["target"] == "c1_fetch" for e in edges) + + +async def test_without_a_composer_use_caliber_is_dropped_like_any_unknown_op(): + nodes: dict = {} + applier = GraphApplier(nodes, []) + applied = applier.apply({"op": "use_caliber", "id": "c1", "workflow_id": "w", "version": 1}) + assert not applied.changed and not applied.forward and nodes == {} + + +# -------------------------------------------------------------------------- +# 问数据走一遍:生成 → 运行 → 比对标 composed +# -------------------------------------------------------------------------- + + +def _answer_script(wf: str) -> list[dict]: + from tests.test_copilot_answer_ops import _edge, _node + + return [ + {"op": "plan", "summary": "选用周销售口径"}, + _node("start", "input", {}), + use(wf), + _node("write", "report", {"instructions": "回答:{{ input.question }}"}), + _edge("c1", "write"), + _node("out", "output", {"fields": [{"name": "答案", "value": "{{ nodes.write.text }}"}]}), + _edge("write", "out"), + {"op": "done", "explanation": "按口径周销售回答", "run": True}, + ] + + +async def test_an_answer_built_with_use_caliber_is_labelled_composed(client, monkeypatch): + from tests.test_copilot_answer_ops import BODY, _Scripted, _sse, _use + + wf = await S.publish() + _use(monkeypatch, _Scripted(_answer_script(wf), [])) + ops = await _sse(client, {**BODY, "instruction": "九月第一周卖了多少"}) + [chosen] = [o for o in ops if o["op"] == "use_caliber"] + assert chosen["result"]["status"] == "ok" and chosen["result"]["workflow_name"] == "周销售" + assert not [o for o in ops if o["op"] == "add_node" and o["node"]["id"] in ("c1", "c1_fetch")], \ + "拷进来的节点不另外转给界面:过程里只有 use_caliber 那一行" + [final] = [o for o in ops if o["op"] == "final"] + assert final["next"] == "run", final["issues"] + graph = final["graph"] + assert {n["id"] for n in graph["nodes"]} == {"start", "c1_fetch", "c1", "write", "out"} + assert not [i for i in validate_graph(GraphSpec.model_validate(graph)).issues if i.level == "error"] + + S.script(monkeypatch, "九月第一周销售额 [[m:gmv]]。") + run = await run_manager.start(graph=graph, input_payload={"question": "九月第一周卖了多少"}, origin_kind="chat") + row = await S.wait(run.id) + assert row.status == "succeeded", row.error + await ledger_match.drain() + recorded = await store.latest(row.id) + content = recorded.content + assert content["algo"] == store.ALGO == "2" + [query] = content["queries"] + assert query["status"] == "composed" and query["node_id"] == "c1_fetch" + [cand] = query["candidates"] + assert cand["status"] == "proven" and cand["how"] == "composed" and cand["caliber"] == f"{wf}@1" + [label] = content["reports"]["write"]["labels"].values() + assert label["kind"] == "caliber" and label["how"] == "composed" and label["queries"] == [query["artifact"]] + assert content["whole"]["equivalent"] is True and content["whole"]["how"] == "composed" + assert recorded.content and (await store.latest(row.id)).trigger == "sealed" + async with SessionLocal() as session: + from app.db.models import Artifact + + ref = await session.get(Artifact, (recorded.artifact, row.id)) + assert ref.meta["calibers"] == [f"{wf}@1"] and ref.meta["counts"]["composed"] == 1 + + +async def test_users_do_not_get_calibers_in_the_answer_look(monkeypatch): + """使用者(开登录后的 user 角色):问数据里不看口径、不能选用(拷进来的取数 SQL 在他的图里看得到)。""" + import app.api.copilot as copilot + from app.api.copilot import GenerateIn + + seen: dict = {} + + async def spy(session, payload, sources, **kw): + seen["kinds"] = kw.get("kinds") + raise RuntimeError("到这里就够了") + + monkeypatch.setattr(copilot, "_look_service", spy) + monkeypatch.setattr("app.api.deps.restricted", lambda: True) + with pytest.raises(RuntimeError): + await copilot.answer_ops(GenerateIn(instruction="x", intent="answer")).__anext__() + assert seen["kinds"] == ("table", "capability") + monkeypatch.setattr("app.api.deps.restricted", lambda: False) + with pytest.raises(RuntimeError): + await copilot.answer_ops(GenerateIn(instruction="x", intent="answer")).__anext__() + assert seen["kinds"] == ("table", "capability", "caliber") + with pytest.raises(RuntimeError): + await copilot.answer_ops(GenerateIn(instruction="x", intent="build")).__anext__() + assert seen["kinds"] == ("table", "capability") diff --git a/frontend/src/lib/terms.ts b/frontend/src/lib/terms.ts index e93f53d7..29929850 100644 --- a/frontend/src/lib/terms.ts +++ b/frontend/src/lib/terms.ts @@ -4526,6 +4526,18 @@ export const LEDGER_TEXT = { kind: { caliber: '来自口径', related: '相关口径', reasoning: '这次的推理', unknown: '没有比对' }, how: { independent: '等价已证明', composed: '助手选用' }, level: { governed: '受管', published: '已发布' }, + /** + * 问数据的助手选用已发布口径(use_caliber,服务端 ledger/compose.py 按那一版生成取数节点和口径卡):过程里照实写一行。 + * 拒收的(参数不对、版本不对……)同样一行,写服务端给的原因 + */ + use: { + title: (name: string, version: number | null, level: string) => + `选用口径「${name}」${version != null ? ` v${version}` : ''}${level ? `(${level})` : ''}`, + detail: (fetches: number, card: string, metrics: string) => + `按这一版生成取数节点 ${formatNumber(fetches)} 个和口径卡「${card}」${metrics ? `,用到的指标:${metrics}` : ''}`, + refused: '没有选用口径', + status: '正在选用口径…', + }, } /** diff --git a/frontend/src/run/decode.ts b/frontend/src/run/decode.ts index 7be7d838..68023974 100644 --- a/frontend/src/run/decode.ts +++ b/frontend/src/run/decode.ts @@ -3577,6 +3577,25 @@ export function decodeCopilot(ops: CopilotOp[], opts?: { .join('\n') }) break } + case 'use_caliber': { + // 问数据的助手选用已发布口径(服务端 ledger/compose.py):取数节点和口径卡由服务端按那一版生成,不另转 add_node, + // 这里一行说清选用了哪一版、生成了几个节点;拒收的照实写原因(原因同样交回了模型去改) + const r = op.result && typeof op.result === 'object' ? op.result : null + if (r?.status === 'ok') { + nodeCount += num(r.nodes) ?? 0 + const metrics = Array.isArray(r.metrics) ? r.metrics.map((m: any) => String(m?.name ?? m?.id ?? '')).filter(Boolean) : [] + add({ id: `uc-${i}`, seq: i, kind: 'node', status: 'done', code: 'use_caliber', + title: clip(LEDGER_TEXT.use.title(String(r.workflow_name ?? r.workflow_id ?? ''), num(r.version) ?? null, + String(r.level_text ?? ''))), + detail: LEDGER_TEXT.use.detail(Array.isArray(r.fetches) ? r.fetches.length : 0, String(r.card ?? r.card_id ?? ''), + metrics.join('、')), + ...(r.card_id ? { nodeId: String(r.card_id) } : {}) }) + } else if (r?.status === 'refused') { + add({ id: `uc-${i}`, seq: i, kind: 'note', status: 'done', level: 'warn', code: 'use_caliber_refused', + title: LEDGER_TEXT.use.refused, detail: String(r.reason ?? '') || undefined }) + } + break + } case 'plan': add({ id: `cp-${i}`, seq: i, kind: 'note', status: 'done', title: clip(String(op.summary ?? '已完成规划'), 120) }) diff --git a/frontend/src/store/chat.ts b/frontend/src/store/chat.ts index d098ea01..c405fbb8 100644 --- a/frontend/src/store/chat.ts +++ b/frontend/src/store/chat.ts @@ -2,7 +2,7 @@ import { create } from 'zustand' import { ApiError, api, streamCopilot, streamRun } from '../api/client' import type { CopilotOp, FixKind, RunFinal } from '../run/decode' import { copilotContext, copilotLook, decodeRun, looksOf } from '../run/decode' -import { CHAT_BLUEPRINT_TEXT, LOOK_TEXT, REJECTED_TEXT } from '../lib/terms' +import { CHAT_BLUEPRINT_TEXT, LEDGER_TEXT, LOOK_TEXT, REJECTED_TEXT } from '../lib/terms' import type { LookEvent } from '../typesApp' import { errorMessage, humanizeError, isNetworkError } from '../lib/errors' import { guardReview, hasEvidence } from '../lib/evidence' @@ -1492,6 +1492,10 @@ function plan(flow: Flow, args: PlanArgs) { status: `正在生成工作流…(${t.ops.filter((o) => o.op === 'add_node').length} 步)`, })) break + case 'use_caliber': + // 助手选用了一份已发布口径(取数节点和口径卡由服务端生成,过程里那一行由 decodeCopilot 写) + patch(() => ({ phase: 'building', status: LEDGER_TEXT.use.status })) + break case 'done': patch(() => ({ explanation: op.explanation ?? '' })) break diff --git a/scripts/check-decode.mjs b/scripts/check-decode.mjs index 16222f78..dc2cd0a6 100644 --- a/scripts/check-decode.mjs +++ b/scripts/check-decode.mjs @@ -1858,6 +1858,32 @@ await section('口径账本:封存后比对已发布口径(ledger.matched) check('不改相位:运行照旧是结束了', phase.phase === 'succeeded', phase.phase) }) +await section('口径账本:问数据的助手选用已发布口径(use_caliber 操作)', async () => { + // next-round 02 做法 4:取数节点和口径卡由服务端按那一版生成(ledger/compose.py),不另转 add_node。过程里一行说清选用了 + // 哪一版、生成了几个节点;拒收的照实写原因(同样交回了模型去改) + const ok = { op: 'use_caliber', id: 'c1', workflow_id: 'wf-week', version: 3, metrics: ['gmv'], inputs: { start: '2026-09-01' }, + result: { status: 'ok', workflow_id: 'wf-week', workflow_name: '周销售', version: 3, level: 'governed', level_text: '受管', + card: '周销售卡', card_id: 'c1', fetches: ['c1_fetch'], metrics: [{ id: 'gmv', name: '销售额' }], nodes: 2 } } + const steps = mod.decodeCopilot([ + { op: 'plan', summary: '选用周销售口径' }, + { op: 'add_node', node: { id: 'start', type: 'input', label: '入口', config: {} } }, + ok, + { op: 'add_node', node: { id: 'write', type: 'report', label: '写答案', config: {} } }, + { op: 'done', explanation: '按口径回答' }, + ], { context: 'chat' }) + const row = steps.find((s) => s.code === 'use_caliber') + check('一行:选用了哪一版、级别', row?.title === '选用口径「周销售」 v3(受管)' && row?.kind === 'node' && row?.status === 'done', row?.title) + check('展开:生成了几个取数节点、哪张口径卡、用到哪几个指标', + row?.detail === '按这一版生成取数节点 1 个和口径卡「周销售卡」,用到的指标:销售额', row?.detail) + check('节点数算进「新增几个步骤」(入口、报告各 1,选用的 2)', + steps.find((s) => s.id.startsWith('cd-'))?.title === '工作流已搭建完成,新增 4 个步骤', steps.find((s) => s.id.startsWith('cd-'))?.title) + const refused = mod.decodeCopilot([{ op: 'use_caliber', id: 'c2', result: { status: 'refused', reason: '请填写「end」' } }]) + .find((s) => s.code === 'use_caliber_refused') + check('拒收的:提醒一行,写服务端给的原因', refused?.title === '没有选用口径' && refused?.detail === '请填写「end」' + && refused?.level === 'warn', `${refused?.title} / ${refused?.detail}`) + check('没带结果(老服务端、形状不对):不出行、不报错', mod.decodeCopilot([{ op: 'use_caliber', id: 'c1' }, { op: 'use_caliber', result: 'x' }]).length === 0) +}) + await section('术语', async () => { // 没起名的节点退到类型名,类型名跟全站同一张表 const h = mod.decodeRun([{ seq: 1, type: 'node.started', node_id: 'h', ts: 1, data: { node_type: 'human', label: 'h' } }])