mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-24 12:32:03 +00:00
可点击证据第一期:报告里的每个数字都点得开出处
「引用即渲染」:写报告的模型只写引用标记([[m:指标id]]、[[i:输入字段]]、[[see:…]]),数值由系统按口径卡
填进去,每个数字都挂着一条能复算的证据链。本期是数字层闭环;实体、结论句的概率性证据放在后续几期。
内核(engine/evidence.py,口径卡、出具契约、表达式等)
- 口径卡记录每个指标的来源:原式、代入式(每个输入写成「值 ← 路径」)、复算结果、口径与版本
- 出具契约的数值匹配改为按位置标注;同一个值有几个出处时记为「出处不唯一」并列出候选,不再随便挑一个
- 证据 id 由内容派生,事后对不上就是被改过;零值、结构性数字(列表序号、代码块标签)单独处理
- 口径卡新增 on_missing:缺输入时默认仍是整个节点失败,可以改成记为空值、交给契约判档
报告撰写节点(report)与引用模式的出具契约
- 流式生成时 token 里就是真实数字,不会漏出原始标记;裸数字、不存在的引用当场判违规,交回去重写
(max_repairs,默认 1 次);仍不过时按 on_violation 失败(正式运行默认)或把违规标在报告里(探索运行默认)
- report.checked 事件记下核对结果,落在封存范围内;fail 模式下仍不过时带 failed,运行记录里画成失败
- 出具契约写了 report_from 就按引用核对:取回文档时复验哈希,独立重算一遍,全部带引用才判完整出具
- 成果字段逐字等于报告正文时标注 _evidence;复核只能加说明,不能改写带证据的答案(前后端各拦一道)
证据接口
- GET /api/runs/{id}/evidence 返回证据图;GET …/evidence/segments/{id} 返回一个片段的证据链
- 只认封存范围内的事件能追到的工件,不读 artifacts 表;封存被改过时不把任何一项标成已封存
- 没有报告的旧运行降级为 none 或 legacy_contract
界面
- EvidenceDoc 按块、句、片段渲染报告,片段是和正文一样的按钮;整份报告只占一个 Tab 位,
←/→ 在片段间移动、↑/↓ 按句、n/N 跳到下一处「无证据」、Enter 打开面板、Esc 关闭并把焦点还回去
- EvidencePanel:宽屏侧边、窄屏底部抽屉、360px 画布右栏里栏内展开;显示指标步骤、代入式、复算结果、
封存状态。正文不是封存的那份报告时明确说出来,不拿别的报告的封存画绿
- 出具横幅多一行「N/N 数字有出处 · 无证据 M」和「定位下一处」;没有 _evidence 的旧回答渲染一字不差
- 画布认得报告撰写节点;Copilot 手册补上口径卡、报告节点、出具契约的写法;新增模板「⑨ 可追溯周报」
验证(沙箱):tsc 干净,生产构建通过,pytest 1601 passed,check-all 16 项检查全绿(新增 check-evidence)。
This commit is contained in:
@@ -11,7 +11,7 @@ from langgraph.graph import END, START, StateGraph
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType
|
||||
from app.engine.context import NodeContext, NodeError, RunContext
|
||||
from app.engine.nodes import control, human, io, knowledge, llm, metrics, multi, tools
|
||||
from app.engine.nodes import control, human, io, knowledge, llm, metrics, multi, report, tools
|
||||
from app.engine.schema import GraphNode, GraphSpec, NodeType, back_edges, innermost_loops
|
||||
from app.engine.state import GraphState
|
||||
|
||||
@@ -35,6 +35,7 @@ RUNNERS: dict[NodeType, NodeRunner] = {
|
||||
NodeType.MEMORY: knowledge.run_memory,
|
||||
NodeType.METRICS: metrics.run_metrics,
|
||||
NodeType.RETRIEVE: knowledge.run_retrieve,
|
||||
NodeType.REPORT: report.run_report,
|
||||
}
|
||||
|
||||
# 这些节点的出边由"决定"路由,不能直接连死
|
||||
@@ -111,6 +112,10 @@ def _wrap(
|
||||
# 如实发出来,只多一个已截断的值,且只有真的赋了值的节点才有。
|
||||
vars=_vars_preview(updates),
|
||||
artifact=artifact_id,
|
||||
# 这一步新记进证据台账的条目(口径卡的指标集工件等)。事件在封存范围
|
||||
# 内,证据接口从这里出发找工件,不去读可以事后插行的 artifacts 表。
|
||||
# 没产出证据的节点不带这个键,事件和以前一字不差
|
||||
**({"evidence": updates["evidence"]} if updates.get("evidence") else {}),
|
||||
)
|
||||
trail = {
|
||||
"node_id": node.id,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -277,6 +277,104 @@ def parse_expression(expr: str) -> tuple[ast.Expression, list[str], list[str]]:
|
||||
return tree, unbrace.found, unknown
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 引用与代入:口径卡要说清「这个数是拿哪几个输入算出来的」
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _chain_root(node: ast.AST) -> str | None:
|
||||
"""node 是不是一条从根名字出发的取值链(vars.kpi.gmv、nodes.q.rows[0])。是就返回根。"""
|
||||
cur = node
|
||||
while isinstance(cur, (ast.Attribute, ast.Subscript)):
|
||||
cur = cur.value
|
||||
if isinstance(cur, ast.Name) and cur.id in EXPRESSION_ROOTS:
|
||||
return cur.id
|
||||
return None
|
||||
|
||||
|
||||
def _walk_refs(node: ast.AST, found: list[ast.AST]) -> None:
|
||||
if isinstance(node, (ast.Attribute, ast.Subscript, ast.Name)) and _chain_root(node):
|
||||
found.append(node)
|
||||
# 链本身不再往里拆(vars.kpi 是 vars.kpi.gmv 的一部分),但下标里的表达式是
|
||||
# 独立的输入:vars.rows[vars.i] 取哪一格由 vars.i 决定
|
||||
cur = node
|
||||
while isinstance(cur, (ast.Attribute, ast.Subscript)):
|
||||
if isinstance(cur, ast.Subscript):
|
||||
_walk_refs(cur.slice, found)
|
||||
cur = cur.value
|
||||
return
|
||||
for child in ast.iter_child_nodes(node):
|
||||
_walk_refs(child, found)
|
||||
|
||||
|
||||
def leaf_refs(tree: ast.AST) -> list[str]:
|
||||
"""表达式引用了哪些值:每条从根名字出发的最长取值链,按出现顺序去重。
|
||||
|
||||
parse_expression 只告诉你「有没有不认识的名字」;口径卡要记来源,得知道
|
||||
round((vars.kpi.gmv - vars.kpi.gmv_prev) / …) 里用到的是 vars.kpi.gmv 和
|
||||
vars.kpi.gmv_prev 这两个值,而不是 vars、kpi 这些零件。
|
||||
路径用 ast.unparse 的写法,substitute 按同样的写法认。
|
||||
"""
|
||||
found: list[ast.AST] = []
|
||||
_walk_refs(tree, found)
|
||||
return list(dict.fromkeys(ast.unparse(n) for n in found))
|
||||
|
||||
|
||||
_SCALARS = (int, float, str, bool, type(None))
|
||||
#: 字符串长过这个数就不代进去:上游模型写的一大段文本抄进代入式(和 metric_set 工件),
|
||||
#: 没人看得懂,只是把工件撑大
|
||||
_INLINE_STR_MAX = 80
|
||||
|
||||
|
||||
def _inlinable(value: Any) -> bool:
|
||||
"""这个值能不能以字面量的样子写进代入式。
|
||||
|
||||
容器不行;含 {{ 或 }} 的字符串不行——parse_expression 会把整条代入式当成
|
||||
「表达式里写了模板」拒掉,复算就成了假的「对不上」;太长的字符串也不代。
|
||||
"""
|
||||
if not isinstance(value, _SCALARS):
|
||||
return False
|
||||
if isinstance(value, str):
|
||||
return len(value) <= _INLINE_STR_MAX and "{{" not in value and "}}" not in value
|
||||
return True
|
||||
|
||||
|
||||
def _literal(value: Any) -> ast.expr:
|
||||
"""负数写成一元负号:Constant(-3) 放在幂运算左边会被 unparse 成 -3 ** 2,
|
||||
读起来和算起来都是 -(3 ** 2)。一元负号节点 unparse 时会自己加括号。"""
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool) and value < 0:
|
||||
return ast.UnaryOp(op=ast.USub(), operand=ast.Constant(-value))
|
||||
return ast.Constant(value)
|
||||
|
||||
|
||||
class _Substitute(ast.NodeTransformer):
|
||||
def __init__(self, values: dict[str, Any]) -> None:
|
||||
self.values = values
|
||||
|
||||
def _replace(self, node: ast.AST) -> ast.AST:
|
||||
if _chain_root(node):
|
||||
path = ast.unparse(node)
|
||||
if path in self.values and _inlinable(self.values[path]):
|
||||
return ast.copy_location(_literal(self.values[path]), node)
|
||||
if path in self.values:
|
||||
return node # 容器、含 {{ }} 的或太长的字符串留原路径,复算时照样取得到
|
||||
return self.generic_visit(node)
|
||||
|
||||
visit_Attribute = visit_Subscript = visit_Name = _replace
|
||||
|
||||
|
||||
def substitute(tree: ast.AST, values: dict[str, Any]) -> str:
|
||||
"""把引用换成它当时的值,得到代入式:round((45678.5 - 42010.0) / 42010.0 * 100, 1)。
|
||||
|
||||
只代标量(含 {{ }} 或长过 80 字的字符串除外)。代入式本身还是一条合法表达式——拿同一个上下文再求一遍,结果必须和
|
||||
原式一样,这是口径卡复算(recompute_ok)的依据。不改动传进来的语法树。
|
||||
"""
|
||||
import copy
|
||||
|
||||
replaced = _Substitute(values).visit(copy.deepcopy(tree))
|
||||
return ast.unparse(ast.fix_missing_locations(replaced))
|
||||
|
||||
|
||||
def eval_expression(expr: str, ctx: dict[str, Any]) -> Any:
|
||||
"""求值一个受限的 Python 表达式。
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from typing import Any, Callable
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 出具校验:叙述里的每个数字必须能回指到指标集
|
||||
@@ -185,6 +185,11 @@ class NumberToken:
|
||||
#: 回指时允许的偏差。缺省按写出的小数位数算;中文数字、带万亿后缀的数有自己的书写精度
|
||||
tolerance: float | None = None
|
||||
|
||||
@property
|
||||
def end(self) -> int:
|
||||
"""raw 在原文里的结束位置。raw 只去掉了右侧空白,开头就是 start。"""
|
||||
return self.start + len(self.raw)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TraceReport:
|
||||
@@ -345,6 +350,27 @@ def _token_matches(token: NumberToken, metric_value: float) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def number_allowance(allow: list[Any] | None) -> Callable[[NumberToken], bool]:
|
||||
"""模板作者放行的字面量:写法相同,或者数值在这个 token 的书写精度内相等。
|
||||
|
||||
旧契约的回指和报告节点的裸数字检查共用这一条,两边放行的范围才一致。
|
||||
"""
|
||||
allowed = {str(a).strip() for a in (allow or [])}
|
||||
values = set()
|
||||
for a in allowed:
|
||||
try:
|
||||
values.add(float(a.replace(",", "").rstrip("%%")))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def ok(token: NumberToken) -> bool:
|
||||
if token.raw in allowed or token.raw.rstrip("%%").strip() in allowed:
|
||||
return True
|
||||
return any(_close(token.value, v, _tolerance(token)) for v in values)
|
||||
|
||||
return ok
|
||||
|
||||
|
||||
def trace_numbers(
|
||||
narrative: str,
|
||||
metrics: list[dict[str, Any]],
|
||||
@@ -356,40 +382,28 @@ def trace_numbers(
|
||||
allow 是模板作者显式放行的字面量(比如报告标题里的期数)——
|
||||
白名单是配置的一部分,进版本、被审查,而不是校验器私藏的宽容。
|
||||
"""
|
||||
numeric_values = [
|
||||
float(m["value"])
|
||||
# 值和指标成对取:以前值列表排掉了布尔、指标列表没排,一个布尔指标就让后面的全错位
|
||||
numeric = [
|
||||
(m, float(m["value"]))
|
||||
for m in metrics
|
||||
if isinstance(m.get("value"), (int, float)) and not isinstance(m.get("value"), bool)
|
||||
]
|
||||
allowed = {str(a).strip() for a in (allow or [])}
|
||||
allowed_values = set()
|
||||
for a in allowed:
|
||||
try:
|
||||
allowed_values.add(float(a.replace(",", "").rstrip("%%")))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
allowed = number_allowance(allow)
|
||||
report = TraceReport()
|
||||
for token in extract_numbers(narrative):
|
||||
if token.raw in allowed or token.raw.rstrip("%%").strip() in allowed:
|
||||
if allowed(token):
|
||||
continue
|
||||
if any(_close(token.value, av, _tolerance(token)) for av in allowed_values):
|
||||
continue
|
||||
hit = next(
|
||||
(
|
||||
m
|
||||
for m, mv in zip(
|
||||
[m for m in metrics if isinstance(m.get("value"), (int, float))],
|
||||
numeric_values,
|
||||
)
|
||||
if _token_matches(token, mv)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if hit is not None:
|
||||
report.matched.append({"token": token.raw, "metric": hit.get("id")})
|
||||
where = {"start": token.start, "end": token.end}
|
||||
# 同一个值可能同时对得上好几个指标(最典型的是一排兜底出来的 0)。以前取第一个
|
||||
# 命中的,界面上所有的 0 都标成「来自指标 A」——出处不唯一就照实说不唯一
|
||||
hits = list(dict.fromkeys(m.get("id") for m, mv in numeric if _token_matches(token, mv)))
|
||||
if len(hits) == 1:
|
||||
report.matched.append({"token": token.raw, "metric": hits[0], **where})
|
||||
elif hits:
|
||||
report.matched.append({"token": token.raw, "metric": None, "candidates": hits,
|
||||
"ambiguous": True, **where})
|
||||
else:
|
||||
report.unmatched.append({"token": token.raw, "context": token.context})
|
||||
report.unmatched.append({"token": token.raw, "context": token.context, **where})
|
||||
return report
|
||||
|
||||
|
||||
@@ -400,6 +414,10 @@ def decide_tier(
|
||||
unmatched: list[dict[str, Any]],
|
||||
strict: bool,
|
||||
gaps: list[str] | None = None,
|
||||
unresolved: list[Any] | None = None,
|
||||
unsupported: list[Any] | int | None = None,
|
||||
uncited_claims: list[Any] | int | None = None,
|
||||
claims_policy: str | dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
"""三档出具的判定。
|
||||
|
||||
@@ -413,11 +431,47 @@ def decide_tier(
|
||||
空串、metrics_from 指向不存在的节点,都会得到一模一样的空列表。
|
||||
校验没发生就盖 formal 章,比漏检某个数字更糟:它让整套机制看起来在工作。
|
||||
所以 gaps 用来承载"校验为什么不完整",非空就不允许 formal。
|
||||
|
||||
引用模式另有几样:unresolved 是解析不了的引用(报告里写了 [[m:gmvx]],目录里
|
||||
没有),和未回指数字同等对待——那个位置上显示的不是一个有出处的数。
|
||||
unsupported / uncited_claims 是结论句的判定,只在声明了 claims_policy 时才参与:
|
||||
字符串(judge / require_citation)两样都按降档处理;对象形式可以分别写
|
||||
on_unsupported / on_uncited 为 degrade、withhold 或 ignore。不声明就不管,
|
||||
旧调用和没开结论检查的契约都不受影响。
|
||||
"""
|
||||
if missing_required:
|
||||
return "withheld"
|
||||
if strict and unmatched:
|
||||
if strict and (unmatched or unresolved):
|
||||
return "withheld"
|
||||
if missing_expected or unmatched or gaps:
|
||||
claims = _claims_effect(claims_policy, unsupported, uncited_claims)
|
||||
if claims == "withhold":
|
||||
return "withheld"
|
||||
if missing_expected or unmatched or unresolved or gaps or claims == "degrade":
|
||||
return "degraded"
|
||||
return "formal"
|
||||
|
||||
|
||||
def _claims_effect(
|
||||
policy: str | dict[str, Any] | None,
|
||||
unsupported: list[Any] | int | None,
|
||||
uncited: list[Any] | int | None,
|
||||
) -> str | None:
|
||||
"""结论句对档位的影响:withhold / degrade / None。"""
|
||||
if isinstance(policy, dict):
|
||||
name = policy.get("policy")
|
||||
on_unsupported = policy.get("on_unsupported") or "degrade"
|
||||
on_uncited = policy.get("on_uncited") or "degrade"
|
||||
else:
|
||||
name, on_unsupported, on_uncited = policy, "degrade", "degrade"
|
||||
if not name or name == "off":
|
||||
return None
|
||||
|
||||
def count(value: list[Any] | int | None) -> int:
|
||||
return value if isinstance(value, int) else len(value or [])
|
||||
|
||||
effects = [on for on, n in ((on_unsupported, count(unsupported)), (on_uncited, count(uncited))) if n]
|
||||
if "withhold" in effects:
|
||||
return "withhold"
|
||||
if "degrade" in effects:
|
||||
return "degrade"
|
||||
return None
|
||||
|
||||
+261
-18
@@ -1,11 +1,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.core.events import EventType
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.expressions import ExpressionError, eval_expression
|
||||
from app.engine.schema import GraphNode, NodeType, _ancestors
|
||||
from app.engine.state import GraphState, template_context
|
||||
|
||||
|
||||
@@ -52,21 +54,99 @@ async def run_output(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 没配映射就把最后一条消息当作结果,让新建的图开箱即用
|
||||
result = {"result": tctx.get("last_message", "")}
|
||||
|
||||
reports = _report_fields(result, mapping, state, ctx)
|
||||
contract = ctx.cfg("contract")
|
||||
if contract:
|
||||
result["_issuance"] = _apply_contract(contract, state, ctx)
|
||||
result["_issuance"] = _apply_contract(contract, state, ctx, reports=reports)
|
||||
evidence = _evidence_of(reports, contract)
|
||||
if evidence:
|
||||
result["_evidence"] = evidence
|
||||
|
||||
return {"output": result, "nodes": {ctx.node.id: result}}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 成果字段和上游报告的对应
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _reference(node: GraphNode) -> re.Pattern[str]:
|
||||
"""字段模板里「带出了这个报告的正文」的写法。
|
||||
|
||||
nodes.write.text、nodes['write']['text']、整个 nodes.write(过 json 也带着正文),以及
|
||||
存的就是正文的 vars.<assign_to>。nodes.write.repairs / stats / doc_artifact 只是把报告的
|
||||
统计或文档 id 一起放进成果,没碰正文——算成改动的话,一份全部带引用的报告会被一个
|
||||
「改写次数」字段拖成降档。模板只认路径加过滤器、没有方法调用,所以这几种写法就是全部。
|
||||
"""
|
||||
nid = re.escape(node.id)
|
||||
head = rf"nodes\s*(?:\.\s*{nid}(?![\w-])|\[\s*['\"]{nid}['\"]\s*\])"
|
||||
alternatives = [rf"{head}(?:\s*\.\s*text(?![\w-])|\s*\[\s*['\"]text['\"]\s*\]|(?!\s*[.\[]))"]
|
||||
var = str(node.config.get("assign_to") or "").strip()
|
||||
if var:
|
||||
alternatives += [rf"vars\s*\.\s*{re.escape(var)}(?![\w-])",
|
||||
rf"vars\s*\[\s*['\"]{re.escape(var)}['\"]\s*\]"]
|
||||
return re.compile("|".join(alternatives))
|
||||
|
||||
|
||||
def _report_fields(
|
||||
result: dict[str, Any], mapping: Any, state: GraphState, ctx: NodeContext,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""上游每个写出了文档的报告节点:哪些成果字段逐字就是它的原文,哪些引用了它却改动过。
|
||||
|
||||
逐字相等的字段,界面能按文档逐段画、逐个数点开证据;模板在报告前后拼了别的字、
|
||||
或者过了过滤器,偏移就对不上了——这种字段不标证据,有契约时记一条 gap。
|
||||
首尾空白不算改动:Markdown 渲染出来一样,文档的 markdown 本来就去掉了首尾空白。
|
||||
"""
|
||||
spec = ctx.run.spec
|
||||
upstream = _ancestors(spec, ctx.node.id)
|
||||
nodes = state.get("nodes") or {}
|
||||
sources = {f.get("name"): f.get("value", "") for f in mapping or [] if isinstance(f, dict) and f.get("name")}
|
||||
out = []
|
||||
for node in spec.nodes:
|
||||
payload = nodes.get(node.id)
|
||||
if node.type != NodeType.REPORT or node.id not in upstream or not isinstance(payload, dict):
|
||||
continue
|
||||
text = payload.get("text")
|
||||
if not payload.get("doc_artifact") or not isinstance(text, str) or not text.strip():
|
||||
continue
|
||||
verbatim = [name for name, value in result.items()
|
||||
if not name.startswith("_") and isinstance(value, str) and value.strip() == text]
|
||||
pattern = _reference(node)
|
||||
edited = [name for name, src in sources.items() if name not in verbatim and pattern.search(
|
||||
src if isinstance(src, str) else json.dumps(src, ensure_ascii=False, default=str))]
|
||||
out.append({"node": node, "doc_artifact": payload["doc_artifact"], "verbatim": verbatim,
|
||||
"edited": edited})
|
||||
return out
|
||||
|
||||
|
||||
def _evidence_of(reports: list[dict[str, Any]], contract: Any) -> dict[str, Any] | None:
|
||||
"""成果上的 _evidence:{report_node, doc_artifact, fields}。
|
||||
|
||||
不管有没有契约、是不是正式运行都标——探索运行里的报告一样能点开看证据。契约的
|
||||
report_from 指着的那份优先;另有报告也被原样放进了成果的,列在 others 里。
|
||||
"""
|
||||
shown = [r for r in reports if r["verbatim"]]
|
||||
if not shown:
|
||||
return None
|
||||
preferred = contract.get("report_from") if isinstance(contract, dict) else None
|
||||
shown.sort(key=lambda r: r["node"].id != preferred)
|
||||
first, *rest = [{"report_node": r["node"].id, "doc_artifact": r["doc_artifact"], "fields": r["verbatim"]}
|
||||
for r in shown]
|
||||
return {**first, "others": rest} if rest else first
|
||||
|
||||
|
||||
def _apply_contract(
|
||||
contract: dict[str, Any], state: GraphState, ctx: NodeContext
|
||||
contract: dict[str, Any], state: GraphState, ctx: NodeContext,
|
||||
*, reports: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.engine.issuance import decide_tier, trace_numbers
|
||||
|
||||
nodes = state.get("nodes") or {}
|
||||
# 写了 report_from 就是引用模式:按报告文档逐段复核,不再按数值回指叙述
|
||||
report_from = contract.get("report_from")
|
||||
citations = report_from not in (None, "")
|
||||
|
||||
# 1) 收指标集:contract.metrics_from 指向一个或多个口径卡节点
|
||||
metrics: list[dict[str, Any]] = []
|
||||
@@ -101,26 +181,35 @@ def _apply_contract(
|
||||
if unresolved:
|
||||
gaps.append(f"指标源未解析:{', '.join(unresolved[:5])}")
|
||||
|
||||
present = {m["id"] for m in metrics}
|
||||
# 引用模式下,缺输入记成空值的指标(口径卡 on_missing=null)就是缺:报告里引用不了它,
|
||||
# 也不能因为 id 在清单里就算「齐了」。旧模式照旧只看 id,行为不变
|
||||
present = {m["id"] for m in metrics if not citations or m.get("value") is not None}
|
||||
missing_required = [m for m in (contract.get("required") or []) if m not in present]
|
||||
missing_expected = [m for m in (contract.get("expected") or []) if m not in present]
|
||||
|
||||
# 2) 叙述数字回指
|
||||
declared_narrative = str(contract.get("narrative", ""))
|
||||
narrative = ctx.render_str(declared_narrative, state)
|
||||
# 模板取不到路径时 render 出来是空串,所以"声明了叙述但渲染成空"必须单独识别:
|
||||
# 节点改名、vars 写错都会让回指校验静默变成空操作
|
||||
if declared_narrative.strip() and not narrative.strip():
|
||||
gaps.append("叙述模板渲染为空(路径可能写错了)")
|
||||
elif not declared_narrative.strip():
|
||||
gaps.append("契约没有声明叙述,数字回指未执行")
|
||||
trace = None
|
||||
cited: dict[str, Any] = {}
|
||||
if citations:
|
||||
cited = _check_citations(str(report_from), contract, state, ctx, reports or [])
|
||||
gaps.extend(cited["gaps"])
|
||||
unmatched = cited["unmatched"]
|
||||
else:
|
||||
# 2) 叙述数字回指
|
||||
declared_narrative = str(contract.get("narrative", ""))
|
||||
narrative = ctx.render_str(declared_narrative, state)
|
||||
# 模板取不到路径时 render 出来是空串,所以"声明了叙述但渲染成空"必须单独识别:
|
||||
# 节点改名、vars 写错都会让回指校验静默变成空操作
|
||||
if declared_narrative.strip() and not narrative.strip():
|
||||
gaps.append("叙述模板渲染为空(路径可能写错了)")
|
||||
elif not declared_narrative.strip():
|
||||
gaps.append("契约没有声明叙述,数字回指未执行")
|
||||
|
||||
trace = (
|
||||
trace_numbers(narrative, metrics, allow=contract.get("allow_numbers"))
|
||||
if narrative.strip()
|
||||
else None
|
||||
)
|
||||
unmatched = trace.unmatched if trace else []
|
||||
trace = (
|
||||
trace_numbers(narrative, metrics, allow=contract.get("allow_numbers"))
|
||||
if narrative.strip()
|
||||
else None
|
||||
)
|
||||
unmatched = trace.unmatched if trace else []
|
||||
|
||||
# 声明了 metrics_from 却一个指标都没收到,同样是"没查成"
|
||||
if sources and not metrics:
|
||||
@@ -140,8 +229,15 @@ def _apply_contract(
|
||||
unmatched=unmatched,
|
||||
strict=bool(contract.get("strict")),
|
||||
gaps=gaps,
|
||||
unresolved=cited.get("unresolved"),
|
||||
)
|
||||
|
||||
if citations:
|
||||
return _declare_citations(tier, cited, calibers=calibers, metrics=metrics, gaps=gaps,
|
||||
missing_required=missing_required, missing_expected=missing_expected,
|
||||
report_from=str(report_from), declared_at=datetime.now(timezone.utc),
|
||||
ctx=ctx)
|
||||
|
||||
# 逐个数字的出处。以前只有一个计数,界面标不出「这个数来自哪个指标」
|
||||
matched = [
|
||||
{**hit, **({"caliber": caliber_of[hit["metric"]]} if caliber_of.get(hit.get("metric")) else {})}
|
||||
@@ -177,6 +273,153 @@ def _apply_contract(
|
||||
return issuance
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 引用模式:按报告文档逐段复核
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
#: 文档本身对不上(不是某个数没出处):这次复核没法完成,记 gap
|
||||
_INTEGRITY = {"bad_schema", "segment_mismatch", "structural_text", "render_mismatch", "eid_mismatch",
|
||||
"state_mismatch"}
|
||||
|
||||
|
||||
def _check_citations(
|
||||
report_from: str, contract: dict[str, Any], state: GraphState, ctx: NodeContext,
|
||||
reports: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""独立复核报告文档:{matched, unmatched, unresolved, gaps, doc_artifact, stats}。
|
||||
|
||||
不信报告节点自己的统计:文档按 id 从工件库取回(取回时复验哈希),目录按报告节点
|
||||
同一套参数从状态里重建(不用文档里存的那份),每个带引用的片段重新解析、重新渲染、
|
||||
逐字比对。一个配错的报告节点绕不过这里。
|
||||
"""
|
||||
from app.core.artifact_store import load
|
||||
from app.engine.evidence import iter_units, resolve_ref, verify_doc
|
||||
from app.engine.nodes.report import report_catalog
|
||||
|
||||
out: dict[str, Any] = {"matched": [], "unmatched": [], "unresolved": [], "gaps": [],
|
||||
"doc_artifact": None, "stats": None}
|
||||
gaps = out["gaps"]
|
||||
spec = ctx.run.spec
|
||||
node = spec.node_map().get(report_from)
|
||||
if node is None or node.type != NodeType.REPORT:
|
||||
gaps.append(f"契约的 report_from 指向的「{report_from}」不是报告撰写节点,引用核对未执行")
|
||||
return out
|
||||
payload = (state.get("nodes") or {}).get(report_from)
|
||||
doc_artifact = payload.get("doc_artifact") if isinstance(payload, dict) else None
|
||||
if not doc_artifact:
|
||||
gaps.append(f"报告撰写节点「{node.title}」没有产出报告文档(没跑到、被跳过或者失败了),"
|
||||
"引用核对未执行")
|
||||
return out
|
||||
out["doc_artifact"] = doc_artifact
|
||||
try:
|
||||
doc = load(doc_artifact)
|
||||
except ValueError:
|
||||
gaps.append(f"报告「{node.title}」的文档和它的哈希对不上,疑似被改过,引用核对未执行")
|
||||
return out
|
||||
if not isinstance(doc, dict):
|
||||
gaps.append(f"报告「{node.title}」的文档在工件库里取不回来,引用核对未执行")
|
||||
return out
|
||||
if doc.get("node_id") != report_from or doc.get("run_id") != ctx.run.run_id \
|
||||
or doc.get("markdown") != payload.get("text"):
|
||||
gaps.append(f"报告「{node.title}」的文档和这次运行里它的产出对不上,引用核对未执行")
|
||||
return out
|
||||
|
||||
catalog = report_catalog(state, spec, node)
|
||||
checked = verify_doc(doc, catalog, allow_numbers=contract.get("allow_numbers"))
|
||||
out["stats"] = checked["stats"]
|
||||
broken: list[str] = []
|
||||
flagged: set[str] = set()
|
||||
for v in checked["violations"]:
|
||||
where = {k: v[k] for k in ("segment", "unit") if v.get(k)}
|
||||
if v.get("span"):
|
||||
where.update(start=v["span"][0], end=v["span"][1])
|
||||
if v.get("segment"):
|
||||
flagged.add(v["segment"])
|
||||
if v["code"] == "uncited_number":
|
||||
out["unmatched"].append({"token": v.get("text", ""), "context": v.get("context", ""), **where})
|
||||
elif v["code"] == "unresolved_ref":
|
||||
out["unresolved"].append({"ref": v.get("ref", ""), "message": v["message"], **where})
|
||||
elif v["code"] in _INTEGRITY:
|
||||
broken.append(v["message"])
|
||||
if broken:
|
||||
more = f"等 {len(broken)} 处" if len(broken) > 1 else ""
|
||||
gaps.append(f"报告「{node.title}」的文档没通过复核:{broken[0]}{more}")
|
||||
|
||||
# 老前端要用的逐个数字出处,从复核通过的数字片段拼出来
|
||||
for _, unit in iter_units(doc):
|
||||
for seg in unit.get("segments") or []:
|
||||
if seg.get("kind") != "number" or not seg.get("ref") or seg.get("id") in flagged:
|
||||
continue
|
||||
cite = resolve_ref(str(seg["ref"]), catalog)
|
||||
if cite["status"] != "resolved" or cite["rendered"] != seg.get("text"):
|
||||
continue
|
||||
entry = catalog.get(cite["alias"]) or {}
|
||||
start, end = seg["span"]
|
||||
hit: dict[str, Any] = {"token": seg["text"], "metric": cite["locator"].get("metric")}
|
||||
if cite["kind"] == "metric":
|
||||
label = " @ ".join(str(v) for v in (entry.get("caliber"), entry.get("version")) if v)
|
||||
if label:
|
||||
hit["caliber"] = label
|
||||
else:
|
||||
hit["input"] = cite["locator"].get("field")
|
||||
out["matched"].append({**hit, "segment": seg["id"], "unit": unit["id"], "start": start, "end": end,
|
||||
"span": [start, end], "eid": cite["eid"]})
|
||||
|
||||
claims = contract.get("claims")
|
||||
policy = claims.get("policy") if isinstance(claims, dict) else claims
|
||||
if policy not in (None, "", "off"):
|
||||
gaps.append("契约声明了结论句检查(claims),这一版还不支持,结论句没有核对")
|
||||
|
||||
mine = next((r for r in reports if r["node"].id == report_from), None)
|
||||
edited = mine["edited"] if mine else []
|
||||
for name in edited:
|
||||
gaps.append(f"成果字段「{name}」改动了报告,无法逐段对应")
|
||||
if not (mine and mine["verbatim"]) and not edited:
|
||||
gaps.append(f"成果里没有哪个字段是报告「{node.title}」的原文:读者看到的内容没有经过引用核对")
|
||||
return out
|
||||
|
||||
|
||||
def _declare_citations(
|
||||
tier: str, cited: dict[str, Any], *, calibers: list[dict[str, str]], metrics: list[dict[str, Any]],
|
||||
gaps: list[str], missing_required: list[str], missing_expected: list[str], report_from: str,
|
||||
declared_at: Any, ctx: NodeContext,
|
||||
) -> dict[str, Any]:
|
||||
"""引用模式的 _issuance。旧字段一个不少(老前端照常显示),另加 mode、report、unresolved。"""
|
||||
report = {"node_id": report_from, "doc_artifact": cited["doc_artifact"]}
|
||||
issuance = {
|
||||
"mode": "citations",
|
||||
"tier": tier,
|
||||
"report": report,
|
||||
"calibers": calibers,
|
||||
"metrics_checked": len(metrics),
|
||||
"missing_required": missing_required,
|
||||
"missing_expected": missing_expected,
|
||||
"unmatched_numbers": cited["unmatched"][:20],
|
||||
"unresolved": cited["unresolved"][:20],
|
||||
"matched_numbers": len(cited["matched"]),
|
||||
"matched": cited["matched"][:50],
|
||||
"stats": cited["stats"],
|
||||
"gaps": gaps,
|
||||
"declared_at": declared_at.isoformat(),
|
||||
}
|
||||
ctx.emit(
|
||||
EventType.ISSUANCE,
|
||||
mode="citations",
|
||||
tier=tier,
|
||||
report=report,
|
||||
missing_required=missing_required,
|
||||
missing_expected=missing_expected,
|
||||
unmatched=len(cited["unmatched"]),
|
||||
unresolved=len(cited["unresolved"]),
|
||||
calibers=calibers,
|
||||
gaps=gaps,
|
||||
metrics_checked=len(metrics),
|
||||
matched_numbers=len(cited["matched"]),
|
||||
matched=cited["matched"][:50],
|
||||
)
|
||||
return issuance
|
||||
|
||||
|
||||
async def run_transform(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"""数据整形。用受限表达式把上游输出揉成下游要的形状,不用为此专门起一个 LLM。"""
|
||||
tctx = template_context(state)
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import describe_exception
|
||||
from app.core.events import EventType
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.expressions import ExpressionError, eval_expression
|
||||
from app.engine.evidence import DEFAULT_FORMAT, FORMATS, MISSING, RenderError, is_number, render_number
|
||||
from app.engine.expressions import ExpressionError, eval_expression, leaf_refs, parse_expression, substitute
|
||||
from app.engine.state import GraphState, template_context
|
||||
|
||||
|
||||
@@ -14,6 +18,10 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
表达式走 AST 白名单求值器——确定性、无模型参与、可复算。
|
||||
下游叙述节点只许引用这里登记过的数,出具校验器按这份清单抽数字回指。
|
||||
这就是"叙述层无算术权限"的机制载体:不是求模型别算,而是它算了也过不了校验。
|
||||
|
||||
每个指标还记下它是怎么来的:用到了哪些输入、各取自哪个节点、代入后的算式、
|
||||
拿代入式复算是否一致。整张卡落成 metric_set 工件,id 进证据台账——报告里的
|
||||
数字点开,一路能追到这里。
|
||||
"""
|
||||
definitions = ctx.cfg("metrics", []) or []
|
||||
if not definitions:
|
||||
@@ -22,6 +30,11 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
tctx = template_context(state)
|
||||
caliber = ctx.render_str(ctx.cfg("caliber", "") or ctx.node.title, state)
|
||||
caliber_version = str(ctx.cfg("caliber_version", "") or "v1")
|
||||
# 缺输入时怎么办。默认 fail:和以前一样整张卡失败;null 则这个指标记为空值、
|
||||
# 交给出具契约的 required / expected 去判档
|
||||
on_missing = str(ctx.cfg("on_missing", "fail") or "fail")
|
||||
if on_missing not in ("fail", "null"):
|
||||
raise NodeError(ctx.node.id, f"on_missing 只能是 fail 或 null,写的是 {on_missing!r}")
|
||||
|
||||
metrics: list[dict[str, Any]] = []
|
||||
errors: list[str] = []
|
||||
@@ -31,6 +44,20 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if not metric_id or not expr:
|
||||
errors.append(f"指标定义不完整:{definition}")
|
||||
continue
|
||||
display, problem = _display_of(definition)
|
||||
if problem:
|
||||
errors.append(f"{metric_id}: {problem}")
|
||||
continue
|
||||
try:
|
||||
tree, _, _ = parse_expression(expr)
|
||||
except ExpressionError as e:
|
||||
errors.append(f"{metric_id}: 表达式错误({e})")
|
||||
continue
|
||||
paths = leaf_refs(tree)
|
||||
values = {path: _value_of(path, tctx) for path in paths}
|
||||
missing = [path for path in paths if values[path] is None]
|
||||
|
||||
value: Any = None
|
||||
try:
|
||||
value = eval_expression(expr, tctx)
|
||||
except ExpressionError as e:
|
||||
@@ -39,9 +66,28 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
except ZeroDivisionError:
|
||||
errors.append(f"{metric_id}: 除以零")
|
||||
continue
|
||||
decimals = definition.get("decimals")
|
||||
except Exception as e: # noqa: BLE001 - 求值器之外的运算错误(None 参与算术、类型不对)要说人话
|
||||
if missing or "NoneType" in str(e):
|
||||
if on_missing != "null":
|
||||
errors.append(f"{metric_id}: " + _missing_reason(missing))
|
||||
continue
|
||||
value = None
|
||||
elif isinstance(e, TypeError):
|
||||
errors.append(f"{metric_id}: 输入的类型不对,算不出来——" + _type_hint(paths, values))
|
||||
continue
|
||||
else:
|
||||
errors.append(f"{metric_id}: 算不出来({describe_exception(e)})")
|
||||
continue
|
||||
|
||||
if display["bad_decimals"] and isinstance(value, float):
|
||||
# 旧写法里 int() 认不得的 decimals:以前走到 round(value, int(decimals)) 就崩,
|
||||
# 现在照样算失败,只是说人话。值不是小数时以前根本用不到它,照旧忽略
|
||||
errors.append(f"{metric_id}: decimals 要写整数,写的是 {definition.get('decimals')!r}")
|
||||
continue
|
||||
decimals = display["decimals"]
|
||||
if isinstance(value, float) and decimals is not None:
|
||||
value = round(value, int(decimals))
|
||||
value = round(value, decimals)
|
||||
substituted = substitute(tree, values)
|
||||
metrics.append(
|
||||
{
|
||||
"id": metric_id,
|
||||
@@ -49,6 +95,15 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"unit": definition.get("unit") or "",
|
||||
"value": value,
|
||||
"expression": expr,
|
||||
"decimals": decimals,
|
||||
"format": display["format"],
|
||||
"rendered": _rendered(value, definition, display),
|
||||
"inputs": [_input_of(path, values[path], state, ctx) for path in paths],
|
||||
"substituted": substituted,
|
||||
"recompute_ok": _recompute(substituted, tctx, value, decimals),
|
||||
# 值是空的就是缺输入,不论 on_missing 是哪一种:fail 模式下直接取到空值的
|
||||
# 指标(原式就是 vars.x.y 而 y 不存在)以前也是照常产出一个 None
|
||||
"status": "ok" if value is not None else "missing_input",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -57,12 +112,20 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
raise NodeError(ctx.node.id, "口径卡计算失败:" + ";".join(errors))
|
||||
|
||||
# text 是给叙述节点 prompt 用的清单——它是叙述层唯一的数字来源
|
||||
lines = [f"- {m['id']}({m['name']})= {m['value']}{m['unit']}" for m in metrics]
|
||||
result = {
|
||||
lines = [
|
||||
f"- {m['id']}({m['name']})= {m['value']}{m['unit']}" if m["value"] is not None
|
||||
else f"- {m['id']}({m['name']})= {MISSING}(缺输入,没有值)"
|
||||
for m in metrics
|
||||
]
|
||||
card = {
|
||||
"kind": "metric_set",
|
||||
"caliber": caliber,
|
||||
"caliber_version": caliber_version,
|
||||
"metrics": metrics,
|
||||
}
|
||||
artifact = await _store(card, caliber, caliber_version, ctx)
|
||||
result = {
|
||||
**card,
|
||||
"text": f"指标清单(口径 {caliber} @ {caliber_version}):\n" + "\n".join(lines),
|
||||
}
|
||||
ctx.emit(
|
||||
@@ -72,7 +135,212 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
|
||||
if artifact:
|
||||
result["artifact"] = artifact
|
||||
executed = sum(1 for t in state.get("trail") or []
|
||||
if t.get("node_id") == ctx.node.id and "error" not in t)
|
||||
updates["evidence"] = [{
|
||||
"kind": "metric_set",
|
||||
"node_id": ctx.node.id,
|
||||
"exec": executed + 1,
|
||||
"artifact": artifact,
|
||||
"caliber": caliber,
|
||||
"version": caliber_version,
|
||||
"metrics": [m["id"] for m in metrics],
|
||||
}]
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: result}
|
||||
return updates
|
||||
|
||||
|
||||
#: 新写法的小数位范围。负数是取整到十位、百位(round(x, -2))
|
||||
_DECIMALS_RANGE = 15
|
||||
|
||||
|
||||
def _display_of(definition: dict[str, Any]) -> tuple[dict[str, Any], str | None]:
|
||||
"""指标的显示格式:{decimals, format, bad_decimals},以及写错时的一句话。
|
||||
|
||||
写了 format 的是新写法,decimals 严格校验:-15 到 15 的整数。
|
||||
没写 format 的是这一期之前的口径卡,旧代码能接受的照旧接受:以前只在值是小数时
|
||||
round(value, int(decimals)),所以 int() 认得的都算数("2"、-2、12);int() 认不得的
|
||||
记成 bad_decimals,由调用方按值的类型决定——值是小数才报错(以前在这里崩),
|
||||
不是小数就忽略(以前根本用不到它)。
|
||||
"""
|
||||
raw = definition.get("decimals")
|
||||
strict = definition.get("format") not in (None, "")
|
||||
fmt = definition.get("format") or DEFAULT_FORMAT
|
||||
if fmt not in FORMATS:
|
||||
return {}, f"format 只能是 {' / '.join(FORMATS)},写的是 {fmt!r}"
|
||||
display: dict[str, Any] = {"decimals": None, "format": fmt, "bad_decimals": False}
|
||||
if raw in (None, ""):
|
||||
return display, None
|
||||
if strict:
|
||||
decimals = _integer(raw)
|
||||
if decimals is None or not -_DECIMALS_RANGE <= decimals <= _DECIMALS_RANGE:
|
||||
return {}, (f"decimals 要写 -{_DECIMALS_RANGE} 到 {_DECIMALS_RANGE} 的整数"
|
||||
f"(负数表示取整到十位、百位),写的是 {raw!r}")
|
||||
display["decimals"] = decimals
|
||||
return display, None
|
||||
try:
|
||||
display["decimals"] = int(raw)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
display["bad_decimals"] = True
|
||||
return display, None
|
||||
|
||||
|
||||
def _integer(raw: Any) -> int | None:
|
||||
"""严格的整数:2、2.0、"2"、"-2" 算;1.5、"两位"、true 不算。"""
|
||||
if isinstance(raw, bool):
|
||||
return None
|
||||
if isinstance(raw, int):
|
||||
return raw
|
||||
if isinstance(raw, float):
|
||||
return int(raw) if raw.is_integer() else None
|
||||
if isinstance(raw, str) and re.fullmatch(r"\s*[+-]?\d+\s*", raw):
|
||||
return int(raw)
|
||||
return None
|
||||
|
||||
|
||||
def _rendered(value: Any, definition: dict[str, Any], display: dict[str, Any]) -> str:
|
||||
try:
|
||||
return render_number(value, unit=str(definition.get("unit") or ""),
|
||||
decimals=display["decimals"], fmt=display["format"])
|
||||
except RenderError:
|
||||
# 按规则渲染不出来的值显示「—」:inf / nan、不是 0 却会显示成 0 的(小数位不够)、
|
||||
# 位数大到不像话的。值本身照旧记着,报告里引用它会被判成解析不了,原因写清楚
|
||||
return MISSING
|
||||
|
||||
|
||||
def _value_of(path: str, tctx: dict[str, Any]) -> Any:
|
||||
"""单独取一个引用的值。取不到(或取值本身出错)一律当作没有值。"""
|
||||
try:
|
||||
return eval_expression(path, tctx)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _missing_reason(missing: list[str]) -> str:
|
||||
if not missing:
|
||||
return "有输入是空值,算不出来(检查上游有没有产出这些字段)"
|
||||
return f"输入 {'、'.join(missing[:4])} 没有值,算不出来(上游没有产出这个字段,或者路径写错了)"
|
||||
|
||||
|
||||
def _type_hint(paths: list[str], values: dict[str, Any]) -> str:
|
||||
kinds = {bool: "布尔值", str: "文本", list: "列表", dict: "对象"}
|
||||
parts = []
|
||||
for path in paths:
|
||||
value = values[path]
|
||||
if value is None or is_number(value):
|
||||
continue
|
||||
label = next((name for t, name in kinds.items() if isinstance(value, t)), type(value).__name__)
|
||||
sample = f"「{str(value)[:20]}」" if isinstance(value, str) else ""
|
||||
parts.append(f"{path} 是{label}{sample}")
|
||||
if not parts:
|
||||
return "参与运算的值不是数"
|
||||
return "、".join(parts[:4]) + ",不能参与数值运算"
|
||||
|
||||
|
||||
_REF_HEAD = re.compile(r"^(vars|nodes|input)\.([A-Za-z_一-鿿][\w\-一-鿿]*)(.*)$", re.S)
|
||||
_VIA = {"input": "input", "code": "code", "agent": "agent", "llm": "llm", "tool": "tool",
|
||||
"transform": "transform", "metrics": "metric", "retrieve": "retrieval", "loop": "loop",
|
||||
"human": "human", "validate": "validate", "supervisor": "team", "subgraph": "subgraph",
|
||||
"memory": "memory"}
|
||||
|
||||
|
||||
def _input_of(path: str, value: Any, state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"""一个输入的来历:{path, value, node_id, via, field?, role?, status}。
|
||||
|
||||
vars.X 要反查是谁写的:assign_to 为 X 的节点里,按执行顺序最后跑的那一个——
|
||||
和状态里 vars 的覆盖顺序一致。入口节点把输入字段也写进 vars。
|
||||
"""
|
||||
spec = ctx.run.spec
|
||||
nodes = spec.node_map()
|
||||
node_id: str | None = None
|
||||
field = ""
|
||||
head = _REF_HEAD.match(path)
|
||||
if head:
|
||||
root, name, rest = head.groups()
|
||||
field = rest.lstrip(".")
|
||||
if root == "nodes":
|
||||
node_id = name if name in nodes else None
|
||||
elif root == "input":
|
||||
node_id = next((n.id for n in spec.entry_nodes() if str(n.type) == "input"), None)
|
||||
else:
|
||||
node_id = _writer_of(name, state, ctx)
|
||||
producer = nodes.get(node_id) if node_id else None
|
||||
entry: dict[str, Any] = {
|
||||
"path": path,
|
||||
"value": value if value is None or isinstance(value, (int, float, str, bool)) else _brief(value),
|
||||
"node_id": node_id,
|
||||
"via": _VIA.get(str(producer.type), str(producer.type)) if producer else "state",
|
||||
}
|
||||
if field:
|
||||
entry["field"] = field
|
||||
if producer is not None and str(producer.type) == "code":
|
||||
# 沙箱算出来的数喂给口径卡:记下它自认是「取数」还是「计算」,治理规则按它判
|
||||
entry["role"] = str(producer.config.get("evidence_role") or "compute")
|
||||
entry["status"] = "ok" if value is not None else "missing"
|
||||
return entry
|
||||
|
||||
|
||||
def _writer_of(var: str, state: GraphState, ctx: NodeContext) -> str | None:
|
||||
nodes = ctx.run.spec.node_map()
|
||||
|
||||
def writes(node_id: str) -> bool:
|
||||
node = nodes.get(node_id)
|
||||
if node is None:
|
||||
return False
|
||||
cfg = node.config
|
||||
if str(cfg.get("assign_to") or "").strip() == var:
|
||||
return True
|
||||
if str(node.type) == "input":
|
||||
return var in (state.get("input") or {})
|
||||
if str(node.type) == "loop":
|
||||
item = str(cfg.get("item_var") or "item").strip()
|
||||
return var in (item, f"{item}_index")
|
||||
return False
|
||||
|
||||
for step in reversed(state.get("trail") or []):
|
||||
node_id = step.get("node_id")
|
||||
if node_id and "error" not in step and writes(node_id):
|
||||
return node_id
|
||||
# 没有执行记录可查(比如直接调用执行器):按图里声明的写入者兜底
|
||||
return next((n.id for n in ctx.run.spec.nodes if writes(n.id)), None)
|
||||
|
||||
|
||||
def _brief(value: Any) -> str:
|
||||
"""容器型的输入不整份抄进指标:记个大概,完整的在上游节点的产出工件里。"""
|
||||
if isinstance(value, list):
|
||||
return f"[{len(value)} 项]"
|
||||
if isinstance(value, dict):
|
||||
return f"{{{len(value)} 个字段}}"
|
||||
return str(value)[:200]
|
||||
|
||||
|
||||
def _recompute(substituted: str, tctx: dict[str, Any], value: Any, decimals: int | None) -> bool | None:
|
||||
"""拿代入式再算一遍,和结果比对。值是空的就没有可比的,返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
again = eval_expression(substituted, tctx)
|
||||
except Exception: # noqa: BLE001 - 代入式算不出来本身就是「对不上」
|
||||
return False
|
||||
if isinstance(again, float) and decimals is not None:
|
||||
again = round(again, decimals)
|
||||
if is_number(again) and is_number(value):
|
||||
return math.isclose(again, value, rel_tol=1e-12, abs_tol=0.0) or again == value
|
||||
return again == value
|
||||
|
||||
|
||||
async def _store(card: dict[str, Any], caliber: str, version: str, ctx: NodeContext) -> str | None:
|
||||
"""整张卡落成 metric_set 工件。写失败不毁掉运行,只是这张卡没法被引用。"""
|
||||
from app.core.artifact_store import put_json
|
||||
|
||||
try:
|
||||
return await put_json(card, kind="metric_set", run_id=ctx.run.run_id, node_id=ctx.node.id,
|
||||
meta={"caliber": caliber, "version": version})
|
||||
except Exception as e: # noqa: BLE001
|
||||
ctx.emit(EventType.LOG, level="warn", code="evidence_store_failed",
|
||||
message=f"口径卡的指标集没能落进工件库({describe_exception(e)}),报告里没法引用它的指标")
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
"""报告撰写节点:模型只写引用标记,数字由系统从口径卡取出来渲染。
|
||||
|
||||
以前「给人看的报告」是 llm 节点写的自由文本:数字是模型转写的,出处要到出口再按
|
||||
数值回头猜——同值的指标一多就猜错,模型顺手写的数也要到出口才被发现。这里把核对
|
||||
挪到写的那一刻:
|
||||
|
||||
1. 建目录:收齐上游口径卡的指标和运行输入,编成 [[m:gmv]]、[[i:week]] 这样的引用
|
||||
2. 流式写作:模型写标记,StreamRenderer 边收边换成真值,流里看到的就是最终的数字
|
||||
3. 核对:compose_doc 切块、分句、切片段,找出裸数字和解析不了的引用
|
||||
4. 修复:有违规就把清单交回去重写,最多 max_repairs 次
|
||||
5. 收尾:文档落成 report_doc 工件,report.checked 事件进封存;仍然违规时按
|
||||
on_violation 失败(fail)或者照常产出、把违规片段标出来(flag)
|
||||
|
||||
出口契约复核(io.py)用 report_catalog 按同一套参数重建目录、独立重算,不信这里的自查。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
|
||||
|
||||
from app.core.errors import describe_exception
|
||||
from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.evidence import (
|
||||
MARKER_RULES,
|
||||
StreamRenderer,
|
||||
build_catalog,
|
||||
catalog_prompt,
|
||||
compose_doc,
|
||||
describe_violations,
|
||||
)
|
||||
from app.engine.nodes.llm import _invoke_streaming, _model_spec, _report_call
|
||||
from app.engine.schema import GraphNode, GraphSpec, NodeType, _ancestors
|
||||
from app.engine.state import GraphState, message_text, thinking_text
|
||||
from app.engine.toolcalls import leaked_markup, markup_warning
|
||||
from app.providers.factory import ProviderNotConfigured, get_chat_model
|
||||
|
||||
ON_VIOLATION = ("fail", "flag")
|
||||
NUMBERS = ("strict", "off")
|
||||
#: 重写一次就是多一次整篇的模型调用,写不对的模型多给几次也大多写不对
|
||||
MAX_REPAIRS = 3
|
||||
|
||||
ROLE = ("你是报告撰写人。报告里的每个数字都由系统从证据里取出来、按口径卡的格式渲染;"
|
||||
"你负责挑重点、组织结构、说清变化和原因。")
|
||||
|
||||
MARKUP_NUDGE = ("你上一条回复把工具调用写成了文字。报告撰写不调用任何工具:能用的数据都在上面的"
|
||||
"证据目录里,直接用引用标记写报告正文。")
|
||||
MARKUP_ERROR = ("模型输出了工具调用的原始标记,而报告撰写节点不调用工具——数据已经在证据目录里。"
|
||||
"换一个模型再试")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 目录与放行名单:出口复核要用同一套参数重建,所以不依赖 NodeContext
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _setting(spec: GraphSpec, node: GraphNode, key: str, default: Any = None) -> Any:
|
||||
"""和 NodeContext.cfg 同一个规则:节点上没写就取图级 defaults。"""
|
||||
value = node.config.get(key)
|
||||
if value in (None, ""):
|
||||
return spec.defaults.get(key, default)
|
||||
return value
|
||||
|
||||
|
||||
def report_catalog(state: GraphState, spec: GraphSpec, node: GraphNode) -> dict[str, Any]:
|
||||
"""报告节点的证据目录。
|
||||
|
||||
出口契约复核必须用这一个函数重建:参数(metrics_from、evidence_from、祖先范围)
|
||||
差一点,alias 集合就不一样——同一个指标 id 在两张卡里时,只收一张写 m:gmv,
|
||||
全收就得写 m:east.gmv——复核会把一份好好的报告判成引用解析不了。
|
||||
"""
|
||||
ledger = [e for e in state.get("evidence") or [] if isinstance(e, dict)]
|
||||
sources = _setting(spec, node, "evidence_from", "ancestors")
|
||||
if isinstance(sources, str) and sources != "ancestors":
|
||||
sources = [sources]
|
||||
if isinstance(sources, list):
|
||||
# evidence_from 只管查询、检索这类证据从哪几个节点来;指标从哪来由 metrics_from 管
|
||||
keep = {str(s) for s in sources}
|
||||
ledger = [e for e in ledger if e.get("kind") not in ("query", "retrieval") or e.get("node_id") in keep]
|
||||
return build_catalog(
|
||||
nodes=state.get("nodes") or {},
|
||||
ledger=ledger,
|
||||
inputs=state.get("input") or {},
|
||||
metrics_from=_setting(spec, node, "metrics_from") or None,
|
||||
allowed=_ancestors(spec, node.id),
|
||||
)
|
||||
|
||||
|
||||
def report_allowance(spec: GraphSpec, node: GraphNode) -> list[Any]:
|
||||
"""报告自查放行的字面量:出口契约 report_from 指向它时,契约的 allow_numbers。
|
||||
|
||||
契约放行、报告却不放行的话,写作者会为一个最终根本不算违规的数白白重写一次。
|
||||
反过来不成立:放行名单只由契约定,报告节点没有自己的名单——出口复核是独立的裁判。
|
||||
"""
|
||||
allowed: list[Any] = []
|
||||
for other in spec.nodes:
|
||||
contract = other.config.get("contract") if other.type == NodeType.OUTPUT else None
|
||||
if isinstance(contract, dict) and contract.get("report_from") == node.id:
|
||||
extra = contract.get("allow_numbers") or []
|
||||
allowed.extend(extra if isinstance(extra, list) else [extra])
|
||||
return allowed
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 执行器
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _RenderedStream:
|
||||
"""借 _invoke_streaming 的流式与回退逻辑,只在出口把 llm.token 换成渲染后的字。
|
||||
|
||||
模型写的是 [[m:gmv]],前端要看到的是「45,678.5元」。标记会被切在两个 chunk
|
||||
中间,StreamRenderer 攒到没有未闭合的 [[ 再放;调用结束时 flush 掉剩下的。
|
||||
"""
|
||||
|
||||
def __init__(self, ctx: NodeContext, catalog: dict[str, Any]) -> None:
|
||||
self._ctx = ctx
|
||||
self._catalog = catalog
|
||||
self._renderer = StreamRenderer(catalog)
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._ctx, name)
|
||||
|
||||
def emit(self, event_type: EventType | str, **data: Any) -> None:
|
||||
if event_type == EventType.LLM_TOKEN:
|
||||
if text := self._renderer.feed(str(data.get("delta") or "")):
|
||||
self._ctx.emit(EventType.LLM_TOKEN, delta=text)
|
||||
return
|
||||
if event_type == EventType.LOG and data.get("code") == "stream_fallback":
|
||||
# 流断在半路、退回非流式重来:攒着的半截不再放出去,免得和重来的那份接在一起
|
||||
self._renderer = StreamRenderer(self._catalog)
|
||||
self._ctx.emit(event_type, **data)
|
||||
|
||||
def flush(self) -> None:
|
||||
if tail := self._renderer.flush():
|
||||
self._ctx.emit(EventType.LLM_TOKEN, delta=tail)
|
||||
|
||||
|
||||
async def _default_on_violation(run_id: str) -> str:
|
||||
"""探索运行默认标注、照常产出;正式运行默认失败——封存的发布版不能带着裸数字出具。"""
|
||||
from app.db.models import Run
|
||||
|
||||
async with SessionLocal() as session:
|
||||
run = await session.get(Run, run_id)
|
||||
return "fail" if run is not None and run.run_class == "formal" else "flag"
|
||||
|
||||
|
||||
def _options(ctx: NodeContext) -> tuple[str, int]:
|
||||
numbers = str(ctx.cfg("numbers", "strict") or "strict")
|
||||
if numbers not in NUMBERS:
|
||||
raise NodeError(ctx.node.id, f"numbers 只能是 {' / '.join(NUMBERS)},写的是 {numbers!r}")
|
||||
raw = ctx.cfg("max_repairs", 1)
|
||||
try:
|
||||
repairs = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise NodeError(ctx.node.id, f"max_repairs 要写 0 到 {MAX_REPAIRS} 的整数,写的是 {raw!r}") from None
|
||||
if isinstance(raw, bool) or not 0 <= repairs <= MAX_REPAIRS:
|
||||
raise NodeError(ctx.node.id, f"max_repairs 要写 0 到 {MAX_REPAIRS} 的整数,写的是 {raw!r}")
|
||||
return numbers, repairs
|
||||
|
||||
|
||||
def _blocking(violations: list[dict[str, Any]], numbers: str) -> list[dict[str, Any]]:
|
||||
"""要让写作者改的违规。numbers=off 时裸数字只记录不拦(文档和出口复核照样看得到)。"""
|
||||
return [v for v in violations if not (numbers == "off" and v.get("code") == "uncited_number")]
|
||||
|
||||
|
||||
def _named(violations: list[dict[str, Any]], limit: int = 3) -> str:
|
||||
"""违规里点名的那几个字:「45678」「m:nope」。"""
|
||||
names = [str(v.get("text") or v.get("ref") or "") for v in violations]
|
||||
names = [n for n in dict.fromkeys(names) if n][:limit]
|
||||
return "、".join(f"「{n}」" for n in names)
|
||||
|
||||
|
||||
def _repair_request(violations: list[dict[str, Any]]) -> str:
|
||||
return (
|
||||
"你写的报告没有通过系统核对,问题如下:\n"
|
||||
f"{describe_violations(violations)}\n\n"
|
||||
"请重写整篇报告:所有数字都用引用标记写,只引用证据目录里有的指标和输入;"
|
||||
"不要解释改了什么,只输出新的报告正文。"
|
||||
)
|
||||
|
||||
|
||||
def _messages(ctx: NodeContext, state: GraphState, catalog: dict[str, Any]) -> list[BaseMessage]:
|
||||
system = ctx.render_str(ctx.cfg("system", ""), state)
|
||||
instructions = ctx.render_str(ctx.cfg("instructions", ""), state).strip() \
|
||||
or "根据下面的证据写一份简洁的报告,先总后分。"
|
||||
return [
|
||||
SystemMessage(content="\n\n".join(p for p in (system, ROLE) if p)),
|
||||
HumanMessage(content=(
|
||||
f"{instructions}\n\n{catalog_prompt(catalog)}\n\n{MARKER_RULES}\n\n"
|
||||
"只输出报告正文(Markdown),不要写撰写说明。"
|
||||
)),
|
||||
]
|
||||
|
||||
|
||||
async def _store(doc: dict[str, Any], ctx: NodeContext) -> str | None:
|
||||
from app.core.artifact_store import put_json
|
||||
|
||||
try:
|
||||
return await put_json(doc, kind="report_doc", run_id=ctx.run.run_id, node_id=ctx.node.id,
|
||||
meta={"stats": doc.get("stats") or {}})
|
||||
except Exception as e: # noqa: BLE001 - 工件写失败不毁掉运行,只是这份报告点不开证据
|
||||
ctx.emit(EventType.LOG, level="warn", code="evidence_store_failed",
|
||||
message=f"报告文档没能落进工件库({describe_exception(e)}),报告里的数字点不开证据")
|
||||
return None
|
||||
|
||||
|
||||
async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
numbers, max_repairs = _options(ctx)
|
||||
on_violation = str(ctx.cfg("on_violation", "") or "") or await _default_on_violation(ctx.run.run_id)
|
||||
if on_violation not in ON_VIOLATION:
|
||||
raise NodeError(ctx.node.id, f"on_violation 只能是 {' / '.join(ON_VIOLATION)},写的是 {on_violation!r}")
|
||||
|
||||
async with SessionLocal() as session:
|
||||
try:
|
||||
model, model_id = await get_chat_model(session, _model_spec(ctx))
|
||||
except ProviderNotConfigured as e:
|
||||
raise NodeError(ctx.node.id, str(e)) from e
|
||||
|
||||
spec = ctx.run.spec
|
||||
catalog = report_catalog(state, spec, ctx.node)
|
||||
allow = report_allowance(spec, ctx.node)
|
||||
if not any(entry.get("kind") == "metric" for entry in catalog.values()):
|
||||
ctx.emit(EventType.LOG, level="warn", code="report_no_evidence",
|
||||
message="报告撰写节点的上游没有可引用的口径卡指标:报告里的数字都会被判为没有出处。"
|
||||
"在它前面接一张口径卡,或者检查 metrics_from")
|
||||
|
||||
messages = _messages(ctx, state, catalog)
|
||||
started = time.perf_counter()
|
||||
spent: list[dict[str, Any]] = []
|
||||
nudged = False
|
||||
|
||||
async def draft(payload: list[BaseMessage]) -> tuple[BaseMessage, str]:
|
||||
nonlocal nudged
|
||||
stream = _RenderedStream(ctx, catalog)
|
||||
began = time.perf_counter()
|
||||
response = await _invoke_streaming(model, payload, stream, model_id) # type: ignore[arg-type]
|
||||
stream.flush()
|
||||
spent.append(_report_call(ctx, response, model_id, began))
|
||||
text = message_text(response)
|
||||
if snippet := leaked_markup(text):
|
||||
# 写成了一段工具调用标记:纠正一次,还这样就判失败,别把标记当报告往下游送
|
||||
if nudged:
|
||||
raise NodeError(ctx.node.id, MARKUP_ERROR)
|
||||
nudged = True
|
||||
ctx.emit(EventType.LOG, level="warn", code="tool_markup_leak",
|
||||
message=f"{markup_warning(snippet)},已提醒它重试一次")
|
||||
return await draft([*payload, response, HumanMessage(content=MARKUP_NUDGE)])
|
||||
if not text and thinking_text(response):
|
||||
ctx.emit(EventType.LOG, level="warn", code="empty_completion",
|
||||
message="模型只输出了思考内容,报告正文为空。把 max_tokens 调大,或把 thinking 设为 off。")
|
||||
return response, text
|
||||
|
||||
def compose(raw: str) -> dict[str, Any]:
|
||||
return compose_doc(raw, catalog, node_id=ctx.node.id, run_id=ctx.run.run_id, allow_numbers=allow)
|
||||
|
||||
response, raw = await draft(messages)
|
||||
doc = compose(raw)
|
||||
repairs = 0
|
||||
while (blocking := _blocking(doc["violations"], numbers)) and repairs < max_repairs:
|
||||
repairs += 1
|
||||
ctx.emit(EventType.LOG, level="warn", code="report_repair",
|
||||
message=f"报告里有 {len(blocking)} 处没通过核对({_named(blocking)}),"
|
||||
f"已要求写作者重写(第 {repairs} 次)")
|
||||
messages = [*messages, response, HumanMessage(content=_repair_request(blocking))]
|
||||
response, raw = await draft(messages)
|
||||
doc = compose(raw)
|
||||
|
||||
doc_artifact = await _store(doc, ctx)
|
||||
ctx.emit(EventType.REPORT_CHECKED, doc_artifact=doc_artifact, ok=not doc["violations"],
|
||||
stats=doc["stats"], violations=doc["violations"][:20], repairs=repairs,
|
||||
on_violation=on_violation, failed=bool(blocking) and on_violation == "fail")
|
||||
if blocking and on_violation == "fail":
|
||||
head = ";".join(v["message"] for v in blocking[:5])
|
||||
more = f";…另有 {len(blocking) - 5} 处" if len(blocking) > 5 else ""
|
||||
raise NodeError(
|
||||
ctx.node.id,
|
||||
f"报告有 {len(blocking)} 处没通过核对(已要求重写 {repairs} 次):{head}{more}。"
|
||||
"换一个遵从度更高的模型,或者先把 on_violation 设成 flag,把问题标注在报告里再看",
|
||||
)
|
||||
|
||||
usage = {key: sum(one[key] for one in spent) for key in spent[0]}
|
||||
usage["cost_usd"] = round(usage["cost_usd"], 6)
|
||||
text = doc["markdown"]
|
||||
result = {
|
||||
"text": text,
|
||||
"doc_artifact": doc_artifact,
|
||||
"stats": doc["stats"],
|
||||
"violations": doc["violations"][:20],
|
||||
"repairs": repairs,
|
||||
"model": model_id,
|
||||
"duration_ms": int((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}, "usage": usage}
|
||||
if ctx.cfg("emit_message", True):
|
||||
updates["messages"] = [AIMessage(content=text or "(空)")]
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: text}
|
||||
return updates
|
||||
@@ -80,6 +80,13 @@ WARN_CODES: dict[str, tuple[str, str]] = {
|
||||
"team_last_failed": ("team_last_failed", DEGRADED),
|
||||
# 校验节点的修复编出了原文没有的值,这次修复被作废
|
||||
"repair_invented": ("repair_invented", DEGRADED),
|
||||
# 报告撰写节点:写作者写了裸数字或引用了不存在的指标,被要求重写。重写好了的
|
||||
# 答案是核对过的,只记缺口;没好的那次按 on_violation 失败或把违规标在报告里
|
||||
"report_repair": ("report_repair", DEGRADED),
|
||||
# 报告撰写节点的上游没有可引用的口径卡指标:报告里的数都没有出处
|
||||
"report_no_evidence": ("report_no_evidence", DEGRADED),
|
||||
# 口径卡的指标集、报告文档没能落进工件库:答案照常,只是点不开证据
|
||||
"evidence_store_failed": ("evidence_store_failed", DEGRADED),
|
||||
}
|
||||
|
||||
# 这些 kind 重跑一次大概率能好:原因说得清,且不是「问题本身没问明白」。
|
||||
@@ -253,7 +260,14 @@ REVIEW_SCHEMA: dict[str, Any] = {
|
||||
}
|
||||
|
||||
|
||||
def review_prompt(question: str, answer: str, signals: list[Signal]) -> str:
|
||||
#: 答案带着逐段证据时追加给复核模型的话
|
||||
LOCKED_NOTE = (
|
||||
"\n\n这份答案带有逐段证据(报告里的每个数字都对应着核对过的出处),不能改写:"
|
||||
"answer 必须留空,只在 note 里说明异常。"
|
||||
)
|
||||
|
||||
|
||||
def review_prompt(question: str, answer: str, signals: list[Signal], *, locked: bool = False) -> str:
|
||||
"""拼给复核模型的请求。
|
||||
|
||||
只给信号清单,不给原始事件流:几百条事件塞进 prompt 既贵又没用,而信号
|
||||
@@ -266,6 +280,7 @@ def review_prompt(question: str, answer: str, signals: list[Signal]) -> str:
|
||||
f"用户的问题:\n{question or '(未记录)'}\n\n"
|
||||
f"系统给出的原答案:\n{answer or '(空)'}\n\n"
|
||||
f"检测到的异常:\n{lines}"
|
||||
+ (LOCKED_NOTE if locked else "")
|
||||
)
|
||||
|
||||
|
||||
@@ -296,12 +311,15 @@ class ReviewResult:
|
||||
|
||||
|
||||
async def review(
|
||||
model: Any, *, question: str, answer: str, signals: list[Signal]
|
||||
model: Any, *, question: str, answer: str, signals: list[Signal], locked: bool = False,
|
||||
) -> ReviewResult:
|
||||
"""叫一次模型复核。调用方负责确保 signals 非空——空信号根本不该走到这里。
|
||||
|
||||
复核本身失败不能让整轮挂掉:答案已经在手上了,复核只是加一层说明。
|
||||
所以这里把异常全兜住,最差也要把原答案原样交出去。
|
||||
|
||||
locked:成果带 _evidence(报告撰写节点产出、逐段对应证据文档)。这种答案只能
|
||||
加说明、不能改写——改写之后界面上点开的出处,指向的是一段已经不存在的文字。
|
||||
"""
|
||||
severity = worst(signals)
|
||||
rule_retry = should_retry(signals)
|
||||
@@ -309,7 +327,7 @@ async def review(
|
||||
s.detail for s in signals
|
||||
)
|
||||
|
||||
messages = [("system", REVIEW_SYSTEM), ("human", review_prompt(question, answer, signals))]
|
||||
messages = [("system", REVIEW_SYSTEM), ("human", review_prompt(question, answer, signals, locked=locked))]
|
||||
try:
|
||||
raw = await model.with_structured_output(REVIEW_SCHEMA).ainvoke(messages)
|
||||
if not isinstance(raw, dict):
|
||||
@@ -334,7 +352,7 @@ async def review(
|
||||
# 白烧一次建图加一次跑图。模型没表态时按规则走
|
||||
retry = rule_retry and bool(raw.get("retry", True))
|
||||
|
||||
if not revised or revised == answer.strip():
|
||||
if locked or not revised or revised == answer.strip():
|
||||
return ReviewResult(
|
||||
verdict="annotated", note=note, retry=retry, signals=signals, severity=severity,
|
||||
)
|
||||
|
||||
@@ -32,6 +32,7 @@ class NodeType(StrEnum):
|
||||
HUMAN = "human" # 人工介入
|
||||
VALIDATE = "validate" # 结构化校验 + 自动重试
|
||||
METRICS = "metrics" # 口径卡:受控指标集,叙述层唯一合法的数字来源
|
||||
REPORT = "report" # 报告撰写:模型只写引用标记,数字由系统从口径卡取出来渲染
|
||||
|
||||
|
||||
# 节点类型在画布上的叫法。报错和门禁文案用它,而不是枚举值——用户在界面上从没
|
||||
@@ -41,7 +42,7 @@ TYPE_LABEL: dict[str, str] = {
|
||||
"supervisor": "多 Agent 协作", "tool": "调用工具", "code": "沙箱代码",
|
||||
"branch": "条件分支", "loop": "循环", "subgraph": "子工作流",
|
||||
"memory": "长期记忆", "retrieve": "知识检索", "transform": "数据整形",
|
||||
"human": "人工审批", "validate": "结构校验", "metrics": "口径卡",
|
||||
"human": "人工审批", "validate": "结构校验", "metrics": "口径卡", "report": "报告撰写",
|
||||
}
|
||||
|
||||
|
||||
@@ -367,6 +368,75 @@ def _check_case_keys(node: GraphNode, cases: list[Any], result: ValidationResult
|
||||
seen.add(key)
|
||||
|
||||
|
||||
def _ancestors(spec: GraphSpec, node_id: str) -> set[str]:
|
||||
"""沿连线往回走能到的所有节点(不含自己)。循环里的节点彼此都算上游。"""
|
||||
parents: dict[str, list[str]] = defaultdict(list)
|
||||
for e in spec.edges:
|
||||
parents[e.target].append(e.source)
|
||||
seen: set[str] = set()
|
||||
stack = list(parents[node_id])
|
||||
while stack:
|
||||
cur = stack.pop()
|
||||
if cur not in seen:
|
||||
seen.add(cur)
|
||||
stack.extend(parents[cur])
|
||||
seen.discard(node_id)
|
||||
return seen
|
||||
|
||||
|
||||
def _check_report_sources(node: GraphNode, spec: GraphSpec, result: ValidationResult) -> None:
|
||||
"""报告的 metrics_from 只能指向它上游的口径卡。
|
||||
|
||||
指错了运行时不会报错:目录里就是没有那张卡的指标,模型要么写不出数、要么被
|
||||
判成引用不存在——在画图时说破比跑完再猜原因便宜得多。
|
||||
"""
|
||||
sources = node.config.get("metrics_from")
|
||||
if sources in (None, "", []):
|
||||
return # 不写就取所有上游口径卡
|
||||
if isinstance(sources, str):
|
||||
sources = [sources]
|
||||
if not isinstance(sources, list) or not all(isinstance(s, str) and s for s in sources):
|
||||
result.add("「报告撰写」的 metrics_from 要写口径卡节点的 id 列表", node_id=node.id,
|
||||
field="metrics_from")
|
||||
return
|
||||
nodes = spec.node_map()
|
||||
upstream = _ancestors(spec, node.id)
|
||||
for src in sources:
|
||||
target = nodes.get(src)
|
||||
if target is None:
|
||||
result.add(f"「报告撰写」的 metrics_from 指向 {src!r},但工作流里不存在这个节点",
|
||||
node_id=node.id, field="metrics_from")
|
||||
elif target.type != NodeType.METRICS:
|
||||
result.add(f"「报告撰写」的 metrics_from 指向「{target.title}」({src}),它不是「口径卡」"
|
||||
f"节点,而是「{type_label(target.type)}」:报告里的指标只能从口径卡来",
|
||||
node_id=node.id, field="metrics_from")
|
||||
elif src not in upstream:
|
||||
result.add(f"「报告撰写」的 metrics_from 指向的口径卡「{target.title}」不在它的上游:报告跑的"
|
||||
"时候那张卡还没算,目录里不会有它的指标。把口径卡连到报告前面",
|
||||
node_id=node.id, field="metrics_from")
|
||||
|
||||
|
||||
def _check_report_from(node: GraphNode, report_from: Any, spec: GraphSpec,
|
||||
result: ValidationResult) -> None:
|
||||
"""引用模式的契约:report_from 必须是出口上游的报告撰写节点。"""
|
||||
field = "contract.report_from"
|
||||
if not isinstance(report_from, str):
|
||||
result.add("出具契约的 report_from 要写「报告撰写」节点的 id", node_id=node.id, field=field)
|
||||
return
|
||||
target = spec.node_map().get(report_from)
|
||||
if target is None:
|
||||
result.add(f"出具契约的 report_from 指向 {report_from!r},但工作流里不存在这个节点",
|
||||
node_id=node.id, field=field)
|
||||
elif target.type != NodeType.REPORT:
|
||||
result.add(f"出具契约的 report_from 指向「{target.title}」({report_from}),它不是「报告撰写」"
|
||||
f"节点,而是「{type_label(target.type)}」:引用模式只核对报告撰写节点产出的文档",
|
||||
node_id=node.id, field=field)
|
||||
elif report_from not in _ancestors(spec, node.id):
|
||||
result.add(f"出具契约的 report_from 指向的「{target.title}」不在这个出口的上游:出口核对的时候"
|
||||
"那份报告还没写出来。把报告撰写节点连到出口前面",
|
||||
node_id=node.id, field=field)
|
||||
|
||||
|
||||
def validate_graph(spec: GraphSpec) -> ValidationResult:
|
||||
"""编译前的静态检查。错误会挡住运行,警告只在画布上提示。"""
|
||||
result = ValidationResult()
|
||||
@@ -427,11 +497,15 @@ def validate_graph(spec: GraphSpec) -> ValidationResult:
|
||||
if not d.get("id") or not d.get("expression"):
|
||||
result.add(f"指标定义缺 id 或 expression:{d.get('id') or '(空)'}",
|
||||
node_id=node.id, field=f"metrics[{i}]")
|
||||
elif node.type == NodeType.REPORT:
|
||||
_check_report_sources(node, spec, result)
|
||||
elif node.type == NodeType.OUTPUT:
|
||||
contract = cfg.get("contract")
|
||||
if contract and not contract.get("metrics_from"):
|
||||
result.add("出具契约缺 metrics_from(指标来自哪个「口径卡」节点)",
|
||||
node_id=node.id, field="contract.metrics_from")
|
||||
if isinstance(contract, dict) and contract.get("report_from") not in (None, ""):
|
||||
_check_report_from(node, contract["report_from"], spec, result)
|
||||
elif node.type == NodeType.LOOP:
|
||||
if not spec.outgoing(node.id):
|
||||
result.add("「循环」节点没有循环体", node_id=node.id)
|
||||
|
||||
@@ -32,6 +32,9 @@ class GraphState(TypedDict, total=False):
|
||||
- nodes:node_id -> 该节点的结构化输出,模板里用 {{ nodes.xxx.text }} 引用
|
||||
- vars:用户显式写入的变量池
|
||||
- output:output 节点收集的最终成果
|
||||
- evidence:证据台账。能被报告引用的工件(口径卡的指标集、查询快照……)按产生
|
||||
顺序记在这里,报告节点建目录时给它们统一编号。只追加不改写;旧 checkpoint 里
|
||||
没有这个通道,续跑时 LangGraph 按空列表起步
|
||||
"""
|
||||
|
||||
messages: Annotated[list[AnyMessage], add_messages]
|
||||
@@ -43,6 +46,7 @@ class GraphState(TypedDict, total=False):
|
||||
trail: Annotated[list[dict[str, Any]], operator.add]
|
||||
# 循环计数器:node_id -> 已迭代次数,防止无限循环
|
||||
loops: Annotated[dict[str, Any], merge_dict]
|
||||
evidence: Annotated[list[dict[str, Any]], operator.add]
|
||||
|
||||
|
||||
def template_context(state: GraphState) -> dict[str, Any]:
|
||||
|
||||
@@ -115,7 +115,7 @@ _EXPRESSION_FIELDS = ("expression", "condition", "skip_if")
|
||||
_BARE_REF_RE = re.compile(r"\b(?:vars|input|nodes)\.[A-Za-z_][\w.]*")
|
||||
|
||||
|
||||
def _iter_expressions(cfg: dict[str, Any]) -> list[tuple[str, str]]:
|
||||
def _iter_expressions(cfg: dict[str, Any], node_type: str = "") -> list[tuple[str, str]]:
|
||||
"""节点配置里那些按表达式求值的字段。"""
|
||||
out: list[tuple[str, str]] = []
|
||||
for key in _EXPRESSION_FIELDS:
|
||||
@@ -126,6 +126,13 @@ def _iter_expressions(cfg: dict[str, Any]) -> list[tuple[str, str]]:
|
||||
cond = (case or {}).get("condition")
|
||||
if isinstance(cond, str) and cond.strip():
|
||||
out.append((f"cases[{i}].condition", cond))
|
||||
# 口径卡的每个指标都是一条表达式。以前不扫,于是口径卡引用了谁在变量表里看不见,
|
||||
# 喂给它的 vars.kpi 还被报成「产出了但没有任何地方引用」
|
||||
if node_type == "metrics":
|
||||
for i, metric in enumerate(cfg.get("metrics") or []):
|
||||
expr = metric.get("expression") if isinstance(metric, dict) else None
|
||||
if isinstance(expr, str) and expr.strip():
|
||||
out.append((f"metrics[{i}].expression", expr))
|
||||
return out
|
||||
|
||||
|
||||
@@ -320,12 +327,14 @@ def analyze(spec: GraphSpec) -> VariableReport:
|
||||
# 只扫模板语法的话,模板⑦里 collect 那个
|
||||
# `(vars.collected or '') + str(vars.one)` 就一个引用都认不出来,
|
||||
# 于是 vars.one 被报成"产出了但没有任何地方引用"——而它明明在用。
|
||||
for field, expr_text in _iter_expressions(cfg):
|
||||
for field, expr_text in _iter_expressions(cfg, str(node.type)):
|
||||
for m in _BARE_REF_RE.finditer(expr_text):
|
||||
path, root = _root_of(m.group(0))
|
||||
if not path:
|
||||
continue
|
||||
target = index.get(path)
|
||||
# vars.kpi.gmv 是在用 vars.kpi:和模板引用一样退到能枚举的那一层
|
||||
target = index.get(path) or _resolve_fallback(
|
||||
path, index, input_is_closed=input_is_closed)
|
||||
if target is not None:
|
||||
target.refs.append(VarRef(
|
||||
node_id=node.id, node_label=label, field=field, expr=m.group(0),
|
||||
|
||||
Reference in New Issue
Block a user