Files
AgentLab/backend/app/engine/nodes/human.py
T
ThearchyHelios cc608f56ec 跑完先过一道复核再交给你:异常说破、数字不许现编、出错自动改一次
「跑完了」和「答得对」之间一直没有任何一层。库里 264 条 succeeded 里,
14 条带着 warn、4 条 agent 步数用满,而交到用户手上的答案对此只字不提。
最糟的一次(run dd9927e6)交出去的干脆是「本轮只执行了第一个工具」——
一句内部管道文案冒充结论。

出具体系(issuance.py)本来就是干这个的,但它挂在输出节点的可选契约上,
还要配口径卡提供受控指标集;问数据页生成的图基本都是 input → agent → output,
走不到那条路。所以补一层轻的。

**干净的运行一次模型都不调。** 先用规则扫一遍事件流(engine/review.py:scan),
没扫出东西就到此为止。实测 15ms 返回。这是整层设计的前提,测试里用
「monkeypatch 一个会抛异常的模型,断言它没被碰过」来守。

**分类挂在 code 上,不是中文消息串。** 12 处 warn 发射点都带上 code。
这样「流式失败,回退非流式」能归成 benign 直接跳过——它对答案内容零影响,
为它叫一次模型等于每次网络抖一下就多花一笔;而「步数用满」归 broken。
原来这两者在事件流里长得一模一样。工具报错之后同一个工具又跑成了,
算 degraded 不算 broken——否则参数自愈每修一次就报一次「答案不可信」。

**复核不许现编数字。** 它手上只有原答案和一份异常清单,没有任何原始数据,
写出来的新数字只能是凭空来的。直接复用 issuance.trace_numbers,把原答案的
数字当受控指标集,对不上就整条退回原答案、只留说明。硬拦截,不是提示。

**规则管重试资格,模型只有否决权。** 一开始写成两边取并,实测 loop_limit
时模型判 retry=true——而重跑一遍循环还是会撞上限,白烧一次建图加一次跑图。
反过来之后,「检索什么都没查到」这类也不会被模型强推重跑。

**重试带着失败的那张图,不是推倒重来。** 原来传 base_graph=null,模型只看到
「原问题 + 一句失败原因」,很可能原样再建出同一张坏图。而且它连自己上次建了
什么都看不到——会话历史按 status != running 过滤,正在重试的这一轮恰好被
排除在外。现在交回去走后端的改图分支,调大步数、改正参数就是改一个字段。
上限一次。

**答案等复核完成再显示。** 端到端抓到的:答案先摆出来,十秒后说明才追上去——
这十秒里用户读的是一个没人核对过的结论,正是要修的那件事本身。改成落库立刻
(防关标签页丢结果)、显示等复核,并给复核加 25s 上限。说明排在成果上方,
broken 用报警色、degraded 用普通边框——混成一个样子用户就学会了一概忽略。

复核结论跟着轮次落库,刷新后还在;也进下一轮的对话历史,否则模型会拿一个
已知不可信的结论当事实继续往下推。

验证:后端 242 passed(新增 test_review.py 25 条);tsc 干净;
check-decode / check-stream / check-ui 全过,check-stream 新增 9 条渲染断言。
两条端到端都在真浏览器 + 真模型上跑通:检索降级那次说明正确排在答案上方;
重试那次建图请求 2 次、第二次 base_graph 带着失败的 3 个节点、第一版没漏出去。

复核结果不是事件流,decode.ts 翻译不到它,所以渲染测试放在 check-stream。
2026-09-20 11:18:53 +08:00

