mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-23 19:42:00 +00:00
可点击证据第二期:取数链路打通、问数据的答案逐段可点;发布前自动修复
一、可点击证据第二期
取数链路
- 智能体、工具节点、代码节点、知识检索取数时都记进证据台账;报告目录按台账编出 Q1… / K1…
- 报告可以引用快照里的一格([[v:Q1.r0.gmv]]),也可以由系统从快照生成整张表([[table:Q1 cols=… rows=0-4]]),
表里每一格都是可点的片段;取值一律以快照为准,取回快照时复验哈希
- 口径卡表达式新增 cell(x, row, column),lineage 精确到单元格
- 智能体开 cite_fields(配合 output_schema)后,循环结束做一次结构化抽取,每个字段标出取自哪次查询的哪一格,
再到快照里核对:一致记 verified;不一致以快照为准并告警;查不到的记为空值,永远不兜底成 0
- 代码节点新增 evidence_role(source / compute)和 code_sha;沙箱算出来的数不能被报告直接引用,要进口径卡
- 查询快照记下列类型,文本列按文本渲染(年份 "2026" 不再显示成「2,026」)
- 升级前发起的运行(停在审批上的)一律走旧逻辑:新的 task 只追加在循环之后,恢复时不会错号
证据接口与面板
- 片段链接上查询步骤:SQL、被引用的行加前后各 2 行、高亮到格;数据源可设 mask_columns 遮罩列,
遮罩在查询时记进快照,数据源事后改名或删除也照样遮罩(在有身份体系之前,遮罩只减少暴露,不是安全边界)
- 输入来源写明核对结果(与快照一致 / 模型报的值和快照不一致 / 没查到记为空);口径卡缺输入时也给出完整的链
- 受管出具要在契约里声明 cells 才能引用单元格;受管与否记在所钉版本上,改画布不再让受管版本的正式运行降级
- 口径卡可以用 caliber_from 钉住另一个已发布工作流里的口径卡,上游有新版本时按 upgrade_policy 处置,
和子工作流同一套规则;子工作流节点也补上了升版处置的配置项
Copilot、校验与报错
- 问数据的答案里有数字时,搭 input → 智能体 → 报告 → 出口,报告直接引用查过的单元格
- 写 SQL 前核对数据源的表结构,SQL 里出现表结构里没有的列会被打回
- 不再搭「智能体文字 → 转换节点解析 JSON」这种图;转换节点的 JSON 报错分清是上游模型写坏了、
模板里裸插了模型文字(给出 | json 的改法),还是模板本身写错了
- 工具节点遇到「查询失败」「SQL 被拒绝」判为失败;发起运行前检查绑定的工具是否存在,不存在时直接拒绝并给出入口
二、发布前自动修复
- 问题带上机器编号(code)和修复 id;新增只读接口 POST /api/workflows/{id}/publish-check 和 /autofix
- 修复分三类:答案唯一、不降低要求的一键修复;要人拿主意的给选项(不替人选);结构性问题交给 Copilot
- 一律先预览,不自动保存、不自动发布;删节点、删契约、放宽审批、关掉 strict、改级别等降低要求的改动一律拒绝,
Copilot 的方案也要过这一关;应用后重跑检查,错误必须变少且不能冒出新的
- 发布弹窗打开就先检查;问题面板新增「发布前检查」,平时就能看到、就地修掉
- 门禁修正:契约有 report_from 时不再要求 narrative(模板⑨可以发成受管);全图默认审批为「全部放行」时同样拦下
- 修掉画布保存会抹掉全图默认(defaults)的老问题:以前任何一次保存都会把它清空,审批 always 因此被悄悄放宽
验证(沙箱):tsc 干净,生产构建通过,pytest 2268 passed(两遍),check-all 17 项检查、3915 项全过
(新增 check-publish);关键行为做了变异验证、全部抓到。
This commit is contained in:
+200
-12
@@ -57,7 +57,12 @@ async def run_output(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
reports = _report_fields(result, mapping, state, ctx)
|
||||
contract = ctx.cfg("contract")
|
||||
if contract:
|
||||
result["_issuance"] = _apply_contract(contract, state, ctx, reports=reports)
|
||||
cells = True
|
||||
if isinstance(contract, dict) and contract.get("report_from") not in (None, ""):
|
||||
from app.engine.governance import cells_allowed, governed_formal
|
||||
|
||||
cells = cells_allowed(contract, governed=await governed_formal(ctx.run.run_id))
|
||||
result["_issuance"] = _apply_contract(contract, state, ctx, reports=reports, cells=cells)
|
||||
evidence = _evidence_of(reports, contract)
|
||||
if evidence:
|
||||
result["_evidence"] = evidence
|
||||
@@ -137,7 +142,7 @@ def _evidence_of(reports: list[dict[str, Any]], contract: Any) -> dict[str, Any]
|
||||
|
||||
def _apply_contract(
|
||||
contract: dict[str, Any], state: GraphState, ctx: NodeContext,
|
||||
*, reports: list[dict[str, Any]] | None = None,
|
||||
*, reports: list[dict[str, Any]] | None = None, cells: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
@@ -190,7 +195,7 @@ def _apply_contract(
|
||||
trace = None
|
||||
cited: dict[str, Any] = {}
|
||||
if citations:
|
||||
cited = _check_citations(str(report_from), contract, state, ctx, reports or [])
|
||||
cited = _check_citations(str(report_from), contract, state, ctx, reports or [], cells=cells)
|
||||
gaps.extend(cited["gaps"])
|
||||
unmatched = cited["unmatched"]
|
||||
else:
|
||||
@@ -284,13 +289,15 @@ _INTEGRITY = {"bad_schema", "segment_mismatch", "structural_text", "render_misma
|
||||
|
||||
def _check_citations(
|
||||
report_from: str, contract: dict[str, Any], state: GraphState, ctx: NodeContext,
|
||||
reports: list[dict[str, Any]],
|
||||
reports: list[dict[str, Any]], *, cells: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""独立复核报告文档:{matched, unmatched, unresolved, gaps, doc_artifact, stats}。
|
||||
|
||||
不信报告节点自己的统计:文档按 id 从工件库取回(取回时复验哈希),目录按报告节点
|
||||
同一套参数从状态里重建(不用文档里存的那份),每个带引用的片段重新解析、重新渲染、
|
||||
逐字比对。一个配错的报告节点绕不过这里。
|
||||
|
||||
cells:受管级别的正式运行、契约没声明 cells 时为 False,单元格引用一律判解析不了。
|
||||
"""
|
||||
from app.core.artifact_store import load
|
||||
from app.engine.evidence import iter_units, resolve_ref, verify_doc
|
||||
@@ -325,7 +332,7 @@ def _check_citations(
|
||||
return out
|
||||
|
||||
catalog = report_catalog(state, spec, node)
|
||||
checked = verify_doc(doc, catalog, allow_numbers=contract.get("allow_numbers"))
|
||||
checked = verify_doc(doc, catalog, allow_numbers=contract.get("allow_numbers"), cells_allowed=cells)
|
||||
out["stats"] = checked["stats"]
|
||||
broken: list[str] = []
|
||||
flagged: set[str] = set()
|
||||
@@ -350,7 +357,7 @@ def _check_citations(
|
||||
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)
|
||||
cite = resolve_ref(str(seg["ref"]), catalog, cells_allowed=cells)
|
||||
if cite["status"] != "resolved" or cite["rendered"] != seg.get("text"):
|
||||
continue
|
||||
entry = catalog.get(cite["alias"]) or {}
|
||||
@@ -360,6 +367,9 @@ def _check_citations(
|
||||
label = " @ ".join(str(v) for v in (entry.get("caliber"), entry.get("version")) if v)
|
||||
if label:
|
||||
hit["caliber"] = label
|
||||
elif cite["kind"] == "cell":
|
||||
# 查询单元格:Q1.r0.gmv(全局编号,和 doc.catalog 一致)
|
||||
hit["cell"] = f"{cite['alias']}.r{cite['locator']['row']}.{cite['locator']['column']}"
|
||||
else:
|
||||
hit["input"] = cite["locator"].get("field")
|
||||
out["matched"].append({**hit, "segment": seg["id"], "unit": unit["id"], "start": start, "end": end,
|
||||
@@ -437,15 +447,12 @@ async def run_transform(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
elif mode == "template":
|
||||
output = ctx.render_str(ctx.cfg("template", ""), state)
|
||||
elif mode == "json":
|
||||
rendered = ctx.render_str(ctx.cfg("template", "{}"), state)
|
||||
template = ctx.cfg("template", "{}")
|
||||
rendered = ctx.render_str(template, state)
|
||||
try:
|
||||
output = json.loads(rendered)
|
||||
except json.JSONDecodeError as e:
|
||||
raise NodeError(
|
||||
ctx.node.id,
|
||||
f"模板渲染出来的不是合法 JSON(第 {e.lineno} 行第 {e.colno} 列附近)。"
|
||||
"检查模板里的引号、逗号,字符串值要用 | json 过滤器输出",
|
||||
) from e
|
||||
raise _json_error(e, str(template or ""), tctx, ctx) from e
|
||||
else:
|
||||
raise NodeError(ctx.node.id, f"未知的整形模式:{mode}")
|
||||
|
||||
@@ -454,3 +461,184 @@ async def run_transform(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: output}
|
||||
return updates
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 按 JSON 解析失败:错在模板,还是错在上游模型写的文字
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
#: 产出是模型写的文字的节点(llm 配了 output_schema 时 text 是系统序列化的,但那样也解析得了)
|
||||
_MODEL_TEXT = (NodeType.AGENT, NodeType.LLM, NodeType.SUPERVISOR)
|
||||
#: 技术细节里给出出错位置前后各多少个字
|
||||
_NEAR = 30
|
||||
_NODE_HEAD = re.compile(r"^nodes\s*(?:\.\s*([\w-]+)|\[\s*['\"]([^'\"]+)['\"]\s*\])")
|
||||
_VAR_HEAD = re.compile(r"^vars\s*(?:\.\s*([\w-]+)|\[\s*['\"]([^'\"]+)['\"]\s*\])")
|
||||
|
||||
|
||||
TEMPLATE_HINT = "检查模板里的引号、逗号,字符串值要用 | json 过滤器输出"
|
||||
#: 解析器在这一段的头一个字上要的是这些:前一个值在模板里已经写完了,缺的是模板里的标点
|
||||
_DELIMITED = ("Expecting ',' delimiter", "Expecting ':' delimiter", "Extra data")
|
||||
|
||||
|
||||
def _json_error(e: json.JSONDecodeError, template: str, tctx: dict[str, Any], ctx: NodeContext) -> NodeError:
|
||||
"""整形节点按 JSON 解析失败时的报错。
|
||||
|
||||
真实踩过:整个模板就是 {{ nodes.X.text }},agent 在 JSON 字符串里夹了没转义的英文双引号,
|
||||
报错却让人去检查模板、加 | json,把人引到了错的方向。反过来也不行:出错的位置落在模型
|
||||
写的那一段里,不等于错在模型——模板把一句话原样放进值的位置、放进引号里,或者紧挨着它
|
||||
漏了逗号,都是模板的错,而且改法就是那句老提示。所以分三种说(见 _diagnose):
|
||||
|
||||
- 上游确实在写 JSON 而没写对:点名上游、按实情说原因、指向结构化输出;
|
||||
- 模板少了 | json:点名是模板里哪一段,给出改好的写法;
|
||||
- 其余:原来那句提示。
|
||||
|
||||
出错位置前后的原文只进技术细节(包在原异常里):首行是给人看的一句话,不贴模型的原文。
|
||||
"""
|
||||
doc, pos = e.doc, e.pos
|
||||
near = (doc[max(0, pos - _NEAR):pos] + "⟨此处⟩" + doc[pos:pos + _NEAR]).replace("\n", "\\n")
|
||||
e.args = (f"{e.args[0]}\n出错位置前后的原文:{near}",)
|
||||
verdict = _diagnose(template, tctx, ctx, e)
|
||||
if verdict is None or isinstance(verdict, str):
|
||||
return NodeError(ctx.node.id, f"模板渲染出来的不是合法 JSON(第 {e.lineno} 行第 {e.colno} 列附近)。"
|
||||
f"{verdict or TEMPLATE_HINT}")
|
||||
node, text, offset, reason = verdict
|
||||
line = text.count("\n", 0, offset) + 1
|
||||
column = offset - (text.rfind("\n", 0, offset) + 1) + 1
|
||||
where = f"第 {line} 行第 {column} 列" if line > 1 else f"第 {column} 列"
|
||||
fix = ("让模型交结构化数据请给它配 output_schema;数要进口径卡的,改用 agent 的 output_schema + cite_fields"
|
||||
if node.type == NodeType.LLM else
|
||||
"让模型交结构化数据请用 output_schema + cite_fields,别用整形节点解析它写的文字")
|
||||
return NodeError(ctx.node.id, f"上游「{node.title}」输出的不是合法 JSON({where}附近),{reason};{fix}")
|
||||
|
||||
|
||||
def _diagnose(template: str, tctx: dict[str, Any], ctx: NodeContext,
|
||||
e: json.JSONDecodeError) -> tuple[GraphNode, str, int, str] | str | None:
|
||||
"""按 JSON 解析失败,错在谁。
|
||||
|
||||
返回 (上游节点, 它写的那段文字, 出错位置在文字里的偏移, 原因) 表示错在上游;返回一句话
|
||||
表示错在模板、而且说得出是哪一段;返回 None 表示照原来那句提示。
|
||||
|
||||
只有上游确实在写 JSON(去掉开头空白后以 { 或 [ 开头,或者包在 ``` 代码块里)、而且这一段
|
||||
不在模板的引号里,才算上游的错;整个模板就是这一段时,模板不可能写错,也算上游的。
|
||||
解析器停在这一段末尾时(紧跟着的逗号漏了),只有它自己开了括号、引号没收尾才怪它。
|
||||
|
||||
每个 {{ }} 单独渲染一次再拼起来,和 render_template 的整段替换结果逐字相同。
|
||||
"""
|
||||
from app.engine.expressions import _TEMPLATE_RE, render_template, resolve_path
|
||||
|
||||
doc, pos = e.doc, e.pos
|
||||
at, last = 0, 0
|
||||
for m in _TEMPLATE_RE.finditer(template):
|
||||
at += m.start() - last
|
||||
piece = render_template(m.group(0), tctx)
|
||||
start, end = at, at + len(piece)
|
||||
at, last = end, m.end()
|
||||
expr = m.group(1).strip()
|
||||
head, *filters = [p.strip() for p in expr.split("|")]
|
||||
if not head or pos < start:
|
||||
continue
|
||||
# 解析器越过空白才报错:停在这一段后面、中间只隔着空白的,也是停在它末尾
|
||||
at_end = pos >= end and not doc[end:pos].strip()
|
||||
if not piece.strip():
|
||||
# 取出来是空的,解析器正好在这里要一个值
|
||||
if e.msg == "Expecting value" and not doc[start:pos].strip() and not _in_json_string(doc, start):
|
||||
return f"模板里 {{{{ {expr} }}}} 取出来是空的,这里缺一个值:检查路径写对没有、前面的节点有没有产出"
|
||||
continue
|
||||
if pos > end and not at_end:
|
||||
continue
|
||||
quoted = _in_json_string(doc, start)
|
||||
if "json" in filters:
|
||||
# 过了 | json 就是一个合法的 JSON 值:错不在它的内容里,除非外面又套了一层引号
|
||||
return (f"模板里 {{{{ {expr} }}}} 出来的已经是合法的 JSON(文字自带引号),外面不要再加引号"
|
||||
if quoted and not at_end else None)
|
||||
value = resolve_path(tctx, head)
|
||||
if not isinstance(value, str) or value != piece:
|
||||
return None
|
||||
node = _producer(head, ctx)
|
||||
model = node is not None and node.type in _MODEL_TEXT
|
||||
lead = start + len(piece) - len(piece.lstrip())
|
||||
if pos == lead and e.msg.startswith(_DELIMITED):
|
||||
return None # 前一个值在模板里就写完了,缺的是它前面的标点
|
||||
if template.strip() == m.group(0):
|
||||
return (node, piece, pos - start, _why(piece, at_end)) if model else None
|
||||
if at_end and not _unclosed(piece):
|
||||
return None # 这一段本身完整,缺的是它后面的标点
|
||||
if quoted:
|
||||
return _needs_json(expr, model)
|
||||
if _writes_json(piece):
|
||||
return (node, piece, pos - start, _why(piece, at_end)) if model else None
|
||||
return _needs_json(expr, model)
|
||||
return None
|
||||
|
||||
|
||||
def _needs_json(expr: str, model: bool) -> str:
|
||||
what = "模型写的文字" if model else "一段文字"
|
||||
return f"模板里 {{{{ {expr} }}}} 是{what},放进 JSON 要写成 {{{{ {expr} | json }}}}(外面不要再加引号)"
|
||||
|
||||
|
||||
def _why(text: str, at_end: bool) -> str:
|
||||
"""上游写的 JSON 为什么解析不了,按看得出来的实情说。"""
|
||||
body = text.lstrip()
|
||||
if body.startswith("```"):
|
||||
return "它把 JSON 包在了 ``` 代码块里"
|
||||
if at_end and _unclosed(text):
|
||||
return "它写的 JSON 没有收尾,可能写到一半被截断了"
|
||||
if not body.startswith(("{", "[")):
|
||||
return "它写的是一段文字,不是 JSON"
|
||||
return "常见原因是字符串里有没转义的英文引号"
|
||||
|
||||
|
||||
def _writes_json(text: str) -> bool:
|
||||
"""这段文字看得出是想写 JSON:以 { 或 [ 开头,或者是包在 ``` 代码块里的 JSON。"""
|
||||
body = text.lstrip()
|
||||
if body.startswith("```"):
|
||||
body = body.split("\n", 1)[1].lstrip() if "\n" in body else ""
|
||||
return body.startswith(("{", "["))
|
||||
|
||||
|
||||
def _in_json_string(doc: str, index: int) -> bool:
|
||||
"""doc[:index] 结束时是不是在一个 JSON 字符串里。解析器已经越过了这里,这一段前缀是
|
||||
合法的 JSON 开头,数引号(跳过转义)就数得准。"""
|
||||
inside, i = False, 0
|
||||
while i < index:
|
||||
ch = doc[i]
|
||||
if inside and ch == "\\":
|
||||
i += 2
|
||||
continue
|
||||
if ch == '"':
|
||||
inside = not inside
|
||||
i += 1
|
||||
return inside
|
||||
|
||||
|
||||
def _unclosed(text: str) -> bool:
|
||||
"""这段文字自己开了引号、括号却没收尾(单独看它,从字符串外面数起)。"""
|
||||
depth, inside, i = 0, False, 0
|
||||
while i < len(text):
|
||||
ch = text[i]
|
||||
if inside:
|
||||
if ch == "\\":
|
||||
i += 1
|
||||
elif ch == '"':
|
||||
inside = False
|
||||
elif ch == '"':
|
||||
inside = True
|
||||
elif ch in "{[":
|
||||
depth += 1
|
||||
elif ch in "}]":
|
||||
depth -= 1
|
||||
i += 1
|
||||
return inside or depth > 0
|
||||
|
||||
|
||||
def _producer(path: str, ctx: NodeContext) -> GraphNode | None:
|
||||
"""模板路径取的是哪个节点的产出:nodes.X 就是 X;vars.Y 是 assign_to 为 Y 的节点。"""
|
||||
nodes = ctx.run.spec.node_map()
|
||||
if m := _NODE_HEAD.match(path):
|
||||
return nodes.get(m.group(1) or m.group(2))
|
||||
if m := _VAR_HEAD.match(path):
|
||||
var = m.group(1) or m.group(2)
|
||||
writers = [n for n in ctx.run.spec.nodes if str(n.config.get("assign_to") or "").strip() == var]
|
||||
# 好几个节点写同一个变量时说不准是谁,宁可给原来的提示也不点错名
|
||||
return writers[0] if len(writers) == 1 else None
|
||||
return None
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Any
|
||||
from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.evidence import ledger_enabled, next_exec
|
||||
from app.engine.state import GraphState, template_context
|
||||
from app.memory import kb, store
|
||||
|
||||
@@ -175,6 +176,10 @@ async def run_retrieve(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
|
||||
if snapshot and ledger_enabled(ctx.run):
|
||||
# 证据台账:报告目录按它编 K1…,[[see:K1]] 点开追得到这次检索命中了哪几段
|
||||
updates["evidence"] = [{"kind": "retrieval", "node_id": ctx.node.id, "exec": next_exec(state, ctx.node.id),
|
||||
"artifact": snapshot, "source": collection, "rows": len(hits)}]
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: context_text}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
@@ -9,6 +10,7 @@ from langchain_core.tools import BaseTool
|
||||
from langgraph.func import task
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core import artifact_store
|
||||
from app.core.config import settings
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType
|
||||
@@ -16,6 +18,8 @@ from app.db.base import SessionLocal
|
||||
from app.db.models import Skill
|
||||
from app.engine.approval import read_decision
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.evidence import cell_eid, ledger_enabled, make_eid, next_exec, query_entry_fields
|
||||
from app.engine.expressions import CellError, cell_value, column_kind, locate_cell, numeric_text, same_value
|
||||
from app.engine.guards import FALLBACK_CONTEXT, Guard, legacy_hint, node_limits
|
||||
from app.engine.replay import ask, once
|
||||
from app.engine.state import GraphState, message_text, template_context, thinking_text
|
||||
@@ -36,6 +40,7 @@ from app.providers.factory import (
|
||||
bind_tools_safely,
|
||||
get_chat_model,
|
||||
)
|
||||
from app.tools.datasource import QUERY_PREFIX
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
ToolBuildError,
|
||||
@@ -407,6 +412,13 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
messages = await _build_messages(state, ctx)
|
||||
# 护栏(engine/guards.py)。None 是升级前发起的运行:默认 12 步、没有别的护栏,和以前一样
|
||||
guard = _guard(ctx, model_id)
|
||||
# 证据台账、工具结果前的编号、cite_fields:升级前发起的运行一样都不加(见 evidence.ledger_enabled)
|
||||
evidence_on = ledger_enabled(ctx.run)
|
||||
exec_no = next_exec(state, ctx.node.id)
|
||||
#: 本节点查成功的库:编号 Q1… 只在本节点内有效,cite_fields 抽取靠它找快照
|
||||
queries: list[dict[str, Any]] = []
|
||||
#: 要记进证据台账的条目,按调用顺序
|
||||
entries: list[dict[str, Any]] = []
|
||||
max_steps = (guard.limits.max_steps if guard
|
||||
else min(int(ctx.cfg("max_steps", 12) or 12), settings.max_agent_steps))
|
||||
total_usage: dict[str, Any] = {"input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0, "calls": 0}
|
||||
@@ -479,6 +491,10 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
snapshot_id = None
|
||||
# 查库成功时工具交回的 JSON 里带着查询快照的工件 id:记进返回值(进 checkpoint,重放拿到的
|
||||
# 是同一份)和 tool.end(在封存范围内,证据接口从这里出发找快照)。只认数据源工具:那个 id 是
|
||||
# 我们自己落的;MCP、自定义工具的文字来自外面,拼一个同样形状的 JSON 就能把任意快照塞进封存范围
|
||||
query = query_entry_fields(content) if evidence_on and ok and name.startswith(QUERY_PREFIX) else None
|
||||
ctx.emit(
|
||||
EventType.TOOL_END if ok else EventType.TOOL_ERROR,
|
||||
tool=name,
|
||||
@@ -486,9 +502,13 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
duration_ms=elapsed,
|
||||
preview=content[:2000],
|
||||
artifact=snapshot_id,
|
||||
**({"query_artifact": query["artifact"]} if query else {}),
|
||||
**extra,
|
||||
)
|
||||
return {"content": content, "ok": ok, "duration_ms": elapsed}
|
||||
outcome: dict[str, Any] = {"content": content, "ok": ok, "duration_ms": elapsed}
|
||||
if evidence_on:
|
||||
outcome.update(snapshot=snapshot_id, query_artifact=query["artifact"] if query else None)
|
||||
return outcome
|
||||
|
||||
@task
|
||||
async def gate_step(name: str, args: dict[str, Any], call_id: str) -> dict[str, Any]:
|
||||
@@ -499,6 +519,30 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
ctx.emit(EventType.TOOL_GATED, tool=name, call_id=call_id, **gate.event())
|
||||
return {"allowed": gate.allowed, **gate.usage}
|
||||
|
||||
@task
|
||||
async def extract_step(payload: list[BaseMessage], schema: dict[str, Any]) -> dict[str, Any]:
|
||||
# cite_fields 的结构化抽取:进 checkpoint,节点重放时不再调用、不再计费。失败也在这里收住、
|
||||
# 作为结果返回——agent 的结论还在,字段记空值、发警告,而不是把整个节点赔进去。
|
||||
# thinking 关掉:结构化输出靠强制工具调用,和思考模式不兼容,抽取也用不着思考
|
||||
spec = model_spec.model_copy(update={
|
||||
"thinking": "off", "max_tokens": max(int(ctx.cfg("max_tokens") or 0), 4096)})
|
||||
started = time.perf_counter()
|
||||
ctx.emit(EventType.LLM_START, model=model_id, structured=True, purpose="cite_fields",
|
||||
message_count=len(payload))
|
||||
try:
|
||||
async with SessionLocal() as session:
|
||||
extractor, _ = await get_chat_model(session, spec)
|
||||
got = await extractor.with_structured_output(schema, include_raw=True).ainvoke(payload)
|
||||
except Exception as e: # noqa: BLE001
|
||||
ctx.emit(EventType.LLM_END, agent=ctx.node.title, model=model_id, purpose="cite_fields",
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), error=describe_exception(e))
|
||||
return {"error": f"结构化抽取没跑成:{explain_model_error(e, model_id)}"}
|
||||
raw, parsed = _split_structured(got)
|
||||
usage = _usage_of(raw if raw is not None else AIMessage(content=""), model_id)
|
||||
ctx.emit(EventType.LLM_END, agent=ctx.node.title, model=model_id, purpose="cite_fields",
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), **usage)
|
||||
return {"parsed": parsed, **usage}
|
||||
|
||||
final_text = ""
|
||||
#: 模型把工具调用写成了文字:纠正过一次了没有
|
||||
nudged = False
|
||||
@@ -610,8 +654,13 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
|
||||
outcome = await tool_step(step, name, args, call_id)
|
||||
content = outcome["content"]
|
||||
transcript.append({"tool": name, "args": args, "ok": outcome["ok"],
|
||||
"duration_ms": outcome["duration_ms"], "result": content[:4000]})
|
||||
record = {"tool": name, "args": args, "ok": outcome["ok"],
|
||||
"duration_ms": outcome["duration_ms"], "result": content[:4000]}
|
||||
if evidence_on:
|
||||
# 编号只取决于 tool_step 的返回值(重放时取自 checkpoint),重放出来的还是这一套
|
||||
content = _record_call(ctx.node.id, exec_no, call_id, name, args, outcome, record,
|
||||
queries, entries)
|
||||
transcript.append(record)
|
||||
messages.append(ToolMessage(content=content, tool_call_id=call_id))
|
||||
if guard:
|
||||
guard.record(step, name, args, outcome["ok"], content)
|
||||
@@ -699,6 +748,21 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
final_text = f"{final_text}\n\n({hint})".strip() if final_text else f"({hint})"
|
||||
ctx.emit(EventType.LOG, level="warn", message=hint, code="step_limit", **limited)
|
||||
|
||||
cited: tuple[dict[str, Any], dict[str, Any]] | None = None
|
||||
schema = _output_schema(ctx) if evidence_on and ctx.cfg("cite_fields") is True else None
|
||||
if schema is not None and (fields := cited_fields(schema)):
|
||||
# 结构化抽取只能追加在循环之后:循环里的 task 按调用位置从 checkpoint 取回,插一个进去,
|
||||
# 停在审批上的运行恢复时位置就错开了
|
||||
extracted: dict[str, Any] = {"error": "这个节点没有查成功的库,没有可以核对出处的数据"}
|
||||
if queries:
|
||||
extracted = await extract_step(_extract_messages(final_text, queries, fields), cited_schema(schema))
|
||||
for key in ("input_tokens", "output_tokens", "calls"):
|
||||
total_usage[key] += int(extracted.get(key) or 0)
|
||||
total_usage["cost_usd"] = round(total_usage["cost_usd"] + float(extracted.get("cost_usd") or 0), 6)
|
||||
cited = verify_cited_fields(extracted, fields, queries)
|
||||
for code, message, names in _field_warnings(*cited, extracted.get("error")):
|
||||
await once(ctx, EventType.LOG, level="warn", code=code, message=message, fields=names)
|
||||
|
||||
total_usage["total_tokens"] = total_usage["input_tokens"] + total_usage["output_tokens"]
|
||||
result = {
|
||||
"text": final_text,
|
||||
@@ -708,13 +772,405 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 没等到模型自己给结论就收了尾:下游校验失败时拿它说明根源(human.py)
|
||||
**({"limited": settle_reason} if settle_reason else {}),
|
||||
}
|
||||
if cited is not None:
|
||||
result["data"], result["data_evidence"] = cited
|
||||
updates: dict[str, Any] = {
|
||||
"nodes": {ctx.node.id: result},
|
||||
"usage": total_usage,
|
||||
}
|
||||
if entries:
|
||||
updates["evidence"] = entries
|
||||
if ctx.cfg("emit_message", True):
|
||||
updates["messages"] = [AIMessage(content=final_text or "(空)")]
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: final_text}
|
||||
# 开了 cite_fields 的,变量里是核对过的 data(值以快照为准),下游口径卡按字段取
|
||||
updates["vars"] = {var_name: cited[0] if cited is not None else final_text}
|
||||
return updates
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 证据台账与 cite_fields:agent 查到的数怎么变成能核对的证据
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _record_call(node_id: str, exec_no: int, call_id: str, name: str, args: dict[str, Any],
|
||||
outcome: dict[str, Any], record: dict[str, Any], queries: list[dict[str, Any]],
|
||||
entries: list[dict[str, Any]]) -> str:
|
||||
"""把一次执行过的工具调用记进台账、调用记录和本节点的查询清单,返回给模型看的内容。
|
||||
|
||||
查库成功的结果前面加一行「【证据 Q1】」:模型在循环里就知道每次查询的编号,cite_fields
|
||||
抽取时照这个编号写出处。编号只在本节点内有效;报告目录里的 Q1… 按全局台账另编,两边
|
||||
靠工件 id 对应,不靠编号。
|
||||
"""
|
||||
content = outcome["content"]
|
||||
record["call_id"] = call_id
|
||||
snapshot, artifact = outcome.get("snapshot"), outcome.get("query_artifact")
|
||||
if snapshot:
|
||||
record["via"] = snapshot
|
||||
entries.append({"kind": "tool", "node_id": node_id, "exec": exec_no, "artifact": snapshot,
|
||||
"call_id": call_id, "tool": name})
|
||||
if not artifact or not name.startswith(QUERY_PREFIX):
|
||||
return content
|
||||
try:
|
||||
data = json.loads(content)
|
||||
except ValueError:
|
||||
data = None
|
||||
fields = query_entry_fields(data)
|
||||
if fields is None:
|
||||
return content
|
||||
alias = f"Q{len(queries) + 1}"
|
||||
record.update(alias=alias, artifact=artifact)
|
||||
entries.append({"kind": "query", "node_id": node_id, "exec": exec_no, "artifact": artifact,
|
||||
**({"via": snapshot} if snapshot else {}), "call_id": call_id, "tool": name,
|
||||
"source": fields["source"], "columns": fields["columns"], "rows": fields["rows"],
|
||||
"truncated": fields["truncated"]})
|
||||
queries.append({"alias": alias, "call_id": call_id, "tool": name, "sql": str(args.get("sql") or ""),
|
||||
"artifact": artifact, "via": snapshot, "columns": fields["columns"],
|
||||
"rows": data.get("rows") or [], "truncated": fields["truncated"]})
|
||||
return f"【证据 {alias}】\n{content}"
|
||||
|
||||
|
||||
def _output_schema(ctx: NodeContext) -> dict[str, Any] | None:
|
||||
"""节点的 output_schema(对象形状)。画布里存成 JSON 文本的也认。"""
|
||||
schema = ctx.cfg("output_schema")
|
||||
if isinstance(schema, str) and schema.strip():
|
||||
try:
|
||||
schema = json.loads(schema)
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(schema, dict) and (schema.get("type") == "object" or "properties" in schema):
|
||||
return schema
|
||||
return None
|
||||
|
||||
|
||||
def _is_object(schema: Any) -> bool:
|
||||
return isinstance(schema, dict) and (schema.get("type") == "object" or "properties" in schema)
|
||||
|
||||
|
||||
def cited_fields(schema: dict[str, Any], prefix: str = "") -> list[tuple[str, dict[str, Any]]]:
|
||||
"""output_schema 里要标出处的字段:(点号路径, 字段的 schema),按声明顺序,嵌套对象展开。"""
|
||||
out: list[tuple[str, dict[str, Any]]] = []
|
||||
for key, sub in (schema.get("properties") or {}).items():
|
||||
path = f"{prefix}{key}"
|
||||
if _is_object(sub):
|
||||
out.extend(cited_fields(sub, f"{path}."))
|
||||
else:
|
||||
out.append((path, sub if isinstance(sub, dict) else {}))
|
||||
return out
|
||||
|
||||
|
||||
#: 一个值在哪次查询的哪一格
|
||||
_FROM_CELL: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"description": "这个值在哪次查询的哪一格:call 是【证据 Qn】里的编号,row 是行号(从 0 数),column 是列名",
|
||||
"properties": {"call": {"type": "string"}, "row": {"type": "integer"}, "column": {"type": "string"}},
|
||||
"required": ["call", "row", "column"],
|
||||
}
|
||||
|
||||
|
||||
def _is_array(schema: Any) -> bool:
|
||||
return isinstance(schema, dict) and schema.get("type") == "array"
|
||||
|
||||
|
||||
def _row_columns(schema: dict[str, Any]) -> list[str] | None:
|
||||
"""数组里是对象时,对象的字段(都得是标量);不是对象返回 None。"""
|
||||
items = schema.get("items")
|
||||
if not _is_object(items):
|
||||
return None
|
||||
return list((items.get("properties") or {}).keys())
|
||||
|
||||
|
||||
def _from_rows(schema: dict[str, Any]) -> dict[str, Any]:
|
||||
"""数组字段按行映射:一段连续的行,标量数组对应一列,对象数组的每个字段各对应一列。"""
|
||||
fields = _row_columns(schema)
|
||||
where = ({"columns": {"type": "object", "description": "对象的每个字段取自哪一列:{字段: 列名}",
|
||||
"properties": {f: {"type": "string"} for f in fields}, "required": fields}}
|
||||
if fields is not None else {"column": {"type": "string"}})
|
||||
return {"type": "object",
|
||||
"description": "这组值在哪次查询的哪几行:call 是【证据 Qn】里的编号,rows 写行号范围(从 0 数,"
|
||||
"如 0-4,数组第 k 个元素就是第 起始+k 行)",
|
||||
"properties": {"call": {"type": "string"}, "rows": {"type": "string"}, **where},
|
||||
"required": ["call", "rows", *where]}
|
||||
|
||||
|
||||
def cited_schema(schema: dict[str, Any]) -> dict[str, Any]:
|
||||
"""抽取用的 schema:每个标量字段改写成 {value, from},查不到时两个都是 null。
|
||||
|
||||
数组字段整个是一个 {value, from}:from 写一段连续的行(rows: "0-4")和对应的列。
|
||||
"""
|
||||
|
||||
def rewrite(node: dict[str, Any]) -> dict[str, Any]:
|
||||
if _is_object(node):
|
||||
props = node.get("properties") or {}
|
||||
return {"type": "object", **({"description": node["description"]} if node.get("description") else {}),
|
||||
"properties": {k: rewrite(v if isinstance(v, dict) else {}) for k, v in props.items()},
|
||||
"required": list(props)}
|
||||
source = _from_rows(node) if _is_array(node) else _FROM_CELL
|
||||
return {"type": "object",
|
||||
"properties": {"value": {"anyOf": [node, {"type": "null"}]},
|
||||
"from": {"anyOf": [source, {"type": "null"}]}},
|
||||
"required": ["value", "from"]}
|
||||
|
||||
# 走工具调用的结构化输出要求函数名只含字母、数字、下划线
|
||||
return {"title": "cited_fields", **rewrite(schema)}
|
||||
|
||||
|
||||
EXTRACT_SYSTEM = (
|
||||
"你是数据抽取员:把智能体查到的数据按给定结构填好,每个字段都写出处。\n"
|
||||
"- value 是字段的值;from 写它在哪次查询的哪一格:call 是【证据 Qn】里的编号,row 是行号(从 0 数),"
|
||||
"column 是列名。\n"
|
||||
"- 只能用下面查询结果里真实出现的值。查不到就把 value 和 from 都填 null,禁止估算,"
|
||||
"禁止用 0 或空字符串代替没查到的值。\n"
|
||||
"- 不要做计算:比率、增幅、合计这类要算出来的量填 null,交给口径卡去算。"
|
||||
)
|
||||
#: 抽取提示里每次查询最多列出几行、整段最多多少字
|
||||
_DIGEST_ROWS, _DIGEST_BUDGET = 50, 16000
|
||||
|
||||
|
||||
def _digest(queries: list[dict[str, Any]]) -> str:
|
||||
parts: list[str] = []
|
||||
for q in queries:
|
||||
lines = [f"【证据 {q['alias']}】{q['tool']}"]
|
||||
if q["sql"]:
|
||||
lines.append(f"SQL:{q['sql'][:300]}")
|
||||
columns = q["columns"]
|
||||
lines.append(f"列:{', '.join(columns)}")
|
||||
for r, record in enumerate(q["rows"][:_DIGEST_ROWS]):
|
||||
values = record if isinstance(record, list) else [record.get(c) for c in columns] \
|
||||
if isinstance(record, dict) else [record]
|
||||
lines.append(f"r{r}:" + ",".join(f"{c}={json.dumps(v, ensure_ascii=False, default=str)}"
|
||||
for c, v in zip(columns, values)))
|
||||
if len(q["rows"]) > _DIGEST_ROWS:
|
||||
lines.append(f"…共 {len(q['rows'])} 行,只列出前 {_DIGEST_ROWS} 行")
|
||||
elif not q["rows"]:
|
||||
lines.append("(0 行)")
|
||||
parts.append("\n".join(lines))
|
||||
text = "\n\n".join(parts)
|
||||
return text if len(text) <= _DIGEST_BUDGET else text[:_DIGEST_BUDGET] + "\n…(查询结果太长,后面的省略了)"
|
||||
|
||||
|
||||
def _extract_messages(final_text: str, queries: list[dict[str, Any]],
|
||||
fields: list[tuple[str, dict[str, Any]]]) -> list[BaseMessage]:
|
||||
wanted = "\n".join(
|
||||
f"- {path}({sub.get('type') or '任意'})" + (f":{sub['description']}" if sub.get("description") else "")
|
||||
for path, sub in fields)
|
||||
return [
|
||||
SystemMessage(content=EXTRACT_SYSTEM),
|
||||
HumanMessage(content=(
|
||||
f"智能体的结论(只作参考,数以查询结果为准):\n{final_text or '(没有结论)'}\n\n"
|
||||
f"查询结果:\n{_digest(queries)}\n\n要填的字段:\n{wanted}"
|
||||
)),
|
||||
]
|
||||
|
||||
|
||||
def _split_structured(got: Any) -> tuple[BaseMessage | None, Any]:
|
||||
"""with_structured_output(include_raw=True) 的结果拆成 (原始回复, 解析结果)。
|
||||
|
||||
不认 include_raw 的模型(比如 mock)直接给解析结果。
|
||||
"""
|
||||
if isinstance(got, dict) and isinstance(got.get("raw"), BaseMessage) and "parsed" in got:
|
||||
raw, parsed = got["raw"], got["parsed"]
|
||||
else:
|
||||
raw, parsed = None, got
|
||||
if parsed is not None and not isinstance(parsed, (dict, list)) and hasattr(parsed, "model_dump"):
|
||||
parsed = parsed.model_dump()
|
||||
return raw, parsed
|
||||
|
||||
|
||||
def _typed(raw: Any, schema: Any, kind: str | None = None) -> Any:
|
||||
"""快照里的一格 → 按字段声明的类型给出的值(data 里放的就是它)。
|
||||
|
||||
数据源把 DECIMAL 落成文本,小数位为 0 的是 "45678":声明成 number / integer 的换成数,下游口径卡
|
||||
才能拿它做除法;声明成 string 的原样是文本,"2026" 不会变成 2026。没声明类型的按 cell_value,
|
||||
kind(查询时记下的列类型)是 text 的原样是文本;老快照没记类型就按值猜。
|
||||
声明成 integer 而快照里是 3.0 这样的整值,给 3;是 45678.5 就照实给 45678.5,不替它取整。
|
||||
"""
|
||||
declared = schema.get("type") if isinstance(schema, dict) else None
|
||||
types = {declared} if isinstance(declared, str) else set(declared) if isinstance(declared, list) else set()
|
||||
value = cell_value(raw, kind)
|
||||
if types & {"number", "integer"}:
|
||||
loose = numeric_text(raw, loose=True)
|
||||
value = value if loose is None else loose
|
||||
if "integer" in types and isinstance(value, float) and value.is_integer():
|
||||
value = int(value)
|
||||
elif "string" in types and isinstance(raw, str):
|
||||
value = raw
|
||||
return value
|
||||
|
||||
|
||||
def _dig(data: Any, path: str) -> Any:
|
||||
for key in path.split("."):
|
||||
data = data.get(key) if isinstance(data, dict) else None
|
||||
return data
|
||||
|
||||
|
||||
def _plant(data: dict[str, Any], path: str, value: Any) -> None:
|
||||
*heads, last = path.split(".")
|
||||
for key in heads:
|
||||
data = data.setdefault(key, {})
|
||||
data[last] = value
|
||||
|
||||
|
||||
def verify_cited_fields(extracted: dict[str, Any], fields: list[tuple[str, dict[str, Any]]],
|
||||
queries: list[dict[str, Any]], loader: Any = None
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""确定性核对:按 from 取出快照里的那一格,以快照为准。返回 (data, data_evidence)。
|
||||
|
||||
每个字段的结果是四种之一:
|
||||
- verified:和模型报的值一致,取快照的值
|
||||
- mismatch:不一致,取快照的值,model_value 留着模型报的
|
||||
- unresolved:出处取不到(没有这次查询、行列不存在、快照取不回来),值为 None,reason 写原因
|
||||
- missing:模型说查不到(from 为 null),值为 None
|
||||
值为 None 就是 None:永远不兜底成 0,也不采信没有出处的模型值。
|
||||
"""
|
||||
load = loader or artifact_store.load
|
||||
by_alias = {q["alias"]: q for q in queries}
|
||||
snapshots: dict[str, tuple[Any, str | None]] = {}
|
||||
|
||||
def snapshot_of(q: dict[str, Any]) -> tuple[Any, str | None]:
|
||||
if q["artifact"] not in snapshots:
|
||||
try:
|
||||
content = load(q["artifact"])
|
||||
snapshots[q["artifact"]] = (content, None if content is not None else "查询快照取不回来")
|
||||
except ValueError:
|
||||
snapshots[q["artifact"]] = (None, "查询快照和哈希对不上,疑似被改过")
|
||||
return snapshots[q["artifact"]]
|
||||
|
||||
parsed = extracted.get("parsed")
|
||||
failed = extracted.get("error") or (None if isinstance(parsed, dict) else "抽取结果不是一个对象")
|
||||
data: dict[str, Any] = {}
|
||||
evidence: dict[str, Any] = {}
|
||||
for path, sub in fields:
|
||||
_plant(data, path, None)
|
||||
if failed:
|
||||
evidence[path] = {"status": "unresolved", "reason": str(failed)}
|
||||
continue
|
||||
node = _dig(parsed, path)
|
||||
if not isinstance(node, dict) or "from" not in node:
|
||||
evidence[path] = {"status": "unresolved", "reason": "抽取结果里没有按 {value, from} 写出这个字段"}
|
||||
continue
|
||||
told, source = node.get("value"), node.get("from")
|
||||
if source is None:
|
||||
evidence[path] = {"ref": None, "status": "missing",
|
||||
**({"model_value": told} if told is not None else {})}
|
||||
continue
|
||||
if _is_array(sub):
|
||||
value, evidence[path] = _verify_rows(sub, told, source, by_alias, snapshot_of)
|
||||
_plant(data, path, value)
|
||||
continue
|
||||
call = str(source.get("call") or "").strip() if isinstance(source, dict) else ""
|
||||
row, column = (source.get("row"), source.get("column")) if isinstance(source, dict) else (None, None)
|
||||
if isinstance(row, str) and row.strip().isdigit():
|
||||
row = int(row) # 有的模型把整数写成 "0":意思没有歧义
|
||||
elif isinstance(row, float) and row.is_integer():
|
||||
row = int(row)
|
||||
ref = f"{call}.r{row}.{column}" if call and isinstance(row, int) and column not in (None, "") else None
|
||||
q = by_alias.get(call)
|
||||
if q is None:
|
||||
evidence[path] = {"ref": ref, "call": call, "status": "unresolved",
|
||||
"reason": f"本节点没有 {call or '(空)'} 这次查询,能用的是 "
|
||||
+ ("、".join(by_alias) or "(没有)")}
|
||||
continue
|
||||
base = {"ref": ref, "call": call, "artifact": q["artifact"], "via": q["via"]}
|
||||
content, why = snapshot_of(q)
|
||||
if why:
|
||||
evidence[path] = {**base, "status": "unresolved", "reason": f"{call} 的{why}"}
|
||||
continue
|
||||
try:
|
||||
raw, name = locate_cell(content, row, column)
|
||||
except CellError as e:
|
||||
evidence[path] = {**base, "status": "unresolved", "reason": f"{call} {e}"}
|
||||
continue
|
||||
truth = _typed(raw, sub, column_kind(content, name))
|
||||
locator = {"row": row, "column": name}
|
||||
cited = {**base, "ref": f"{call}.r{row}.{name}", "locator": locator,
|
||||
"eid": cell_eid(q["artifact"], row, name)}
|
||||
if same_value(told, truth):
|
||||
cited["status"] = "verified"
|
||||
else:
|
||||
cited.update(status="mismatch", model_value=told)
|
||||
_plant(data, path, truth)
|
||||
evidence[path] = cited
|
||||
return data, evidence
|
||||
|
||||
|
||||
_ROWS = re.compile(r"^\s*(\d+)\s*(?:-\s*(\d+))?\s*$")
|
||||
|
||||
|
||||
def _verify_rows(schema: dict[str, Any], told: Any, source: Any, by_alias: dict[str, dict[str, Any]],
|
||||
snapshot_of: Any) -> tuple[Any, dict[str, Any]]:
|
||||
"""数组字段:按 from 的行范围和列从快照里取出整组值,以快照为准。返回 (值, 出处)。"""
|
||||
if not isinstance(source, dict):
|
||||
return None, {"status": "unresolved", "reason": "数组的 from 要写成 {call, rows, column(或 columns)}"}
|
||||
call = str(source.get("call") or "").strip()
|
||||
span = _ROWS.match(str(source.get("rows") or ""))
|
||||
fields = _row_columns(schema)
|
||||
wanted = source.get("columns") if fields is not None else source.get("column")
|
||||
if fields is not None and not (isinstance(wanted, dict) and all(isinstance(wanted.get(f), str) for f in fields)):
|
||||
return None, {"call": call, "status": "unresolved", "reason": "对象数组要写 columns:每个字段取自哪一列"}
|
||||
if fields is None and not isinstance(wanted, str):
|
||||
return None, {"call": call, "status": "unresolved", "reason": "数组要写 column:这组值取自哪一列"}
|
||||
if span is None:
|
||||
return None, {"call": call, "status": "unresolved", "reason": "rows 要写成 0-4 这样的行号范围(从 0 数)"}
|
||||
first, last = int(span.group(1)), int(span.group(2) or span.group(1))
|
||||
q = by_alias.get(call)
|
||||
if q is None or last < first:
|
||||
reason = (f"rows 要从小到大写,写的是 {source.get('rows')}" if q is not None else
|
||||
f"本节点没有 {call or '(空)'} 这次查询,能用的是 " + ("、".join(by_alias) or "(没有)"))
|
||||
return None, {"call": call, "status": "unresolved", "reason": reason}
|
||||
base = {"call": call, "artifact": q["artifact"], "via": q["via"]}
|
||||
content, why = snapshot_of(q)
|
||||
if why:
|
||||
return None, {**base, "status": "unresolved", "reason": f"{call} 的{why}"}
|
||||
columns = {f: wanted[f] for f in fields} if fields is not None else {"": wanted}
|
||||
items = schema.get("items") if isinstance(schema.get("items"), dict) else {}
|
||||
kinds = ({f: (items.get("properties") or {}).get(f) for f in fields} if fields is not None else {"": items})
|
||||
truth: list[Any] = []
|
||||
names: dict[str, str] = {}
|
||||
try:
|
||||
for r in range(first, last + 1):
|
||||
one = {}
|
||||
for f, col in columns.items():
|
||||
raw, names[f] = locate_cell(content, r, col)
|
||||
one[f] = _typed(raw, kinds[f], column_kind(content, names[f]))
|
||||
truth.append(one if fields is not None else one[""])
|
||||
except CellError as e:
|
||||
return None, {**base, "status": "unresolved", "reason": f"{call} {e}"}
|
||||
locator: dict[str, Any] = {"rows": [first, last],
|
||||
**({"columns": names} if fields is not None else {"column": names[""]})}
|
||||
cited = {"ref": f"{call}.r{first}-{last}" + ("" if fields is not None else f".{names['']}"), **base,
|
||||
"locator": locator, "eid": make_eid("rows", q["artifact"], locator)}
|
||||
same = isinstance(told, list) and len(told) == len(truth) and all(
|
||||
(isinstance(m, dict) and all(same_value(m.get(f), t[f]) for f in t)) if isinstance(t, dict)
|
||||
else same_value(m, t)
|
||||
for m, t in zip(told, truth))
|
||||
cited.update({"status": "verified"} if same else {"status": "mismatch", "model_value": told})
|
||||
return truth, cited
|
||||
|
||||
|
||||
def _shown(value: Any) -> str:
|
||||
text = json.dumps(value, ensure_ascii=False, default=str) if not isinstance(value, str) else value
|
||||
return text if len(text) <= 40 else text[:40] + "…"
|
||||
|
||||
|
||||
def _field_warnings(data: dict[str, Any], evidence: dict[str, Any],
|
||||
failed: str | None) -> list[tuple[str, str, list[str]]]:
|
||||
"""核对结果里要让人看见的:(code, message, 字段)。mismatch 和 unresolved 各一条;missing 是模型
|
||||
照实说没查到,值已经是空的,不另发警告。"""
|
||||
out: list[tuple[str, str, list[str]]] = []
|
||||
mismatched = [(p, e) for p, e in evidence.items() if e.get("status") == "mismatch"]
|
||||
if mismatched:
|
||||
detail = ";".join(f"{p} 模型报 {_shown(e.get('model_value'))},快照是 {_shown(_dig(data, p))}"
|
||||
for p, e in mismatched[:6])
|
||||
out.append(("agent_field_mismatch",
|
||||
f"有 {len(mismatched)} 个字段和查询快照对不上,已按快照取值:{detail}", [p for p, _ in mismatched]))
|
||||
unresolved = [(p, e) for p, e in evidence.items() if e.get("status") == "unresolved"]
|
||||
if unresolved:
|
||||
if failed:
|
||||
message = f"{failed}。{len(unresolved)} 个字段都记为空值(没有兜底成 0)"
|
||||
else:
|
||||
detail = ";".join(f"{p}({e.get('reason')})" for p, e in unresolved[:6])
|
||||
message = f"有 {len(unresolved)} 个字段核对不了出处,记为空值(没有兜底成 0):{detail}"
|
||||
out.append(("agent_field_unverified", message, [p for p, _ in unresolved]))
|
||||
return out
|
||||
|
||||
@@ -1,14 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.core import artifact_store
|
||||
from app.core.errors import describe_exception
|
||||
from app.core.events import EventType
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
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.evidence import (
|
||||
DEFAULT_FORMAT,
|
||||
FORMATS,
|
||||
MISSING,
|
||||
RenderError,
|
||||
cell_eid,
|
||||
is_number,
|
||||
next_exec,
|
||||
render_number,
|
||||
)
|
||||
from app.engine.expressions import (
|
||||
CellError,
|
||||
ExpressionError,
|
||||
cell_parts,
|
||||
cell_value,
|
||||
eval_expression,
|
||||
leaf_refs,
|
||||
locate_cell,
|
||||
parse_expression,
|
||||
same_value,
|
||||
substitute,
|
||||
)
|
||||
from app.engine.state import GraphState, template_context
|
||||
|
||||
|
||||
@@ -24,12 +46,18 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
数字点开,一路能追到这里。
|
||||
"""
|
||||
definitions = ctx.cfg("metrics", []) or []
|
||||
caliber_raw, caliber_version = ctx.cfg("caliber", "") or ctx.node.title, str(ctx.cfg("caliber_version", "") or "v1")
|
||||
source: dict[str, Any] | None = None
|
||||
if ctx.config.get("caliber_from") not in (None, "", {}):
|
||||
# 钉住别的工作流某一版里的口径卡:名字、版本、指标定义都按那一版,本地写的不算
|
||||
pinned, source = await _pinned_caliber(ctx)
|
||||
definitions = pinned["metrics"]
|
||||
caliber_raw, caliber_version = pinned["caliber"], pinned["caliber_version"]
|
||||
if not definitions:
|
||||
raise NodeError(ctx.node.id, "口径卡没有定义任何指标")
|
||||
|
||||
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")
|
||||
caliber = ctx.render_str(caliber_raw, state)
|
||||
# 缺输入时怎么办。默认 fail:和以前一样整张卡失败;null 则这个指标记为空值、
|
||||
# 交给出具契约的 required / expected 去判档
|
||||
on_missing = str(ctx.cfg("on_missing", "fail") or "fail")
|
||||
@@ -98,7 +126,7 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"decimals": decimals,
|
||||
"format": display["format"],
|
||||
"rendered": _rendered(value, definition, display),
|
||||
"inputs": [_input_of(path, values[path], state, ctx) for path in paths],
|
||||
"inputs": [_input_of(path, values[path], state, ctx, tctx) for path in paths],
|
||||
"substituted": substituted,
|
||||
"recompute_ok": _recompute(substituted, tctx, value, decimals),
|
||||
# 值是空的就是缺输入,不论 on_missing 是哪一种:fail 模式下直接取到空值的
|
||||
@@ -123,6 +151,9 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"caliber_version": caliber_version,
|
||||
"metrics": metrics,
|
||||
}
|
||||
if source:
|
||||
# 指标定义来自哪个工作流的哪一版:证据面板的指标步骤据此写出处,升版处置按它比版本
|
||||
card["source"] = source
|
||||
artifact = await _store(card, caliber, caliber_version, ctx)
|
||||
result = {
|
||||
**card,
|
||||
@@ -137,16 +168,15 @@ 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,
|
||||
"exec": next_exec(state, ctx.node.id),
|
||||
"artifact": artifact,
|
||||
"caliber": caliber,
|
||||
"version": caliber_version,
|
||||
"metrics": [m["id"] for m in metrics],
|
||||
**({"source": source} if source else {}),
|
||||
}]
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
@@ -154,6 +184,60 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
return updates
|
||||
|
||||
|
||||
async def _pinned_caliber(ctx: NodeContext) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""caliber_from 指向的那张口径卡:({caliber, caliber_version, metrics}, 来源)。
|
||||
|
||||
从那个工作流的 WorkflowVersion 快照里取——版本快照不可变,同一份引用每次取到的定义都一样,
|
||||
审批恢复后节点重放也还是这一份。取不到就让节点失败并说清是哪一环断了:悄悄退回本地
|
||||
定义,等于换了口径还照常出具。
|
||||
"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import Workflow, WorkflowVersion
|
||||
from app.engine.schema import type_label
|
||||
|
||||
ref = ctx.config.get("caliber_from")
|
||||
wf_id = str(ref.get("workflow_id") or "").strip() if isinstance(ref, dict) else ""
|
||||
node_id = str(ref.get("node_id") or "").strip() if isinstance(ref, dict) else ""
|
||||
version = _integer(ref.get("workflow_version")) if isinstance(ref, dict) else None
|
||||
if not wf_id or not node_id or version is None or version < 1:
|
||||
raise NodeError(ctx.node.id, "caliber_from 要写 {workflow_id, workflow_version, node_id}:钉住哪个工作流"
|
||||
f"的哪一版里的哪张口径卡,写的是 {ref!r}")
|
||||
async with SessionLocal() as session:
|
||||
workflow = await session.get(Workflow, wf_id)
|
||||
if workflow is None:
|
||||
raise NodeError(ctx.node.id, f"caliber_from 钉住的工作流 {wf_id} 不存在(可能已经被删了):"
|
||||
"在节点里重新选一张口径卡")
|
||||
snapshot = (await session.execute(select(WorkflowVersion).where(
|
||||
WorkflowVersion.workflow_id == wf_id, WorkflowVersion.version == version))).scalar_one_or_none()
|
||||
name = workflow.name
|
||||
if snapshot is None:
|
||||
raise NodeError(ctx.node.id, f"caliber_from 钉住的「{name}」没有 v{version} 这个版本:在节点里重新选版本")
|
||||
found = next((n for n in (snapshot.graph or {}).get("nodes") or []
|
||||
if isinstance(n, dict) and n.get("id") == node_id), None)
|
||||
if found is None:
|
||||
raise NodeError(ctx.node.id, f"「{name}」v{version} 里没有节点 {node_id}:在节点里重新选一张口径卡")
|
||||
data = found.get("data") if isinstance(found.get("data"), dict) else {}
|
||||
title = data.get("label") or node_id
|
||||
if found.get("type") != "metrics":
|
||||
raise NodeError(ctx.node.id, f"caliber_from 指向的「{name}」v{version} 里的「{title}」不是口径卡,"
|
||||
f"是「{type_label(found.get('type'))}」")
|
||||
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
||||
origin = cfg.get("caliber_from")
|
||||
if origin not in (None, "", {}):
|
||||
root = origin.get("workflow_id") if isinstance(origin, dict) else None
|
||||
async with SessionLocal() as session:
|
||||
upstream = await session.get(Workflow, str(root)) if root else None
|
||||
where = (f"「{upstream.name}」v{origin.get('workflow_version')} 的 {origin.get('node_id')}"
|
||||
if upstream is not None else f"{origin!r}")
|
||||
raise NodeError(ctx.node.id, f"「{name}」v{version} 里的「{title}」自己也是钉住别处的口径卡(源头是 {where}):"
|
||||
"直接钉住源头那张,升版处置才比得对版本")
|
||||
source = {"workflow_id": wf_id, "workflow_version": version, "node_id": node_id}
|
||||
return {"caliber": cfg.get("caliber") or title, "caliber_version": str(cfg.get("caliber_version") or "v1"),
|
||||
"metrics": cfg.get("metrics") or []}, source
|
||||
|
||||
|
||||
#: 新写法的小数位范围。负数是取整到十位、百位(round(x, -2))
|
||||
_DECIMALS_RANGE = 15
|
||||
|
||||
@@ -248,12 +332,19 @@ _VIA = {"input": "input", "code": "code", "agent": "agent", "llm": "llm", "tool"
|
||||
"memory": "memory"}
|
||||
|
||||
|
||||
def _input_of(path: str, value: Any, state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
def _input_of(path: str, value: Any, state: GraphState, ctx: NodeContext,
|
||||
tctx: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""一个输入的来历:{path, value, node_id, via, field?, role?, status}。
|
||||
|
||||
vars.X 要反查是谁写的:assign_to 为 X 的节点里,按执行顺序最后跑的那一个——
|
||||
和状态里 vars 的覆盖顺序一致。入口节点把输入字段也写进 vars。
|
||||
|
||||
两种来历能追到查询快照里的那一格:
|
||||
- cell(nodes.fetch, 0, 'gmv'):via tool_cell,带 locator、artifact、eid,按快照核对
|
||||
- agent 开了 cite_fields 的字段:via agent_field,接上它的 data_evidence(eid、核对状态)
|
||||
"""
|
||||
if (parts := cell_parts(path)) is not None:
|
||||
return _cell_input(path, value, parts, state, ctx, tctx or template_context(state))
|
||||
spec = ctx.run.spec
|
||||
nodes = spec.node_map()
|
||||
node_id: str | None = None
|
||||
@@ -281,6 +372,136 @@ def _input_of(path: str, value: Any, state: GraphState, ctx: NodeContext) -> dic
|
||||
# 沙箱算出来的数喂给口径卡:记下它自认是「取数」还是「计算」,治理规则按它判
|
||||
entry["role"] = str(producer.config.get("evidence_role") or "compute")
|
||||
entry["status"] = "ok" if value is not None else "missing"
|
||||
if producer is not None and str(producer.type) == "agent" and field:
|
||||
cited = _agent_field(state, producer.id, root if head else "", field)
|
||||
if cited is not None:
|
||||
entry.update(cited)
|
||||
return entry
|
||||
|
||||
|
||||
def _field_key(field: str) -> str:
|
||||
"""vars.kpi['gmv'] 和 vars.kpi.gmv 是同一个字段:下标写法换成点号。"""
|
||||
return re.sub(r"\[\s*['\"]([^'\"\]]+)['\"]\s*\]", r".\1", field).strip(".")
|
||||
|
||||
|
||||
def _agent_field(state: GraphState, node_id: str, root: str, field: str) -> dict[str, Any] | None:
|
||||
"""agent 字段的出处:{via: agent_field, field, ref, artifact, locator, eid, status, model_value?, reason?}。
|
||||
|
||||
assign_to 写进 vars 的是 data 本身,nodes.<agent> 下要多走一层 data。没开 cite_fields
|
||||
(或者是老运行)的 agent 没有 data_evidence,返回 None,来历照旧记成 agent。
|
||||
"""
|
||||
output = (state.get("nodes") or {}).get(node_id)
|
||||
evidence = output.get("data_evidence") if isinstance(output, dict) else None
|
||||
if not isinstance(evidence, dict):
|
||||
return None
|
||||
key = _field_key(field)
|
||||
if root == "nodes":
|
||||
if not key.startswith("data."):
|
||||
return None
|
||||
key = key[len("data."):]
|
||||
cited = evidence.get(key)
|
||||
if not isinstance(cited, dict):
|
||||
return _agent_element(evidence, key)
|
||||
out: dict[str, Any] = {"via": "agent_field", "field": key, "status": cited.get("status") or "unresolved"}
|
||||
for k in ("ref", "artifact", "locator", "eid", "model_value", "reason"):
|
||||
if k in cited:
|
||||
out[k] = cited[k]
|
||||
return out
|
||||
|
||||
|
||||
_ELEMENT = re.compile(r"^(?P<base>[^\[\]]+)\[(?P<index>\d+)\](?:\.(?P<sub>[^\[\]]+))?$")
|
||||
|
||||
|
||||
def _agent_element(evidence: dict[str, Any], key: str) -> dict[str, Any] | None:
|
||||
"""数组字段里的一个元素(vars.kpi.weeks[1].amount):按行映射落到快照里的一格。
|
||||
|
||||
数组的出处是一段行 rows=[a, b] 加列;第 k 个元素就是第 a+k 行。整组的核对状态说的是整组:
|
||||
别的元素对不上,不等于这一个也对不上。所以这一个元素按它自己那一格再核一遍——模型报的是
|
||||
model_value 里的第 k 个(整组 verified 时模型报的就是快照里的值),和快照里那一格比。
|
||||
"""
|
||||
m = _ELEMENT.match(key)
|
||||
cited = evidence.get(m.group("base")) if m else None
|
||||
locator = cited.get("locator") if isinstance(cited, dict) else None
|
||||
if not (isinstance(locator, dict) and isinstance(locator.get("rows"), list) and len(locator["rows"]) == 2):
|
||||
return None
|
||||
first, last = locator["rows"]
|
||||
index, sub = int(m.group("index")), m.group("sub")
|
||||
row = first + index
|
||||
column = (locator.get("columns") or {}).get(sub) if sub else locator.get("column")
|
||||
if row > last or not isinstance(column, str):
|
||||
return None
|
||||
call, artifact = str(cited.get("call") or ""), cited.get("artifact")
|
||||
out: dict[str, Any] = {"via": "agent_field", "field": key, "ref": f"{call}.r{row}.{column}", "artifact": artifact,
|
||||
"locator": {"row": row, "column": column}, "eid": cell_eid(artifact, row, column)}
|
||||
try:
|
||||
truth, _ = locate_cell(artifact_store.load(artifact), row, column)
|
||||
except (ValueError, CellError, OSError) as e:
|
||||
out.update(status="unresolved", reason=f"查询快照取不回来或对不上:{e}")
|
||||
return out
|
||||
if cited.get("status") == "verified":
|
||||
out["status"] = "verified"
|
||||
return out
|
||||
told = cited.get("model_value")
|
||||
item = told[index] if isinstance(told, list) and index < len(told) else None
|
||||
reported = isinstance(told, list) and index < len(told) and (not sub or (isinstance(item, dict) and sub in item))
|
||||
element = (item[sub] if sub else item) if reported else None
|
||||
if reported and same_value(element, truth):
|
||||
out["status"] = "verified"
|
||||
else:
|
||||
# 模型没报这个元素(给的数组短了)就没有 model_value 可留
|
||||
out.update(status="mismatch", **({"model_value": element} if reported else {}))
|
||||
return out
|
||||
|
||||
|
||||
def _cell_input(path: str, value: Any, parts: tuple[str, str, str], state: GraphState, ctx: NodeContext,
|
||||
tctx: dict[str, Any]) -> dict[str, Any]:
|
||||
"""cell() 取的那一格:它来自哪次查询(台账里的 query 条目)、第几行哪一列、快照里是不是这个值。
|
||||
|
||||
查询结果经 transform 解析过也认得出来:数据源工具交回的 JSON 里带着快照的工件 id。
|
||||
取不到快照、或者快照里那一格和算的时候用的值不一样,status 如实写,不替它圆。
|
||||
"""
|
||||
source, row_src, column_src = parts
|
||||
entry: dict[str, Any] = {"path": path, "value": value if value is None or isinstance(value, (int, float, str, bool))
|
||||
else _brief(value), "node_id": None, "via": "tool_cell"}
|
||||
table = _value_of(source, tctx)
|
||||
row, column = _value_of(row_src, tctx), _value_of(column_src, tctx)
|
||||
data = table
|
||||
if isinstance(data, str):
|
||||
try:
|
||||
data = json.loads(data)
|
||||
except ValueError:
|
||||
data = None
|
||||
artifact = data.get("artifact") if isinstance(data, dict) else None
|
||||
queries = [e for e in state.get("evidence") or [] if isinstance(e, dict) and e.get("kind") == "query"]
|
||||
ledger = next((e for e in reversed(queries) if artifact and e.get("artifact") == artifact), None)
|
||||
head = _REF_HEAD.match(source)
|
||||
if ledger is None and head and head.group(1) == "nodes":
|
||||
# 台账是按工件认的;工具交回的不是带工件 id 的 JSON 时,按取值链上的节点找它最后一次查询
|
||||
ledger = next((e for e in reversed(queries) if e.get("node_id") == head.group(2)), None)
|
||||
if ledger is None:
|
||||
entry.update(node_id=head.group(2) if head and head.group(1) == "nodes" else None,
|
||||
status="unresolved", reason="找不到这份数据对应的查询快照:cell() 要取查询工具交回的结果")
|
||||
return entry
|
||||
entry["node_id"] = ledger.get("node_id")
|
||||
artifact = ledger.get("artifact")
|
||||
try:
|
||||
raw, name = locate_cell(data if isinstance(data, dict) else table, row, column)
|
||||
except CellError as e:
|
||||
entry.update(status="unresolved", reason=f"cell() {e}", artifact=artifact)
|
||||
return entry
|
||||
locator = {"row": row, "column": name}
|
||||
entry.update(locator=locator, artifact=artifact, eid=cell_eid(artifact, row, name))
|
||||
try:
|
||||
snapshot = artifact_store.load(artifact)
|
||||
truth, _ = locate_cell(snapshot, row, name)
|
||||
except (ValueError, CellError, OSError) as e:
|
||||
entry.update(status="unresolved", reason=f"查询快照取不回来或对不上:{e}")
|
||||
return entry
|
||||
if cell_value(truth) != cell_value(raw):
|
||||
# 算的时候用的值和快照不一样(上游改写过这份结果):照实记下快照里的值
|
||||
entry.update(status="mismatch", snapshot_value=cell_value(truth))
|
||||
return entry
|
||||
entry["status"] = "verified"
|
||||
return entry
|
||||
|
||||
|
||||
|
||||
@@ -25,12 +25,14 @@ from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.evidence import (
|
||||
CELLS_REASON,
|
||||
MARKER_RULES,
|
||||
StreamRenderer,
|
||||
build_catalog,
|
||||
catalog_prompt,
|
||||
compose_doc,
|
||||
describe_violations,
|
||||
ledger_enabled,
|
||||
)
|
||||
from app.engine.nodes.llm import _invoke_streaming, _model_spec, _report_call
|
||||
from app.engine.schema import GraphNode, GraphSpec, NodeType, _ancestors
|
||||
@@ -104,6 +106,36 @@ def report_allowance(spec: GraphSpec, node: GraphNode) -> list[Any]:
|
||||
return allowed
|
||||
|
||||
|
||||
def report_cells_allowed(spec: GraphSpec, node: GraphNode, *, governed: bool) -> bool:
|
||||
"""报告能不能直接引用查询单元格:出口契约的 report_from 指着它、而那份契约不允许的,写作时就不给。
|
||||
|
||||
出口复核按契约判(io.py),这里提前照同一条规则建目录:不然写作者照着提示写了单元格、自查
|
||||
通过,到出口才整段判成解析不了——受管出具直接不予出具。
|
||||
"""
|
||||
from app.engine.governance import cells_allowed
|
||||
|
||||
contracts = [other.config.get("contract") for other in spec.nodes if other.type == NodeType.OUTPUT]
|
||||
return all(cells_allowed(c, governed=governed) for c in contracts
|
||||
if isinstance(c, dict) and c.get("report_from") == node.id)
|
||||
|
||||
|
||||
#: 目录里能被报告引用的几种来源(沙箱代码节点的登记只为说清为什么不能引用,不算)
|
||||
_CITABLE = {"metric": "口径卡指标", "query": "查询结果", "retrieval": "知识库检索", "input": "运行输入"}
|
||||
|
||||
|
||||
def _no_evidence(catalog: dict[str, Any], cells: bool) -> str | None:
|
||||
"""目录里没有可引用的来源时给一句话,说清缺的是哪种;有就返回 None。"""
|
||||
kinds = {entry.get("kind") for entry in catalog.values()}
|
||||
if not kinds & set(_CITABLE):
|
||||
return ("报告撰写节点的上游没有可引用的来源:" + "、".join(_CITABLE.values()) + "都没有,"
|
||||
"报告里的数字都会被判为没有出处。在它前面接取数节点或口径卡,或者检查 metrics_from / evidence_from")
|
||||
if not cells and not kinds & {"metric", "input"}:
|
||||
# 只有查询和检索:单元格引用不了,检索片段本来就只能当依据,一个数都没处引
|
||||
return (f"报告撰写节点的上游只有查询结果、没有口径卡指标,而这次{CELLS_REASON}:单元格引用不了,"
|
||||
"报告里的数字都会被判为没有出处。在出口契约里写 \"cells\": true,或者把要写的数登记进口径卡")
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 执行器
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -116,10 +148,11 @@ class _RenderedStream:
|
||||
中间,StreamRenderer 攒到没有未闭合的 [[ 再放;调用结束时 flush 掉剩下的。
|
||||
"""
|
||||
|
||||
def __init__(self, ctx: NodeContext, catalog: dict[str, Any]) -> None:
|
||||
def __init__(self, ctx: NodeContext, catalog: dict[str, Any], cells: bool = True) -> None:
|
||||
self._ctx = ctx
|
||||
self._catalog = catalog
|
||||
self._renderer = StreamRenderer(catalog)
|
||||
self._cells = cells
|
||||
self._renderer = StreamRenderer(catalog, cells_allowed=cells)
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._ctx, name)
|
||||
@@ -131,7 +164,7 @@ class _RenderedStream:
|
||||
return
|
||||
if event_type == EventType.LOG and data.get("code") == "stream_fallback":
|
||||
# 流断在半路、退回非流式重来:攒着的半截不再放出去,免得和重来的那份接在一起
|
||||
self._renderer = StreamRenderer(self._catalog)
|
||||
self._renderer = StreamRenderer(self._catalog, cells_allowed=self._cells)
|
||||
self._ctx.emit(event_type, **data)
|
||||
|
||||
def flush(self) -> None:
|
||||
@@ -183,14 +216,14 @@ def _repair_request(violations: list[dict[str, Any]]) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _messages(ctx: NodeContext, state: GraphState, catalog: dict[str, Any]) -> list[BaseMessage]:
|
||||
def _messages(ctx: NodeContext, state: GraphState, catalog: dict[str, Any], cells: bool = True) -> 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"
|
||||
f"{instructions}\n\n{catalog_prompt(catalog, cells_allowed=cells)}\n\n{MARKER_RULES}\n\n"
|
||||
"只输出报告正文(Markdown),不要写撰写说明。"
|
||||
)),
|
||||
]
|
||||
@@ -223,19 +256,23 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
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")
|
||||
cells = True
|
||||
if ledger_enabled(ctx.run):
|
||||
# 升级前发起的运行没有查询条目,单元格无从谈起,也就不多查这一次
|
||||
from app.engine.governance import governed_formal
|
||||
|
||||
messages = _messages(ctx, state, catalog)
|
||||
cells = report_cells_allowed(spec, ctx.node, governed=await governed_formal(ctx.run.run_id))
|
||||
if warning := _no_evidence(catalog, cells):
|
||||
ctx.emit(EventType.LOG, level="warn", code="report_no_evidence", message=warning)
|
||||
|
||||
messages = _messages(ctx, state, catalog, cells)
|
||||
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)
|
||||
stream = _RenderedStream(ctx, catalog, cells)
|
||||
began = time.perf_counter()
|
||||
response = await _invoke_streaming(model, payload, stream, model_id) # type: ignore[arg-type]
|
||||
stream.flush()
|
||||
@@ -255,7 +292,8 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
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)
|
||||
return compose_doc(raw, catalog, node_id=ctx.node.id, run_id=ctx.run.run_id, allow_numbers=allow,
|
||||
cells_allowed=cells)
|
||||
|
||||
response, raw = await draft(messages)
|
||||
doc = compose(raw)
|
||||
|
||||
@@ -9,13 +9,16 @@ from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from langgraph.func import task
|
||||
|
||||
from app.core.artifact_store import canonical_json, content_hash
|
||||
from app.engine.approval import read_decision
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.evidence import ledger_enabled, next_exec, query_entry_fields
|
||||
from app.engine.replay import ask, once
|
||||
from app.engine.state import GraphState
|
||||
from app.engine.toolcalls import ToolTimeout, limit_fields, limit_of, run_bounded
|
||||
from app.sandbox.base import SandboxLimits
|
||||
from app.sandbox.manager import sandbox_manager
|
||||
from app.tools.datasource import QUERY_PREFIX
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
ToolBuildError,
|
||||
@@ -27,6 +30,12 @@ from app.tools.registry import (
|
||||
)
|
||||
from app.tools.trust import ask_gate, asks_trustable, call_policy, node_task
|
||||
|
||||
#: 数据源查询工具没查成时交回的话的开头(tools/datasource.py)。agent 里原话喂回模型让它改 SQL;
|
||||
#: tool 节点没有下一轮可改,照常往下走的话,下游拿到的是一句报错当查询结果
|
||||
QUERY_FAILED = ("查询失败:", "SQL 被拒绝:")
|
||||
#: code 节点在证据链里的角色:取数(产出本身就是源数据)还是计算。缺省按计算算
|
||||
EVIDENCE_ROLES = ("source", "compute")
|
||||
|
||||
|
||||
def _tool_ctx(ctx: NodeContext) -> ToolContext:
|
||||
return ToolContext(
|
||||
@@ -146,6 +155,14 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
result = {"error": reason, "detail": raw_detail(e)}
|
||||
|
||||
elapsed = int((time.perf_counter() - started) * 1000)
|
||||
evidence_on = ledger_enabled(ctx.run)
|
||||
if evidence_on and name.startswith(QUERY_PREFIX) and isinstance(result, str) and result.startswith(QUERY_FAILED):
|
||||
# 没查成:原话就是报错(「查询失败:no such table: x」),照写,别再套一层
|
||||
ctx.emit(EventType.TOOL_ERROR, tool=name, error=result[:2000], duration_ms=elapsed)
|
||||
if ctx.cfg("fail_fast", True):
|
||||
raise NodeError(ctx.node.id, f"工具 {name} 没查成——{result}。按这句话改节点里的 SQL 再跑")
|
||||
result = {"error": result}
|
||||
|
||||
# 取数快照:query(args)和结果集一起进工件库,完整出具时数字回指的就是它
|
||||
from app.core.artifact_store import put_json
|
||||
|
||||
@@ -156,11 +173,26 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
snapshot_id = None
|
||||
# 只认数据源工具交回的查询:别的工具(MCP、自定义)拼出同样形状的 JSON,里面的工件 id 不是我们落的
|
||||
query = query_entry_fields(result) if evidence_on and name.startswith(QUERY_PREFIX) else None
|
||||
ctx.emit(EventType.TOOL_END, tool=name, duration_ms=elapsed,
|
||||
preview=json.dumps(result, ensure_ascii=False, default=str)[:2000],
|
||||
artifact=snapshot_id)
|
||||
artifact=snapshot_id, **({"query_artifact": query["artifact"]} if query else {}))
|
||||
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
|
||||
if evidence_on:
|
||||
# 证据台账:工具快照一条;查库的再记一条查询快照(外面包着的是工具快照)。报告按台账编 Q1…
|
||||
exec_no = next_exec(state, ctx.node.id)
|
||||
entries: list[dict[str, Any]] = []
|
||||
if snapshot_id:
|
||||
entries.append({"kind": "tool", "node_id": ctx.node.id, "exec": exec_no, "artifact": snapshot_id,
|
||||
"tool": name})
|
||||
if query:
|
||||
entries.append({"kind": "query", "node_id": ctx.node.id, "exec": exec_no, "artifact": query["artifact"],
|
||||
**({"via": snapshot_id} if snapshot_id else {}), "tool": name, "source": query["source"],
|
||||
"columns": query["columns"], "rows": query["rows"], "truncated": query["truncated"]})
|
||||
if entries:
|
||||
updates["evidence"] = entries
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: result}
|
||||
@@ -172,6 +204,10 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
code = ctx.render_str(ctx.cfg("code", ""), state)
|
||||
if not code.strip():
|
||||
raise NodeError(ctx.node.id, "代码节点是空的")
|
||||
evidence_on = ledger_enabled(ctx.run)
|
||||
role = str(ctx.cfg("evidence_role", "") or "compute")
|
||||
if evidence_on and role not in EVIDENCE_ROLES:
|
||||
raise NodeError(ctx.node.id, f"evidence_role 只能是 source(取数)或 compute(计算),写的是 {role!r}")
|
||||
|
||||
language = ctx.cfg("language", "python")
|
||||
limits = SandboxLimits(
|
||||
@@ -269,6 +305,14 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
payload["text"] = text
|
||||
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: payload}}
|
||||
if evidence_on:
|
||||
# 实际送进沙箱的那份代码(渲染之后、审批改过之后)的指纹:同一张图两次运行算出不同的数,
|
||||
# 先看这个就知道代码本身变没变
|
||||
payload["code_sha"] = content_hash(code)
|
||||
# 台账的工件就是节点产出工件:外层包装按同样的内容落盘,id 相同
|
||||
updates["evidence"] = [{"kind": "node_output", "node_id": ctx.node.id, "exec": next_exec(state, ctx.node.id),
|
||||
"artifact": content_hash(canonical_json(payload)), "code_sha": payload["code_sha"],
|
||||
"role": role, "language": language}]
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
# {{ vars.x }} 和 {{ nodes.x.text }} 必须是同一个值:两种写法给不同的
|
||||
|
||||
Reference in New Issue
Block a user