182 lines
7.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import json
from typing import Any
from langgraph.types import interrupt
from app.core.events import EventType
from app.db.base import SessionLocal
from app.engine.context import NodeContext, NodeError
from app.engine.state import GraphState, message_text, template_context
from app.providers.factory import ModelSpec, get_chat_model
async def run_human(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
"""人工介入节点。
执行到这里会挂起整张图并落盘 checkpoint;进程重启也不影响,
人在前端回复之后从断点继续,而不是从头重跑。
"""
mode = ctx.cfg("mode", "approve") # approve | input | edit
payload = {
"kind": "human_node",
"node_id": ctx.node.id,
"mode": mode,
"title": ctx.render_str(ctx.cfg("title", "需要你确认"), state),
"message": ctx.render_str(ctx.cfg("message", ""), state),
"schema": ctx.cfg("schema") or {},
"context": ctx.render(ctx.cfg("context", {}) or {}, state),
}
if mode == "edit":
payload["draft"] = ctx.render(ctx.cfg("draft", ""), state)
ctx.emit(EventType.HUMAN_REQUESTED, **payload)
response = interrupt(payload)
ctx.emit(EventType.HUMAN_RESOLVED, response=response)
if mode == "approve":
approved = _truthy(response)
result: dict[str, Any] = {
"approved": approved,
"note": _note_of(response),
"__decision__": "approved" if approved else "rejected",
}
if not approved and ctx.cfg("stop_on_reject", False):
raise NodeError(ctx.node.id, f"人工拒绝:{result['note'] or '未说明原因'}")
else: # edit / input
# 驳回在这两种模式下以前是个摆设:__decision__ 硬编码成 approved,
# approved 字段看都不看。界面上按钮在、toast 说"已驳回",运行却照常
# 往下走——比没有这个按钮更糟。
#
# 这两种模式在图上只有一个 out 出口(没有 rejected 那条边),所以驳回
# 的正确语义是终止运行,而不是当作通过继续。缺省仍是通过:只传 value
# 不带 approved 的老调用方行为不变。
rejected = isinstance(response, dict) and response.get("approved") is False
if rejected:
note = _note_of(response)
raise NodeError(ctx.node.id, f"人工驳回:{note or '未说明原因'}")
value = response.get("value") if isinstance(response, dict) else response
result = {"value": value, "note": _note_of(response), "__decision__": "approved"}
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
var_name = ctx.cfg("assign_to", "")
if var_name:
updates["vars"] = {var_name: result.get("value", result.get("approved"))}
return updates
def _truthy(value: Any) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, dict):
if "approved" in value:
return bool(value["approved"])
return str(value.get("decision", "")).lower() in ("approve", "yes", "true", "同意")
if isinstance(value, str):
return value.strip().lower() in ("yes", "y", "true", "approve", "ok", "同意", "通过")
return bool(value)
def _note_of(value: Any) -> str:
if isinstance(value, dict):
return str(value.get("note", "") or value.get("comment", ""))
return ""
# --------------------------------------------------------------------------
# 结构化校验
# --------------------------------------------------------------------------
async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
"""按 JSON Schema 校验上游产出。
校验失败时可以把错误原样喂回模型让它改 —— 这比在 prompt 里祈祷它输出正确格式可靠得多。
"""
import jsonschema
schema = ctx.cfg("schema")
if not schema:
raise NodeError(ctx.node.id, "校验节点需要一个 JSON Schema")
source_cfg = ctx.cfg("source", "{{ last_message }}")
raw = ctx.render(source_cfg, state) if not isinstance(source_cfg, str) else ctx.render_str(source_cfg, state)
max_retries = int(ctx.cfg("max_retries", 2) or 0)
repair = bool(ctx.cfg("repair_with_llm", True))
attempt = 0
errors: list[str] = []
value: Any = raw
while True:
value, parse_error = _coerce_json(raw)
if parse_error:
errors = [parse_error]
else:
try:
jsonschema.validate(value, schema)
ctx.emit(EventType.LOG, level="info", message=f"校验通过(第 {attempt + 1} 次尝试)")
result = {"valid": True, "data": value, "attempts": attempt + 1, "errors": []}
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
var_name = ctx.cfg("assign_to", "")
if var_name:
updates["vars"] = {var_name: value}
return updates
except jsonschema.ValidationError as e:
path = "/".join(str(p) for p in e.absolute_path) or "(根)"
errors = [f"{path}: {e.message}"]
ctx.emit(EventType.LOG, level="warn", message=f"第 {attempt + 1} 次校验失败:{errors[0]}",
code="validate_retry")
attempt += 1
if attempt > max_retries or not repair:
break
raw = await _repair(raw, schema, errors, ctx, state)
result = {"valid": False, "data": value, "attempts": attempt, "errors": errors}
if ctx.cfg("fail_fast", True):
raise NodeError(ctx.node.id, f"结构化校验未通过:{'; '.join(errors)}")
return {"nodes": {ctx.node.id: result}}
def _coerce_json(raw: Any) -> tuple[Any, str | None]:
"""尽量把模型输出解析成 JSON:剥掉 ``` 围栏,再退一步找第一个完整对象。"""
if isinstance(raw, (dict, list)):
return raw, None
text = str(raw or "").strip()
if text.startswith("```"):
lines = text.splitlines()
text = "\n".join(lines[1 : -1 if lines[-1].strip().startswith("```") else None]).strip()
try:
return json.loads(text), None
except json.JSONDecodeError:
pass
start = min(
(i for i in (text.find("{"), text.find("[")) if i >= 0), default=-1
)
if start >= 0:
for end in range(len(text), start, -1):
try:
return json.loads(text[start:end]), None
except json.JSONDecodeError:
continue
return text, "输出不是合法 JSON"
async def _repair(raw: Any, schema: dict[str, Any], errors: list[str], ctx: NodeContext,
state: GraphState) -> str:
async with SessionLocal() as session:
model, _ = await get_chat_model(
session,
ModelSpec(provider=ctx.cfg("provider"), model=ctx.cfg("model"), max_tokens=4096),
)
prompt = (
"下面这段输出没有通过 JSON Schema 校验,请修正后重新输出。\n\n"
f"Schema:\n{json.dumps(schema, ensure_ascii=False, indent=2)}\n\n"
f"错误:\n- " + "\n- ".join(errors) + "\n\n"
f"原始输出:\n{str(raw)[:6000]}\n\n"
"只输出修正后的 JSON,不要任何解释或代码围栏。"
)
return message_text(await model.ainvoke(prompt))