diff --git a/backend/app/api/artifacts.py b/backend/app/api/artifacts.py index 4b257fd3..80e3521c 100644 --- a/backend/app/api/artifacts.py +++ b/backend/app/api/artifacts.py @@ -20,5 +20,5 @@ async def get_artifact(artifact_id: str) -> dict[str, Any]: # 哈希对不上:明确报给调用方,这正是工件库存在的意义 raise HTTPException(409, str(e)) from e if content is None: - raise HTTPException(404, "这个工件不存在,可能已经被删了") + raise HTTPException(404, "工件不存在,可能已被删除") return {"id": artifact_id, "content": content} diff --git a/backend/app/api/conversations.py b/backend/app/api/conversations.py index 293e966b..161fe10b 100644 --- a/backend/app/api/conversations.py +++ b/backend/app/api/conversations.py @@ -254,7 +254,7 @@ async def _statuses( async def _get(session: AsyncSession, conversation_id: str) -> Conversation: row = await session.get(Conversation, conversation_id) if not row: - raise HTTPException(404, "这个对话不存在,可能已经被删了") + raise HTTPException(404, "对话不存在,可能已被删除") return row @@ -403,7 +403,7 @@ async def patch_turn( ) -> TurnOut: turn = await session.get(ConversationTurn, turn_id) if not turn or turn.conversation_id != conversation_id: - raise HTTPException(404, "这一轮对话不存在,可能已经被删了") + raise HTTPException(404, "该轮对话不存在,可能已被删除") for field in ( "question", "answer", "explanation", "graph", "run_id", "status", "error", "review", "meta", diff --git a/backend/app/api/copilot.py b/backend/app/api/copilot.py index 569778f2..778153e9 100644 --- a/backend/app/api/copilot.py +++ b/backend/app/api/copilot.py @@ -46,8 +46,8 @@ async def _sources(session: AsyncSession, scope: list[str] | None) -> list[Any]: picked = [r for r in rows if r.id in wanted or r.name in wanted] if not picked: raise CodedHTTPException( - 400, "限定的数据源都不在了:可能已经被删掉或停用。去掉限定再问," - "或者到「数据」页确认它还在、而且是启用的", + 400, "限定的数据源都已不可用,可能已被删除或停用。请取消限定后重试," + "或到「数据」页确认数据源存在且已启用", DATASOURCE_SCOPE_EMPTY, ) return picked @@ -497,7 +497,7 @@ async def set_copilot_model( def _unconfigured(e: ProviderNotConfigured) -> str: - return f"助手用的模型还没配好:{not_configured(e)}。到「设置 → 模型接入」检查一下" + return f"助手使用的模型尚未配置完成:{not_configured(e, with_hint=False)}。请到「设置 → 模型接入」检查" class GenerateOut(BaseModel): @@ -701,8 +701,8 @@ async def generate( except Exception as e: # noqa: BLE001 reason, _ = explain_error(e) raise HTTPException( - 502, f"模型这次没交回能用的工作流({reason})。换个说法再试一次;" - "总是这样的话,到设置里给助手换一个更听指令的模型", + 502, f"模型未返回可用的工作流({reason})。请换一种描述重试;如反复出现," + "请在输入框的「助手使用的模型」中换用指令遵循能力更强的模型", ) from e graph = { @@ -729,7 +729,7 @@ async def generate( spec = GraphSpec.model_validate(graph) except Exception as e: # noqa: BLE001 raise HTTPException( - 502, f"模型交回的工作流结构不对:{graph_error(e)}。再试一次,或者把需求说得更具体些", + 502, f"模型返回的工作流结构有误:{graph_error(e)}。请重试,或把需求描述得更具体", ) from e spec, layout = _layout_keeping(spec, _pinned_positions(payload.base_graph)) @@ -1083,10 +1083,14 @@ def _unsourced_reports(spec: GraphSpec, changed: set[str]) -> list[dict[str, Any if any(_evidence_source(nodes[a]) for a in _ancestors(spec, node.id) if a in nodes): continue out.append({"level": "error", "node_id": node.id, "edge_id": None, "field": None, "code": "report_no_source", - "message": f"「{node.title}」(报告撰写)的上游没有能引用数字的证据来源:没有口径卡、查库的 Agent 或调用工具、" - "知识检索,入口也没有看得出是数的字段,报告里写的数都会被判成没有出处。在它前面接取数的节点" - "(要算比率、增幅再加口径卡),连线连到它;要写的数本来就是运行输入的话,在入口字段上写明数值默认值," - "报告用 [[i:字段名]] 引用"}) + "message": f"「{node.title}」(报告撰写)的上游没有可引用数字的证据来源(口径卡、查询数据的 Agent、" + "调用工具、知识检索,或声明了数值的输入字段),报告中的数字都将被判为没有出处。请在它前面接入" + "取数的节点并连线(需要计算比率、增幅时再添加口径卡);如果要写的数字来自运行输入,请在输入字段" + "上填写数值默认值,报告按 [[i:字段名]] 引用", + "for_model": f"「{node.title}」(报告撰写)的上游没有能引用数字的证据来源:没有口径卡、查库的 Agent 或调用工具、" + "知识检索,入口也没有看得出是数的字段,报告里写的数都会被判成没有出处。在它前面接取数的节点" + "(要算比率、增幅再加口径卡),连线连到它;要写的数本来就是运行输入的话,在入口字段上写明数值" + "默认值,报告用 [[i:字段名]] 引用"}) return out @@ -1106,9 +1110,10 @@ def authored_issues(spec: GraphSpec, sources: list[Any], baseline: list[dict[str for issue in text_parse_issues(spec): if issue.node_id in changed: # 模型的文字放在模板引号里的那种,改法是 | json,不是换结构化输出 - tail = "。不要用整形节点解析 agent / llm 的文字" if "cite_fields" in issue.message else "" + # 给人看的是 validate 那句原话;交回模型改时再补一句该怎么做(for_model) + tail = "。不要用整形节点解析 agent / llm 的文字" if "按出处核对字段" in issue.message else "" out.append({**issue.model_dump(), "level": "error", "code": "parse_model_text", - "message": issue.message + tail}) + **({"for_model": issue.message + tail} if tail else {})}) by_name = {getattr(r, "name", None): r for r in sources} for node in spec.nodes: if node.id not in changed or node.type != NodeType.TOOL: @@ -1126,9 +1131,11 @@ def authored_issues(spec: GraphSpec, sources: list[Any], baseline: list[dict[str listed = "、".join(known[:20]) + (f" 等 {len(known)} 列" if len(known) > 20 else "") out.append({"level": "error", "node_id": node.id, "edge_id": None, "field": "args.sql", "code": "sql_unknown_column", - "message": f"SQL 里的 {'、'.join(unknown[:5])} 在数据源「{source.name}」的结构里查不到(这几张表的列:" - f"{listed})。照结构里的列名改;拿不准就先用 db_schema__{source.name} 查表结构," - "别凭空猜列名"}) + "message": f"SQL 中的列 {'、'.join(unknown[:5])} 在数据源「{source.name}」的表结构中不存在(相关表的列:" + f"{listed})。请按表结构修改列名,不确定时可先查看表结构", + "for_model": f"SQL 里的 {'、'.join(unknown[:5])} 在数据源「{source.name}」的结构里查不到(这几张表的列:" + f"{listed})。照结构里的列名改;拿不准就先用 db_schema__{source.name} 查表结构," + "别凭空猜列名"}) return out @@ -1275,19 +1282,27 @@ def scope_issues(nodes: list[dict[str, Any]], scope: set[str] | None) -> list[Va if outside: out.append(ValidationIssue( level="error", node_id=node.get("id"), - message=f"用了限定范围之外的数据源 {'、'.join(outside)}:这一轮只查 " - f"{'、'.join(sorted(scope))},改用它们的 db_query__ / db_schema__ 工具", + message=f"使用了限定范围之外的数据源 {'、'.join(outside)}:本轮只允许使用 {'、'.join(sorted(scope))}", )) return out +#: 交回模型改时补在问题后面的一句「该怎么做」,按问题代码。界面上只显示问题本身(message) +_FIX_TAIL = {"datasource_out_of_scope": ",改用它们的 db_query__ / db_schema__ 工具"} + + def _issue_dicts(issues: list[ValidationIssue], code: str) -> list[dict[str, Any]]: - return [{**i.model_dump(), "code": code} for i in issues] + tail = _FIX_TAIL.get(code) + return [{**i.model_dump(), "code": code, **({"for_model": i.message + tail} if tail else {})} for i in issues] def _issue_line(issue: dict[str, Any]) -> str: - """交回模型的修正请求里,一条问题一行,节点 id 在前。""" - return f"「{issue['node_id']}」{issue['message']}" if issue.get("node_id") else issue["message"] + """交回模型的修正请求里,一条问题一行,节点 id 在前。 + + 写给模型的改法(for_model:「照结构里的列名改;拿不准就先用 db_schema__x 查」这类)和给人看的问题(message) + 分开存:界面只显示 message,交回模型时有 for_model 用它。键不叫 fix:前端的问题条目里 fix 是修复 id。""" + text = issue.get("for_model") or issue["message"] + return f"「{issue['node_id']}」{text}" if issue.get("node_id") else text # -------------------------------------------------------------------------- @@ -1460,16 +1475,16 @@ def dropped_tool_warnings(changes: list[dict[str, Any]], instruction: str) -> li if not unasked: continue who = f"「{c['label']}」" + (f"的成员「{c['member']}」" if c["member"] else "") - now = f" {'、'.join(c['after'])}" if c["after"] else "空" - said = ("这一轮的要求里没有提到去掉工具" if len(unasked) == len(c["removed"]) - else f"这一轮的要求里没有提到去掉 {'、'.join(unasked)}") - cost = ("没有绑定工具,它只能「假设」调用,查不了库" if not c["after"] - else f"{'、'.join(unasked)} 它就调不到了") + now = f" {'、'.join(c['after'])}" if c["after"] else "无" + said = ("本轮要求中没有提到移除工具" if len(unasked) == len(c["removed"]) + else f"本轮要求中没有提到移除 {'、'.join(unasked)}") + cost = ("没有绑定工具时,它无法查询数据库,只能假设调用结果" if not c["after"] + else f"{'、'.join(unasked)} 将无法调用") out.append({ "level": "warning", "node_id": c["node_id"], "edge_id": None, "code": "tools_dropped", "field": c["field"], - "message": f"{who}的工具从 {'、'.join(c['before'])} 变成了{now}。" - f"{said},确认一下是不是改漏了:{cost}", + "message": f"{who}的工具从 {'、'.join(c['before'])} 变为{now}。" + f"{said},请确认是否误删:{cost}", }) return out @@ -1583,7 +1598,7 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g yield f"data: {json.dumps(op, ensure_ascii=False)}\n\n" except Exception as e: # noqa: BLE001 reason, hint = explain_error(e) - yield _sse({"op": "error", "message": f"助手这一轮没跑完:{reason}", + yield _sse({"op": "error", "message": f"助手本轮未完成:{reason}", "hint": hint, "detail": raw_error(e)}) return @@ -1628,7 +1643,7 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g yield _sse(op) except Exception as e: # noqa: BLE001 - 修不成就照实交付,下面列出剩下的问题 yield _sse({"op": "check", "status": "error", - "message": f"自查修正没跑成:{explain_error(e)[0]}", "detail": raw_error(e)}) + "message": f"自查修正失败:{explain_error(e)[0]}", "detail": raw_error(e)}) break repaired = round_no remaining = _blocking_issues(nodes, edges, scope, sources=sources, baseline=baseline) @@ -1663,7 +1678,7 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g issues += [ {"level": "warning", "node_id": None, "edge_id": None, "code": "unknown_node_type", "type": t, - "message": f"模型写了一个不存在的节点类型「{t}」,这一步已跳过"} + "message": f"模型使用了不存在的节点类型「{t}」,已跳过这一步"} for t in dict.fromkeys(skipped_types) ] final = { @@ -1677,8 +1692,8 @@ async def generate_stream(payload: GenerateIn, session: AsyncSession = Depends(g "tool_changes": changes, } except Exception as e: # noqa: BLE001 - final = {"op": "error", "message": f"模型交回的工作流结构不对:{graph_error(e)}", - "hint": "再试一次,或者把需求说得更具体些", "detail": raw_error(e)} + final = {"op": "error", "message": f"模型返回的工作流结构有误:{graph_error(e)}", + "hint": "请重试,或把需求描述得更具体", "detail": raw_error(e)} yield f"data: {json.dumps(final, ensure_ascii=False)}\n\n" return StreamingResponse( @@ -1764,7 +1779,7 @@ async def assist_publish_fix( out: dict[str, Any] = {"accepted": False, "reason": None, "summary": "", "questions": [], "graph": graph, "ops": []} if not errors: - out["summary"] = "没有挡住发布的错误,不用交给 Copilot" + out["summary"] = "没有阻止发布的错误,无需交给助手" return out try: spec_ = await copilot_model_spec( @@ -1805,13 +1820,13 @@ async def assist_publish_fix( if _apply_op(nodes, edges, op): effective.append(op) except Exception as e: # noqa: BLE001 - 修不成就照实说,确定性修复的结果照样交给人 - out["summary"] = f"Copilot 这一轮没跑完:{explain_error(e)[0]}" + out["summary"] = f"助手本轮未完成:{explain_error(e)[0]}" return out out["summary"] = out["summary"] or plan if not effective: # 没动图:要么全是要人拿主意的问题,要么它没给出能用的修改。都不算「拒绝」 - out["summary"] = out["summary"] or ("Copilot 认为这些问题要你来拿主意" if out["questions"] - else "Copilot 这一轮没有给出修改") + out["summary"] = out["summary"] or ("助手认为这些问题需要由你决定" if out["questions"] + else "助手本轮没有给出修改") return out proposed = _proposed_graph(base, nodes, edges) @@ -1819,11 +1834,11 @@ async def assist_publish_fix( after = _blocking_issues(_nodes_by_id(proposed), proposed.get("edges") or [], sources=sources, baseline=baseline, level=level, defaults=proposed.get("defaults")) if reasons: - out["reason"] = "Copilot 的修改降低了要求,已作废:" + ";".join(reasons) + out["reason"] = "助手的修改降低了要求,已作废:" + ";".join(reasons) elif after is None: - out["reason"] = "Copilot 改完的图结构读不懂,已作废" + out["reason"] = "助手修改后的工作流结构无法解析,已作废" elif why := judge(errors, after): - out["reason"] = f"Copilot 的修改没有让图变得更好,已作废:{why}" + out["reason"] = f"助手的修改未能改善工作流,已作废:{why}" else: out.update(accepted=True, graph=proposed, ops=effective) return out @@ -1903,9 +1918,9 @@ def _kept_code(spec: GraphSpec) -> list[str]: """assist 之后仍然喂着口径卡的计算角色沙箱代码:不是纯算术、或者 Copilot 拿不准的,保留原样并警告。""" from app.engine.upgrade import compute_feeders - return [f"「{code.title}」(沙箱代码)没有改写成口径卡表达式,保留原样:口径卡" + return [f"「{code.title}」(沙箱代码)未改写为口径卡表达式,已保留原样:口径卡" + "、".join(f"「{c.title}」" for c in cards) - + "读到的数核对不了出处。它在取数的话,把 evidence_role 标成 source;在做计算的话,把计算写进口径卡" + + "读取的数字无法追溯出处。若该节点负责取数,请将「证据角色」设为「取数」;若负责计算,请把计算移到口径卡的表达式中" for code, cards in compute_feeders(spec)] @@ -1930,7 +1945,7 @@ async def assist_upgrade( "warnings": [], "graph": graph, "ops": []} feeders = compute_feeders(spec) if not feeders: - out["summary"] = "口径卡的输入都不来自做计算的沙箱代码,没有要交给 Copilot 改写的" + out["summary"] = "口径卡的输入均不来自负责计算的沙箱代码,无需交给助手改写" return out sources = await _sources(session, None) before_nodes = {str(n["id"]): n for n in copy.deepcopy(base.get("nodes") or []) if isinstance(n, dict)} @@ -1994,12 +2009,12 @@ async def assist_upgrade( break await collect(_repair_request(nodes, edges, fresh), first=False) except Exception as e: # noqa: BLE001 - 改不成就照实说,确定性改写的结果照样交给人 - out.update(ok=False, summary=f"Copilot 这一轮没跑完:{explain_error(e)[0]}") + out.update(ok=False, summary=f"助手本轮未完成:{explain_error(e)[0]}") return out out["summary"] = out["summary"] or plan if not effective: - out["summary"] = out["summary"] or ("Copilot 认为这些代码不是纯算术,都保留原样" if out["questions"] - else "Copilot 这一轮没有给出修改") + out["summary"] = out["summary"] or ("助手认为这些代码不是纯算术,均保留原样" if out["questions"] + else "助手本轮没有给出修改") return out proposed = _proposed_graph(base, nodes, edges) @@ -2007,11 +2022,11 @@ async def assist_upgrade( after = _blocking_issues(_nodes_by_id(proposed), proposed.get("edges") or [], sources=sources, baseline=baseline, level=level, defaults=proposed.get("defaults")) if reasons: - out["reason"] = "Copilot 的修改降低了要求,已作废:" + ";".join(reasons) + out["reason"] = "助手的修改降低了要求,已作废:" + ";".join(reasons) elif after is None: - out["reason"] = "Copilot 改完的图结构读不懂,已作废" + out["reason"] = "助手修改后的工作流结构无法解析,已作废" elif why := worse(base_errors, after): - out["reason"] = f"Copilot 的修改让图变糟了,已作废:{why}" + out["reason"] = f"助手的修改未能改善工作流,已作废:{why}" else: out.update(accepted=True, graph=proposed, ops=effective, warnings=_kept_code(GraphSpec.model_validate(proposed))) out["ok"] = out["reason"] is None @@ -2064,7 +2079,7 @@ async def upgrade_evidence(payload: UpgradeIn, session: AsyncSession = Depends(g return {"graph": payload.graph, "changes": [], "ops": [], "notes": [], "applied": [], "rejected": [], "assist": None, "ok": False, "issues": [{"level": "error", "node_id": None, "edge_id": None, "field": None, "code": None, - "fix": None, "message": f"工作流的结构读不懂:{graph_error(e)}"}]} + "fix": None, "message": f"无法解析工作流结构:{graph_error(e)}"}]} out = upgrade_for_evidence(payload.graph, level=payload.level) out["graph"] = _placed(payload.graph, out["graph"]) out["assist"] = None @@ -2077,7 +2092,7 @@ async def upgrade_evidence(payload: UpgradeIn, session: AsyncSession = Depends(g from app.engine.upgrade import compute_feeders out["changes"] += _node_changes( - diff_changes(out["graph"], helped["graph"], fix_id="assist", label="Copilot 的修改")) + diff_changes(out["graph"], helped["graph"], fix_id="assist", label="助手的修改")) out["ops"] += helped["ops"] out["applied"].append("assist") out["graph"] = helped["graph"] @@ -2115,13 +2130,13 @@ async def extract_template( run = await session.get(Run, payload.run_id) if not run: - raise HTTPException(404, "这次运行的记录不存在,可能已经被删了") + raise HTTPException(404, "运行记录不存在,可能已被删除") # 没跑通的路径提出来是半截骨架:失败节点之后的步骤一步都不在里面, # 人拿去审改时却看不出它缺了什么 if run.status != "succeeded": raise HTTPException( - 409, "这次运行没有跑完(没有成功结束),提取出来的只是半截路径。" - "先让它跑成功一次,再从那次运行提取", + 409, "这次运行未成功结束,提取出的执行路径不完整。" + "请先让它成功运行一次,再从该次运行提取", ) if not run.graph.get("nodes"): raise HTTPException(400, "这次运行没有保存工作流快照,无法提取") @@ -2140,7 +2155,7 @@ async def extract_template( if e.type == "edge.taken" and e.node_id } if not executed: - raise HTTPException(400, "事件流里没有节点执行记录") + raise HTTPException(400, "这次运行没有节点执行记录") spec = GraphSpec.model_validate(run.graph) kept_nodes = [n for n in spec.nodes if n.id in executed] @@ -2169,8 +2184,8 @@ async def extract_template( ) graph = draft_spec.model_dump(mode="json") workflow = Workflow( - name=payload.name or f"{run.workflow_name or '探索'}·提取模板", - description=f"从运行 {run.id[:8]} 的实际执行路径提取({len(kept_nodes)} 节点),待人审后发布", + name=payload.name or f"{run.workflow_name or '探索'}(提取的模板)", + description=f"从运行 {run.id[:8]} 的实际执行路径提取({len(kept_nodes)} 个节点),经人工审核后发布", graph=graph, tags=["extracted"], status="draft", @@ -2180,7 +2195,7 @@ async def extract_template( session.add( WorkflowVersion( workflow_id=workflow.id, version=1, graph=graph, - graph_hash=graph_hash(graph), note=f"自运行 {run.id} 提取", + graph_hash=graph_hash(graph), note=f"从运行 {run.id} 提取", ) ) await session.commit() @@ -2298,7 +2313,7 @@ async def review_run( run = await session.get(Run, payload.run_id) if not run: - raise HTTPException(404, "这次运行的记录不存在,可能已经被删了") + raise HTTPException(404, "运行记录不存在,可能已被删除") rows = list((await session.execute( select(RunEvent).where(RunEvent.run_id == payload.run_id).order_by(RunEvent.seq) diff --git a/backend/app/api/datasources.py b/backend/app/api/datasources.py index be613f0f..24271c5a 100644 --- a/backend/app/api/datasources.py +++ b/backend/app/api/datasources.py @@ -14,7 +14,7 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.api import health -from app.core.errors import explain, first_line, raw +from app.core.errors import AUTH, NETWORK, TIMEOUT, classify, explain, first_line, raw from app.core.config import settings from app.core.crypto import encrypt, mask from app.data import introspect as introspect_mod @@ -138,7 +138,7 @@ def _probe_record(result: dict[str, Any]) -> dict[str, Any]: async def _get_or_404(session: AsyncSession, source_id: str) -> DataSource: row = await session.get(DataSource, source_id) if not row: - raise HTTPException(404, "这个数据源不存在,可能已经被删了") + raise HTTPException(404, "数据源不存在,可能已被删除") return row @@ -151,15 +151,15 @@ async def list_sources(session: AsyncSession = Depends(get_session)) -> list[Dat #: 每种库都有的「查询时限」。数据库按它自己停下语句,不只是后端不再等 _TIMEOUT_FIELD = { "key": QUERY_TIMEOUT_OPTION, "label": "查询时限(秒)", "placeholder": "30", - "help": f"一条查询最多跑多久,到点由数据库自己停下;留空是 30 秒,最多 {MAX_QUERY_TIMEOUT_S} 秒", + "help": f"单条查询的最长执行时间,超时后由数据库终止;留空为 30 秒,最多 {MAX_QUERY_TIMEOUT_S} 秒", } #: 证据面板展示原始行时遮掉的列。每种库都有:遮罩只看查询结果的列名,和方言无关 _MASK_FIELD = { "key": MASK_COLUMNS_OPTION, "label": "遮罩的列", "placeholder": "phone, email", - "help": "证据面板展示查询结果的原始行时,这些列的值一律显示成「已遮罩」。在有身份体系之前," - "遮罩只减少暴露,不是安全边界:完整快照仍能按工件取到,SQL 里给列起别名也能绕开", + "help": "证据面板展示查询结果的原始行时,这些列显示为「已遮罩」。" + "遮罩只减少暴露,不是安全边界:完整快照仍可通过工件获取,SQL 中给列起别名也可绕过", } @@ -181,28 +181,26 @@ async def list_kinds() -> dict[str, Any]: "kinds": [ {"value": "mysql", "label": "MySQL / MariaDB", "default_port": 3306, "needs": ["host", "database", "username", "password"], - "hint": "字符集默认 utf8mb4,要换就在「高级连接参数」里加 charset", + "hint": "字符集默认为 utf8mb4;如需更改,请在「高级连接参数」中添加 charset", "advanced": [{"key": "charset", "label": "字符集", "placeholder": "utf8mb4"}, _TIMEOUT_FIELD, _MASK_FIELD]}, {"value": "postgres", "label": "PostgreSQL", "default_port": 5432, "needs": ["host", "database", "username", "password"], - "hint": "「schema」留空就用 public", + "hint": "「schema」留空时使用 public", "advanced": [_TIMEOUT_FIELD, _MASK_FIELD]}, {"value": "oracle", "label": "Oracle", "default_port": 1521, "needs": ["host", "username", "password"], - "hint": "service_name 和 SID 二选一:一般填 service_name,老库只给了 SID 就切到 SID。" - "驱动走 thin 模式,不需要装 Instant Client。" - "只读账号名下通常没有对象——数据在别的 schema 里," - "把它填进「schema」(如 ANALYTICS),否则探查结果是空的", + "hint": "service_name 与 SID 二选一,通常填写 service_name;无需安装 Instant Client。" + "若只读账号名下没有对象,请在「schema」中填写数据所在的 schema(如 ANALYTICS)", "advanced": [ {"key": "service_name", "label": "service_name", "placeholder": "ORCLPDB1", - "help": "和 SID 二选一"}, - {"key": "sid", "label": "SID", "placeholder": "ORCL", "help": "和 service_name 二选一"}, + "help": "与 SID 二选一"}, + {"key": "sid", "label": "SID", "placeholder": "ORCL", "help": "与 service_name 二选一"}, _TIMEOUT_FIELD, _MASK_FIELD, ]}, {"value": "sqlite", "label": "SQLite(文件)", "default_port": None, - "needs": ["database"], "hint": "「数据库文件路径」填 .db 文件的绝对路径", + "needs": ["database"], "hint": "「数据库文件路径」请填写 .db 文件的绝对路径", "advanced": [_TIMEOUT_FIELD, _MASK_FIELD]}, ], "supported": list(SUPPORTED_KINDS), @@ -244,12 +242,12 @@ async def create_source( payload: DataSourceIn, session: AsyncSession = Depends(get_session) ) -> DataSourceOut: if payload.kind not in SUPPORTED_KINDS: - raise HTTPException(400, f"不支持「{payload.kind}」这种数据库,支持:{'、'.join(SUPPORTED_KINDS)}") + raise HTTPException(400, f"不支持「{payload.kind}」类型的数据库,目前支持:{'、'.join(SUPPORTED_KINDS)}") exists = (await session.execute( select(DataSource).where(DataSource.name == payload.name) )).scalar_one_or_none() if exists: - raise HTTPException(409, f"已经有叫「{payload.name}」的数据源了,换个标识") + raise HTTPException(409, f"已存在名为「{payload.name}」的数据源,请换一个标识") _refuse_bad_options(payload.options) row = DataSource( @@ -305,34 +303,44 @@ async def delete_source(source_id: str, session: AsyncSession = Depends(get_sess _TEST_TIMEOUT = 15 +_WRONG_PASSWORD = ("用户名或密码错误", "请核对「用户名」和「密码」;编辑时密码留空表示沿用已保存的密码") +_CHECK_HOST = "请检查「主机」和「端口」;内网数据库请确认本机可以访问(防火墙、VPN)" + + def _explain_connect(e: BaseException, kind: str) -> tuple[str, str]: """连库失败的常见原因。驱动的原文九成能定位问题,但得先翻译成表单上的说法。""" low = str(e).lower() if any(s in low for s in ("password authentication failed", "access denied", "ora-01017", "invalid username/password", "(1045")): - return "账号或密码不对", "核对「用户名」和「密码」;编辑时密码留空表示沿用已保存的那个" + return _WRONG_PASSWORD if "ora-12514" in low: - return "Oracle 不认识这个 service_name", "核对 service_name;老库可能只给了 SID,切到 SID 再试" + return "Oracle 无法识别该 service_name", "请核对 service_name;部分旧版数据库只提供 SID,可改用 SID 后重试" if "ora-12505" in low: - return "Oracle 不认识这个 SID", "核对 SID,或者改用 service_name" + return "Oracle 无法识别该 SID", "请核对 SID,或改用 service_name" if "service_name 或 sid" in low: - return "没填 service_name 或 SID", "在「service_name」一栏填上,或者切到 SID" + return "未填写 service_name 或 SID", "请在「service_name」中填写,或改用 SID" if "unknown database" in low or "(1049" in low or ( "does not exist" in low and "database" in low ): - return "服务器上没有这个库", "核对「数据库」一栏" + return "服务器上不存在该数据库", "请核对「数据库」一栏" if "unable to open database file" in low: - return "打不开这个数据库文件", "核对路径是不是绝对路径、文件在不在,以及后端进程有没有读权限" + return "无法打开该数据库文件", "请确认路径是绝对路径、文件存在,且服务端进程有读取权限" if "file is not a database" in low: - return "这个文件不是 SQLite 数据库", "核对路径指的是不是 .db 文件" + return "该文件不是 SQLite 数据库", "请确认路径指向的是 .db 文件" if "no module named" in low: - return "后端没装这种数据库的驱动", "pip install 'agentlab-backend[db]' 之后重启后端" + return "服务端未安装该数据库的驱动", "请执行 pip install 'agentlab-backend[db]',然后重启服务端" + # 下面按错误类别换成数据库的说法:通用的那几句说的是 API(API Key、Base URL),这里是数据库。 + # 按类别判断,不比较 explain 的文字——那句话改一个字,这里就再也对不上 + category = classify(e) + if category == AUTH: + return _WRONG_PASSWORD + if category == NETWORK: + return "网络不通,或数据库服务未启动", _CHECK_HOST + if category == TIMEOUT: + return "数据库长时间没有响应", _CHECK_HOST reason, hint = explain(e) - if reason in ("等了太久没有响应", "连不上对方的服务"): - # 通用那句说的是 API,这里是数据库:多半是主机、端口或者网络不通 - hint = "核对「主机」和「端口」;内网库要确认这台机器访问得到它(防火墙、VPN)" - elif kind == "sqlite" and not hint: - hint = "核对数据库文件的路径" + if kind == "sqlite" and not hint: + hint = "请检查数据库文件的路径" return reason, hint @@ -356,11 +364,11 @@ def _missing_sqlite_file(source: Any) -> tuple[str, str, str] | None: return None path = source.database or "" if not path.strip(): - return "没填数据库文件路径", "在「数据库文件路径」里填 .db 文件的绝对路径", "database 为空" + return "未填写数据库文件路径", "请在「数据库文件路径」中填写 .db 文件的绝对路径", "database 为空" if path == ":memory:" or Path(path).is_file(): return None - return ("打不开这个数据库文件", - "这个路径上没有文件。核对路径是不是绝对路径、文件在不在(~ 不会被展开)", + return ("无法打开该数据库文件", + "该路径下没有文件。请确认路径是绝对路径且文件存在(~ 不会被展开)", f"文件不存在:{path}") @@ -378,7 +386,7 @@ async def _probe(source: Any, *, cached: bool) -> dict[str, Any]: missing = _missing_sqlite_file(source) if missing: reason, hint, detail = missing - return {"ok": False, "error": f"连不上:{reason}", "hint": hint, "detail": detail, + return {"ok": False, "error": f"连接失败:{reason}", "hint": hint, "detail": detail, "elapsed_ms": 0, "url": _safe_url(source)} engine = None try: @@ -400,7 +408,7 @@ async def _probe(source: Any, *, cached: bool) -> dict[str, Any]: reason, hint = _explain_connect(e, (source.kind or "").lower()) return { "ok": False, - "error": f"连不上:{reason}", + "error": f"连接失败:{reason}", "hint": hint, "detail": raw(e), "elapsed_ms": int((time.perf_counter() - started) * 1000), @@ -454,8 +462,8 @@ async def test_draft( 接内网 Oracle 这类填错一个字段就连不上的东西,来回四五趟。 """ if payload.kind not in SUPPORTED_KINDS: - return {"ok": False, "error": f"不支持「{payload.kind}」这种数据库", - "hint": f"支持:{'、'.join(SUPPORTED_KINDS)}", "detail": "", "elapsed_ms": 0, "url": ""} + return {"ok": False, "error": f"不支持「{payload.kind}」类型的数据库", + "hint": f"目前支持:{'、'.join(SUPPORTED_KINDS)}", "detail": "", "elapsed_ms": 0, "url": ""} saved = await session.get(DataSource, payload.id) if payload.id else None draft = _draft_source(payload, saved) result = await _probe(draft, cached=False) @@ -586,7 +594,7 @@ async def upload_table( if not _re.match(_NAME_PATTERN, name or ""): raise HTTPException( - 400, "名字只能用小写字母开头的字母数字下划线——它会成为工具名的一部分" + 400, "名称必须以小写字母开头,只能包含字母、数字和下划线(名称会成为工具名的一部分)" ) # 边读边数,超了立刻停。和知识库上传同一套:那个检查拦的是"入库", @@ -597,7 +605,7 @@ async def upload_table( while piece := await file.read(1024 * 1024): total += len(piece) if total > limit: - raise HTTPException(413, f"文件超过 {settings.max_upload_mb}MB") + raise HTTPException(413, f"文件超过 {settings.max_upload_mb} MB") pieces.append(piece) raw = b"".join(pieces) @@ -612,7 +620,7 @@ async def upload_table( )).scalar_one_or_none() if existing and existing.kind != "sqlite": raise HTTPException( - 409, f"已经有一个叫 {name} 的数据源了,而且它不是上传来的表格。换个名字。" + 409, f"已存在名为「{name}」的数据源(非上传表格),请换一个名称" ) try: @@ -622,7 +630,7 @@ async def upload_table( except Exception as e: # noqa: BLE001 raise HTTPException( 400, f"导入失败:{first_line(e) if isinstance(e, ValueError) else explain(e)[0]}。" - "确认文件是 Excel 或 CSV、没有加密,表头行号填得对", + "请确认文件是未加密的 Excel 或 CSV,且表头行号填写正确", ) from e row = existing diff --git a/backend/app/api/evidence.py b/backend/app/api/evidence.py index 9efce4c9..9894614e 100644 --- a/backend/app/api/evidence.py +++ b/backend/app/api/evidence.py @@ -82,24 +82,24 @@ SEGMENT_NOT_FOUND = "evidence_segment_not_found" DOC_MISSING = "evidence_doc_missing" DOC_TAMPERED = "evidence_doc_tampered" -LEGACY_NOTE = "旧版出具:按数值匹配,不是显式引用。同一个值对得上好几个指标时,出处不唯一" -NONE_NOTE = "这次运行没有报告文档,也没有出具契约,没有可以展示的证据" -NO_DOC_NOTE = "这次运行的出具契约用的是引用模式,但报告没有产出可以核对的文档" +LEGACY_NOTE = "旧版出具:按数值匹配,不是显式引用。同一个值与多个指标相符时,出处不唯一" +NONE_NOTE = "本次运行没有报告文档,也没有出具契约,没有可展示的证据" +NO_DOC_NOTE = "本次运行的出具契约采用引用模式核对,但报告没有产出可核对的文档" MASKED = "已遮罩" -MASK_NOTE = "这些列在数据源里设了遮罩,面板上不显示原值。在有身份体系之前,遮罩只减少暴露,不是安全边界" +MASK_NOTE = "这些列在数据源中设置了遮罩,面板上不显示原值。遮罩只减少暴露,不是安全边界" #: 查询条目的数据源现在找不到了(改名或删掉了):只能按快照里记下的、查询当时的遮罩来遮 -SOURCE_GONE = "数据源「{source}」现在找不到了(改名或删掉了),按查询当时记下的遮罩处理" +SOURCE_GONE = "数据源「{source}」已不存在(可能已改名或删除),按查询时记录的遮罩处理" #: 查询步骤给被引用的行前后各带几行 WINDOW = 2 #: 一个查询步骤最多给多少行:数组字段引用了一大段行时,窗口不能把整份快照搬过来 MAX_WINDOW_ROWS = 50 -UNSEALED_QUERY = "这份查询快照不在封存范围内的任何事件里(没有哪次查询在封存前交回过它),不能当证据展示" -TAMPERED_QUERY = "查询快照和它的哈希对不上,疑似被改过,不展示其中的行" -MISSING_QUERY = "查询快照在工件库里取不回来" -UNSEALED_RETRIEVAL = "这份检索快照不在封存范围内的任何事件里(没有哪次检索在封存前交回过它),不能当证据展示" -TAMPERED_RETRIEVAL = "检索快照和它的哈希对不上,疑似被改过,不展示原文" -MISSING_RETRIEVAL = "检索快照在工件库里取不回来,或者里面没有这条命中" +UNSEALED_QUERY = "这份查询快照不属于封存范围内的任何事件(封存前没有任何查询返回过它),不能作为证据展示" +TAMPERED_QUERY = "查询快照与哈希不一致,疑似被修改,不展示其中的行" +MISSING_QUERY = "无法读取查询快照" +UNSEALED_RETRIEVAL = "这份检索快照不属于封存范围内的任何事件(封存前没有任何检索返回过它),不能作为证据展示" +TAMPERED_RETRIEVAL = "检索快照与哈希不一致,疑似被修改,不展示原文" +MISSING_RETRIEVAL = "无法读取检索快照,或其中没有这条命中" # -------------------------------------------------------------------------- @@ -554,7 +554,7 @@ def _metric_sources(sealed: _Sealed, nodes: list[Any]) -> dict[str, list[dict[st #: 只缓存封存完好的运行:还在跑、停在审批的运行事件还会变,封存链断了的运行不该被一份旧结果盖住 GUESS_CACHE_SIZE = 64 _guess_cache: OrderedDict[tuple[Any, ...], dict[str, Any] | None] = OrderedDict() -NO_CANDIDATE = "旧答案里的这个数,在这次运行封存的查询结果和口径卡里没有找到相同的值" +NO_CANDIDATE = "旧版答案中的这个数字,在本次运行封存的查询结果和口径卡中没有找到相同的值" async def _mask_fingerprint() -> dict[str, list[str]]: @@ -672,15 +672,15 @@ async def evidence_segment(run_id: str, segment_id: str, report: str | None = No sealed = await _sealed(run_id) reports = _reports(sealed) if not reports: - raise CodedHTTPException(404, "这次运行没有封存的报告文档,没有可以点开的片段", REPORT_NOT_FOUND) + raise CodedHTTPException(404, "本次运行没有封存的报告文档,没有可查看的片段", REPORT_NOT_FOUND) chosen = _choose(reports, report, sealed) if chosen.hash_ok is False: - raise CodedHTTPException(409, "报告文档和它的哈希对不上,疑似被改过,不能再当证据展示", DOC_TAMPERED) + raise CodedHTTPException(409, "报告文档与哈希不一致,疑似被修改,不能作为证据展示", DOC_TAMPERED) if chosen.doc is None: - raise CodedHTTPException(404, "报告文档在工件库里取不回来", DOC_MISSING) + raise CodedHTTPException(404, "无法读取报告文档", DOC_MISSING) found = find_segment(chosen.doc, segment_id) if found is None: - raise CodedHTTPException(404, f"报告里没有片段 {segment_id}", SEGMENT_NOT_FOUND) + raise CodedHTTPException(404, "报告中没有这个片段", SEGMENT_NOT_FOUND) block, unit, seg = found doc = chosen.doc @@ -713,7 +713,7 @@ def _choose(reports: list[_Report], wanted: str | None, sealed: _Sealed) -> _Rep if wanted: chosen = next((r for r in reports if r.node_id == wanted), None) if chosen is None: - raise CodedHTTPException(404, f"这次运行里没有报告节点 {wanted} 的文档", REPORT_NOT_FOUND) + raise CodedHTTPException(404, "本次运行中没有所选报告撰写节点的文档", REPORT_NOT_FOUND) return chosen primary = next(iter(_output_evidence(sealed)), {}) return next((r for r in reports if r.node_id == primary.get("report_node")), reports[0]) @@ -1150,35 +1150,35 @@ def _note(seg: dict[str, Any], unit: dict[str, Any]) -> str: issue = seg.get("issue") cite = seg.get("cite") or {} if issue == "uncited_number": - return "这个数字没有出处:写作者直接写了数字,没有用引用标记,系统没法核对它" + return "这个数字没有出处:报告中直接写出了数字,而不是引用标记,系统无法核对" if issue == "unresolved_ref": - return f"引用解析不了:{cite.get('reason') or '证据目录里没有它'}" + return f"引用无法解析:{cite.get('reason') or '本次运行的证据中没有它'}" if issue == "unknown_entity": return UNKNOWN_ENTITY_REASON if issue == "unverified_entity": - return f"核对不了:{UNVERIFIED_ENTITY_REASON}" + return f"无法核实:{UNVERIFIED_ENTITY_REASON}" if seg.get("state") == "deterministic" and seg.get("kind") == "entity": - lead = "系统在正文里认出的表名、字段名:" if seg.get("auto") else "" - return (f"{lead}这个名字在本次运行冻结的表结构快照、查询用到的表或查询结果列里确实存在。" - "只核对它存在、这次用过,不核对它的业务含义") + lead = "系统在正文中识别出的表名、字段名:" if seg.get("auto") else "" + return (f"{lead}这个名字在本次运行冻结的表结构快照、查询用到的表或查询结果列中确实存在。" + "仅核对它存在且本次用到,不核对其业务含义") if seg.get("state") == "deterministic" and seg.get("kind") == "quote": - return "这段原话在知识库检索命中的片段里逐字出现(空白归一化后比对),由系统核对过" + return "这段原话在知识库检索命中的片段中逐字出现(空白归一化后比对),已由系统核对" if seg.get("state") == "deterministic" and cite.get("kind") == "cell": - return "这个值由系统从查询快照里取出、按固定规则渲染,没有经过模型转写" + return "该值由系统从查询快照中取出、按固定规则显示,未经模型转写" if seg.get("state") == "deterministic": - return "数字由系统从证据里取出、按口径卡的格式渲染,没有经过模型转写" + return "数字由系统从证据中取出、按口径卡的格式显示,未经模型转写" kind = seg.get("kind") if kind == "structural": - return "这是 Markdown 的版式符号" + return "这是排版符号" if unit.get("kind") == "heading": return "这是标题" if unit.get("kind") == "connective": - return "这是连接性文字,不陈述数据事实,所以不需要证据" + return "这是连接性文字,不陈述数据事实,无需证据" cites = [str(c) for c in unit.get("cites") or []] if cites: - return (f"这是结论句里的文字,这句挂了依据:{'、'.join(cites[:4])}{' 等' if len(cites) > 4 else ''}。" - "依据支不支持这句话,系统核对不了,只能由模型判断(模型的判断不是确定性的)") - return "这是结论句里的文字,这句没有挂依据。句子本身有没有依据,系统核对不了,只能由模型判断(模型的判断不是确定性的)" + return (f"这是结论句中的文字,这句附有依据:{'、'.join(cites[:4])}{' 等' if len(cites) > 4 else ''}。" + "依据是否支持这句话,系统无法确定性核对,只能由模型判断(模型的判断不是确定性的)") + return "这是结论句中的文字,这句没有附依据。句子是否有依据,系统无法核对,只能由模型判断(模型的判断不是确定性的)" # -------------------------------------------------------------------------- @@ -1195,22 +1195,24 @@ JUDGE_MAX_UNITS = 200 #: 跑完了的几种终态。还在跑、停在审批、正在接着跑的运行,追加的判定会被封进下一次的清单,不判 _TERMINAL = ("succeeded", "failed", "cancelled") -FORMAL_JUDGED = "正式运行的裁判在节点内完成(claims: judge),判定随报告文档一起封存,不能再按需裁判" -UNSEALED_JUDGE = "运行还没跑完封存(还在跑、停在人工审批,或者正在接着跑),跑完再请模型判断" -LEGACY_JUDGE = "这次运行发起于证据台账上线之前,不支持按需裁判" -BROKEN_JUDGE = "封存核对没通过:封存之后有事件被改过、删过或插过,报告和证据都不能再当真,不再请模型判断" -JUDGED_ALREADY = "这句已经判过了" +FORMAL_JUDGED = "正式运行的结论句已在报告撰写节点内完成裁判,结果随报告一起封存,不能再按需裁判" +UNSEALED_JUDGE = "运行尚未结束并封存(仍在运行、停在人工审批或正在继续运行),请在运行结束后再请模型裁判" +LEGACY_JUDGE = "这次运行发起时系统尚未记录证据,不支持按需裁判" +BROKEN_JUDGE = "封存核对未通过:封存后有事件被修改、删除或插入,报告和证据已不可信,无法再请模型裁判" +JUDGED_ALREADY = "这句已裁判" #: 裁判期间运行被接着跑了(失败的运行可以继续),或者接着跑完重新封存了:判定照样交回,不记进运行记录 -NOT_RECORDED = "运行已经接着跑了,这次的判定没有记进运行记录(只在这里看得到,刷新就没了);等它跑完封存,再请模型判断" -NOT_A_CLAIM = "不是结论句(标题、连接性的话、表格单元格、代码),不需要模型判断" -BAD_UNITS = f'units 要写成句子编号的列表,比如 {{"units": ["u4"]}},一次最多 {JUDGE_MAX_UNITS} 句;report 要写报告节点的 id' +NOT_RECORDED = "运行已继续执行,本次裁判结果未写入运行记录,刷新后将不再显示。请在运行结束并封存后重新裁判" +NOT_A_CLAIM = "不是结论句(标题、连接性文字、表格单元格或代码),无需模型裁判" +BAD_UNITS = (f'请求格式有误:units 应为句子编号列表,例如 {{"units": ["u4"]}},一次最多 {JUDGE_MAX_UNITS} 句;' + "report 应为报告撰写节点的 ID") #: 触顶时告诉人怎么调:设置页「证据裁判」一组的各项上限都能调高,也都能设成不限 JUDGE_ADJUST = { - "max_cost_usd": "到设置 → 证据裁判里调高「每次点击」的金额上限,或者设成不限", - "daily_max_usd": "今天的裁判花费到了全局每日上限:到设置 → 证据裁判里调高「每日」上限或者设成不限,也可以明天再判", - "max_claims": "一次最多判这么多句:分几次点,或者到设置 → 证据裁判里调高「每份报告的句数」" - "(报告节点上写了 judge.max_claims 的按节点,写 null 是不限)", - "timeout_s": "裁判超时了:到设置 → 证据裁判里调高「时长」上限或者设成不限,再点一次", + "max_cost_usd": "请前往「设置 → 偏好设置 → 证据裁判」调高「每次点击的金额上限」,或设为不限", + "daily_max_usd": "今日裁判费用已达每日上限:请前往「设置 → 偏好设置 → 证据裁判」调高「每日金额上限」或设为不限," + "也可次日再裁判", + "max_claims": "单次裁判的句数已达上限:请分几次点击,或前往「设置 → 偏好设置 → 证据裁判」调高「每份报告最多裁判句数」" + "(报告撰写节点的「结论句裁判」中已设置的,以节点为准)", + "timeout_s": "裁判超时:请前往「设置 → 偏好设置 → 证据裁判」调高「每份报告的时长上限」或设为不限,然后再次点击", } @@ -1263,7 +1265,7 @@ def _on_demand(sealed: _Sealed, doc: dict[str, Any], uid: str, verdict: dict[str if not sealed.ledger_on: return no("legacy", LEGACY_JUDGE) if not candidates(doc, [uid]): - return no("not_a_claim", NOT_A_CLAIM) + return no("not_a_claim", f"这句{NOT_A_CLAIM}") if isinstance(verdict, dict) and verdict.get("status") in JUDGED: return no("judged", JUDGED_ALREADY) if not sealed.sealed or sealed.status not in _TERMINAL: @@ -1357,9 +1359,9 @@ async def judge_units(run_id: str, payload: Any = Body(None), report: str | None raise CodedHTTPException(404, "这次运行没有封存的报告文档,没有可以判断的句子", REPORT_NOT_FOUND) chosen = _choose(reports, wanted, sealed) if chosen.hash_ok is False: - raise CodedHTTPException(409, "报告文档和它的哈希对不上,疑似被改过,不能再当证据展示", DOC_TAMPERED) + raise CodedHTTPException(409, "报告文档与哈希不一致,疑似被修改,不能作为证据展示", DOC_TAMPERED) if chosen.doc is None: - raise CodedHTTPException(404, "报告文档在工件库里取不回来", DOC_MISSING) + raise CodedHTTPException(404, "无法读取报告文档", DOC_MISSING) return await _judge_now(sealed, chosen, units) @@ -1421,14 +1423,14 @@ def _judge_message(outcome: dict[str, Any] | None, budget: Any, skipped: dict[st if outcome and outcome["limits_hit"]: labels = "、".join(_limit_label(r, budget, click=True) for r in outcome["limits_hit"]) n = sum(outcome["unjudged"].get(r, 0) for r in outcome["limits_hit"]) - return f"已到上限({labels}):{n} 句没判,记为未裁判;已判的保留" + return f"已达上限({labels}):{n} 句未裁判,已裁判的结果保留" if outcome and outcome["gaps"]: - return "裁判没跑完:" + ";".join(outcome["gaps"]) + return "结论句裁判未完成:" + ";".join(outcome["gaps"]) parts = [] if others := [u for u, why in skipped.items() if why == "not_a_claim"]: - parts.append(f"{'、'.join(others)} {NOT_A_CLAIM}") + parts.append(f"所选句子中有 {len(others)} 句{NOT_A_CLAIM}") if missing := [u for u, why in skipped.items() if why == "not_found"]: - parts.append(f"报告里没有 {'、'.join(missing)}") + parts.append(f"报告中没有所选的 {len(missing)} 句") return ";".join(parts) or None @@ -1484,26 +1486,25 @@ async def _append_judged(sealed: _Sealed, report: _Report, units: list[str], AUDIT_SCHEMA = "agentlab.evidence.audit/1" BAD_FORMAT = "evidence_bad_format" BAD_GROUP = "evidence_bad_group" -#: 分组的顺序固定:有出处 / 无证据 / 可疑实体 / 旧运行猜测 -GROUPS = (("cited", "有出处"), ("none", "无证据"), ("suspicious", "可疑实体"), ("candidate", "旧运行猜测")) +#: 分组的顺序固定:有出处 / 无证据 / 可疑名称 / 按数值猜测(叫法同前端 lib/terms.ts 的 EVIDENCE_AUDIT_TEXT.groups) +GROUPS = (("cited", "有出处"), ("none", "无证据"), ("suspicious", "可疑名称"), ("candidate", "按数值猜测")) #: 文档本身对不上的违规:不管落在哪个片段上都单独列一行,不能被那个片段「有出处」的行盖住 _INTEGRITY = frozenset({"bad_schema", "segment_mismatch", "structural_text", "render_mismatch", "eid_mismatch", "state_mismatch"}) -UNCITED_CLAIM = "这句结论没有挂依据(没有引用标记,也没有 [[see:]])" -UNCITED_CLAIM_COUNTED = "这句结论没有挂依据:这份报告要求结论句挂依据(claims: require_citation),出具时计入缺口" -UNCITED_CLAIM_WITHHELD = "这句结论没有挂依据:出具契约要求结论句挂依据,没挂的按契约不予出具(on_uncited: withhold)" -UNCITED_CLAIM_REQUIRED = ("这句结论没有挂依据:这份报告要求结论句挂依据(claims: require_citation),不过没有出具契约" - "按它判档(没配契约,或者还没到出具那一步)") +UNCITED_CLAIM = "这句结论没有附依据(既没有引用,也没有注明依据)" +UNCITED_CLAIM_COUNTED = "这句结论没有附依据。本报告要求结论句附依据,出具时计入缺口" +UNCITED_CLAIM_WITHHELD = "这句结论没有附依据,按出具契约不予出具" +UNCITED_CLAIM_REQUIRED = ("这句结论没有附依据。本报告要求结论句附依据,但目前没有出具契约据此判档" + "(未配置契约,或尚未到出具步骤)") #: claims: judge 在挂依据这件事上和 require_citation 一样严(出口按 on_uncited 计入缺口) -UNCITED_CLAIM_JUDGED = ("这句结论没有挂依据:这份报告的结论句由模型裁判(claims: judge),挂依据的要求和 " - "require_citation 一样,出具时计入缺口") -UNCITED_CLAIM_JUDGE_REQUIRED = ("这句结论没有挂依据:这份报告的结论句由模型裁判(claims: judge),要求结论句挂依据," - "不过没有出具契约按它判档(没配契约,或者还没到出具那一步)") -LEGACY_UNMATCHED = "旧版出具里这个数字对不上任何指标" +UNCITED_CLAIM_JUDGED = "这句结论没有附依据。本报告的结论句由模型裁判,同样要求附依据,出具时计入缺口" +UNCITED_CLAIM_JUDGE_REQUIRED = ("这句结论没有附依据。本报告的结论句由模型裁判,同样要求附依据,但目前没有出具契约" + "据此判档(未配置契约,或尚未到出具步骤)") +LEGACY_UNMATCHED = "旧版出具中这个数字与任何指标都不相符" #: CSV 的列:(表头, 行里的键) CSV_COLUMNS = ( - ("分组", "group"), ("报告节点", "report"), ("成果字段", "field"), ("片段", "segment"), ("句子编号", "unit"), + ("分组", "group"), ("报告节点", "report"), ("成果字段", "field"), ("片段编号", "segment"), ("句子编号", "unit"), ("种类", "kind"), ("原文", "text"), ("状态", "state"), ("问题", "issue"), ("引用", "ref"), ("证据", "evidence"), ("证据种类", "evidence_kind"), ("证据编号", "eid"), ("工件", "artifact"), ("来源节点", "node_id"), ("已封存", "sealed"), ("句子", "sentence"), ("说明", "note"), @@ -1511,16 +1512,16 @@ CSV_COLUMNS = ( ("封存核对", "seal"), ) SEAL_OK = "封存核对通过(封存于第 {seq} 条事件)" -SEAL_BROKEN = "封存核对没通过:封存之后有事件被改过、删过或插过" -SEAL_NONE = "未封存:运行还没跑完,或者停在人工审批" +SEAL_BROKEN = "封存核对未通过:封存后有事件被修改、删除或插入" +SEAL_NONE = "未封存:运行尚未结束,或正停在人工审批" _CSV_LABELS: dict[str, dict[Any, str]] = { "group": dict(GROUPS), "kind": {"number": "数字", "value": "值", "entity": "表名、字段名", "quote": "引文", "claim": "结论句", "violation": "违规"}, "state": {"deterministic": "有出处", "none": "无证据", "candidate": "候选"}, - "issue": {"uncited_number": "没有出处的数字", "unresolved_ref": "引用解析不了", "unknown_entity": "可能是编造的名字", - "unverified_entity": "核对不了", "uncited_claim": "结论句没挂依据", "no_candidate": "没找到候选", - **{code: "文档对不上" for code in _INTEGRITY}}, + "issue": {"uncited_number": "没有出处的数字", "unresolved_ref": "引用无法解析", "unknown_entity": "疑似不存在的名称", + "unverified_entity": "无法核实", "uncited_claim": "结论句未附依据", "no_candidate": "未找到候选", + **{code: "文档不一致" for code in _INTEGRITY}}, "evidence_kind": {"metric": "口径卡指标", "cell": "查询单元格", "input": "运行输入", "table": "表", "column": "字段", "quote": "知识库原话", "query": "查询结果"}, "sealed": {True: "是", False: "否", None: "—"}, @@ -1541,7 +1542,7 @@ async def evidence_audit(run_id: str, fmt: str | None = Query(None, alias="forma """ wanted = _wanted_groups(groups) if fmt not in (None, "", "json", "csv"): - raise CodedHTTPException(422, f"导出格式只能是 json 或 csv,写的是 {fmt!r}", BAD_FORMAT) + raise CodedHTTPException(422, f"导出格式只能是 json 或 csv,当前为「{fmt}」", BAD_FORMAT) sealed = await _sealed(run_id) reports = _reports(sealed) mode, extra = await _mode_of(sealed, reports) @@ -1592,7 +1593,7 @@ def _wanted_groups(raw: str | None) -> set[str]: return set(known) picked = {part.strip() for part in raw.split(",") if part.strip()} if unknown := picked - set(known): - raise CodedHTTPException(422, f"分组只能是 {' / '.join(known)},写的是 {'、'.join(sorted(unknown))}", BAD_GROUP) + raise CodedHTTPException(422, f"分组只能是 {' / '.join(known)},当前为「{'、'.join(sorted(unknown))}」", BAD_GROUP) return picked diff --git a/backend/app/api/governance.py b/backend/app/api/governance.py index 1c584da0..8ae5f324 100644 --- a/backend/app/api/governance.py +++ b/backend/app/api/governance.py @@ -29,7 +29,7 @@ async def tool_usage( """ workflow = await session.get(Workflow, workflow_id) if not workflow: - raise HTTPException(404, "这个工作流不存在,可能已经被删了") + raise HTTPException(404, "工作流不存在,可能已被删除") spec = GraphSpec.model_validate(workflow.graph) # 各节点声明的白名单 @@ -83,7 +83,7 @@ async def tool_usage( "workflow_id": workflow_id, "runs_considered": len(run_ids), "nodes": report, - "hint": "授权了却很多轮都没用过的工具,是白名单在慢慢放宽的信号,考虑从节点里摘掉", + "hint": "授权后多次运行都未使用的工具说明授权范围偏宽,建议从节点中移除", } @@ -147,5 +147,5 @@ async def exploratory_clusters( return { "clusters": out, "considered": len(items), - "hint": "标为晋升候选的问题反复出现,考虑用「提取模板」把它固定成工作流里的一步", + "hint": "被标记为可固化的问题反复出现,建议用「提取模板」把它固定为工作流中的一步", } diff --git a/backend/app/api/health.py b/backend/app/api/health.py index 8df5c0a2..74a033c1 100644 --- a/backend/app/api/health.py +++ b/backend/app/api/health.py @@ -28,7 +28,7 @@ def record(ok: bool, latency_ms: int | None, error: str | None = None) -> dict[s "at": utcnow().isoformat(), "ok": bool(ok), "latency_ms": None if latency_ms is None else int(latency_ms), - "error": None if ok else (error or "连不上"), + "error": None if ok else (error or "无法连接"), } diff --git a/backend/app/api/knowledge.py b/backend/app/api/knowledge.py index 3a609877..a9dac9b2 100644 --- a/backend/app/api/knowledge.py +++ b/backend/app/api/knowledge.py @@ -61,7 +61,7 @@ class MemoryOut(BaseModel): def _content(text: str) -> str: """只有空白的内容和空串是一回事——存下去就是一条什么都召回不到的空记忆。""" if not text.strip(): - raise HTTPException(422, "记忆内容是空的:写上要记住的那句话再保存") + raise HTTPException(422, "记忆内容为空,请填写要记住的内容后再保存") return text @@ -149,7 +149,7 @@ async def update_memory( kind=payload.kind, importance=payload.importance, ) if item is None: - raise HTTPException(404, "这条记忆不存在,可能已经被删了") + raise HTTPException(404, "记忆不存在,可能已被删除") return (await _with_source(session, [item]))[0] @@ -170,7 +170,7 @@ async def delete_memory( memory_id: str, session: AsyncSession = Depends(get_session) ) -> None: if not await store.forget(session, memory_id): - raise HTTPException(404, "这条记忆不存在,可能已经被删了") + raise HTTPException(404, "记忆不存在,可能已被删除") @memory_router.delete("/scope/{scope}") @@ -261,7 +261,7 @@ async def upload( while piece := await file.read(1024 * 1024): total += len(piece) if total > limit: - raise HTTPException(413, f"文件超过 {settings.max_upload_mb}MB") + raise HTTPException(413, f"文件超过 {settings.max_upload_mb} MB") chunks.append(piece) raw = b"".join(chunks) @@ -307,7 +307,7 @@ async def _process_in_background(doc_id: str) -> None: if doc: reason, hint = explain(e) doc.status = "failed" - doc.error = (f"切块或算向量时出错:{reason}" + (f"。{hint}" if hint else ""))[:500] + doc.error = (f"文档分块或生成向量时出错:{reason}" + (f"。{hint}" if hint else ""))[:500] await session.commit() @@ -428,7 +428,7 @@ async def probe_embedding(base_url: str) -> dict[str, Any]: data = (await client.get(url)).json() except Exception as e: # noqa: BLE001 reason, hint = explain(e) - raise HTTPException(400, f"问不到 {url} 上有哪些模型:{reason}" + (f"。{hint}" if hint else "")) from e + raise HTTPException(400, f"无法获取 {url} 上的模型列表:{reason}" + (f"。{hint}" if hint else "")) from e models = [m.get("id", "") for m in (data.get("data") or []) if m.get("id")] return {"base_url": base_url, "models": models} @@ -496,7 +496,7 @@ async def _run_reindex(job: _ReindexJob) -> None: except Exception as e: # noqa: BLE001 - 失败要落到任务状态上,不能只进日志 logger.warning("重建索引失败:%s", raw(e)) reason, hint = explain(e) - job.state, job.error, job.hint = "failed", f"重建索引没做完:{reason}", hint or None + job.state, job.error, job.hint = "failed", f"重建索引未完成:{reason}", hint or None finally: job.finished_at = utcnow() @@ -535,8 +535,8 @@ async def reindex( if _REINDEX is not None and _REINDEX.state == "running": running = _REINDEX.view() raise HTTPException( - 409, f"已经在重建索引了({_REINDEX.collection or '全部集合'}," - f"已完成 {running['done']}/{running['total']}),等它做完再点", + 409, f"正在重建索引({_REINDEX.collection or '全部集合'}," + f"已完成 {running['done']}/{running['total']}),请等待完成后再操作", ) job = _REINDEX = _ReindexJob(collection, chunks, memories) if background: @@ -577,7 +577,7 @@ async def get_document( doc = await session.get(Document, doc_id) if not doc: - raise HTTPException(404, "这份文档不存在,可能已经被删了") + raise HTTPException(404, "文档不存在,可能已被删除") rows = list((await session.execute( select(Chunk).where(Chunk.document_id == doc_id).order_by(Chunk.ordinal) @@ -606,7 +606,7 @@ async def get_document( @kb_router.delete("/documents/{doc_id}", status_code=204) async def delete_document(doc_id: str, session: AsyncSession = Depends(get_session)) -> None: if not await kb.delete_document(session, doc_id): - raise HTTPException(404, "这份文档不存在,可能已经被删了") + raise HTTPException(404, "文档不存在,可能已被删除") # -------------------------------------------------------------------------- @@ -655,7 +655,7 @@ async def update_skill( ) -> Skill: row = await session.get(Skill, skill_id) if not row: - raise HTTPException(404, "这个 Skill 不存在,可能已经被删了") + raise HTTPException(404, "Skill 不存在,可能已被删除") for key, value in payload.model_dump().items(): setattr(row, key, value) await session.commit() @@ -667,6 +667,6 @@ async def update_skill( async def delete_skill(skill_id: str, session: AsyncSession = Depends(get_session)) -> None: row = await session.get(Skill, skill_id) if not row: - raise HTTPException(404, "这个 Skill 不存在,可能已经被删了") + raise HTTPException(404, "Skill 不存在,可能已被删除") await session.delete(row) await session.commit() diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index e6489b3f..ff622173 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -99,16 +99,16 @@ async def start_run( # 正式运行的全部语义就这一条规则:必须引用一个不可变的已发布版本。 # 传裸 graph、或工作流还没发布过,都进不了 formal。 if not payload.workflow_id: - raise HTTPException(400, "正式运行要从一个已保存的工作流发起:请求里没有指定工作流") + raise HTTPException(400, "正式运行需要从已保存的工作流发起:请求中没有指定工作流") if payload.graph is not None: - raise HTTPException(400, "正式运行只跑已发布的版本,不接受画布上没发布的改动——先保存并发布") + raise HTTPException(400, "正式运行只能使用已发布的版本,画布上未发布的修改不会生效。请先保存并发布") workflow = await session.get(Workflow, payload.workflow_id) if not workflow: - raise HTTPException(404, "找不到这个工作流,可能已经被删除了") + raise HTTPException(404, "工作流不存在,可能已被删除") # 只看 published_version:status 反映的是当前画布(改过图就退回 draft), # 而 formal 跑的是已发布的那一版,两者本来就可以不一致 if not workflow.published_version: - raise HTTPException(409, f"「{workflow.name}」还没有发布版本,先在编排页发布") + raise HTTPException(409, f"「{workflow.name}」还没有发布版本,请先在编排页发布") version = payload.version or workflow.published_version # "不可变"和"过过闸"是两件事。快照确实不可变,但 PATCH 保存出来的 # 草稿版本同样有快照——只认 version 存不存在的话,工作流只要发布过 @@ -118,7 +118,7 @@ async def start_run( raise HTTPException( 409, f"v{version} 不是当前发布版本(v{workflow.published_version})。" - "正式运行只能引用发布过的版本——要跑这一版就先发布它。", + "正式运行只能使用当前发布版本;如需运行这一版,请先发布它。", ) snapshot = ( await session.execute( @@ -147,11 +147,11 @@ async def start_run( if payload.workflow_id: workflow = await session.get(Workflow, payload.workflow_id) if not workflow: - raise HTTPException(404, "找不到这个工作流,可能已经被删除了") + raise HTTPException(404, "工作流不存在,可能已被删除") graph = graph or workflow.graph name = workflow.name if not graph: - raise HTTPException(400, "没有要运行的内容:请求里既没有工作流 id,也没有工作流内容") + raise HTTPException(400, "没有要运行的内容:请求中既没有工作流 ID,也没有工作流内容") await _refuse_missing_tools(session, graph) from app.api.settings import resolve_run_scope @@ -264,16 +264,16 @@ async def _refuse_missing_tools(session: AsyncSession, graph: dict[str, Any]) -> missing = await missing_tools(session, spec) if not missing: return - lines = ";".join(f"{who}绑的 {name}" for who, name, _ in missing[:8]) + lines = ";".join(f"{who}绑定的 {name}" for who, name, _ in missing[:8]) more = f"等 {len(missing)} 处" if len(missing) > 8 else "" places = {where for _, _, where in missing} if places == {"data"}: - fix = "去数据页接入,或在节点里重新选" + fix = "请到「数据」页接入,或在节点中重新选择" elif places == {"tools"}: - fix = "去工具页接入,或在节点里重新选" + fix = "请到「工具」页接入,或在节点中重新选择" else: - fix = "数据源工具去数据页接入、其他工具去工具页接入,或在节点里重新选" - raise CodedHTTPException(422, f"绑定的工具在本机不存在:{lines}{more}。{fix}", TOOL_MISSING) + fix = "数据源工具请到「数据」页接入,其他工具请到「工具」页接入,或在节点中重新选择" + raise CodedHTTPException(422, f"绑定的工具不存在:{lines}{more}。{fix}", TOOL_MISSING) #: workflow_id 取这个值时只要没挂在任何工作流上的运行:画布上没保存就跑的临时图, @@ -410,9 +410,9 @@ async def cancel_run(run_id: str, x_actor: str | None = Header(default=None)) -> def _cannot_cancel(status: str) -> str: return { "succeeded": "这次运行已完成,没有要停止的。", - "failed": "这次运行已经失败结束了,没有要停止的;要继续请用「接着跑」。", - "cancelled": "这次运行已经取消了。", - }.get(status, "这次运行已经不在执行中(可能刚结束,或者服务重启过),不需要再停止。刷新看看最新状态") + "failed": "这次运行已失败结束,没有要停止的;如需继续,请点「继续运行」。", + "cancelled": "这次运行已取消。", + }.get(status, "这次运行已不在执行中(可能刚结束,或服务重启过),无需停止。请刷新页面查看最新状态") class ResumeIn(BaseModel): @@ -421,7 +421,7 @@ class ResumeIn(BaseModel): def _missing(e: KeyError) -> HTTPException: - # str(KeyError) 会带上 repr 的引号,界面上就成了 "'找不到运行 x'" + # str(KeyError) 会带上 repr 的引号,界面上就成了 "'运行记录不存在'" return HTTPException(404, str(e.args[0]) if e.args else "运行记录不存在") @@ -557,12 +557,12 @@ async def delete_run( if not run: raise HTTPException(404, "运行记录不存在") if run.status in ("queued", "running") or run_manager.is_active(run_id): - raise HTTPException(409, "这次运行还在进行,现在删除会留下没人管的任务。先停止它,再删除") + raise HTTPException(409, "这次运行仍在进行,现在删除会留下无人管理的后台任务。请先停止运行,再删除") if run.run_class == "formal" and run.manifest_hash and not force: raise HTTPException( 409, - "这是一次已封存的正式运行,是出具结果的追溯凭证。删除后它的事件和工件会一并删掉," - "封存清单再也无法核对。确认要删的话请再确认一次(强制删除)", + "这是一次已封存的正式运行,是出具结果的追溯凭证。删除后其事件和工件将一并删除," + "封存清单无法再核对。如仍要删除,请选择「强制删除」", ) await session.delete(run) await session.commit() @@ -754,9 +754,9 @@ async def decide( ) -> Run: approval = await session.get(Approval, approval_id) if not approval: - raise HTTPException(404, "找不到这条审批,所属的运行可能已经被删除了") + raise HTTPException(404, "审批记录不存在,所属的运行可能已被删除") if approval.status != "pending": - raise HTTPException(409, "这条审批已经处理过了,刷新看看最新状态") + raise HTTPException(409, "这条审批已处理过,请刷新页面查看最新状态") # 责任归属先落库再恢复执行——恢复失败也要留下"谁试图批的" approval.resolved_by = actor_of(x_actor) diff --git a/backend/app/api/settings.py b/backend/app/api/settings.py index acf1124b..c0e941ff 100644 --- a/backend/app/api/settings.py +++ b/backend/app/api/settings.py @@ -155,7 +155,7 @@ async def create_provider( await session.execute(select(Provider).where(Provider.name == payload.name)) ).scalar_one_or_none() if exists: - raise HTTPException(409, f"已经有叫「{payload.name}」的模型接入了,换个名字") + raise HTTPException(409, f"已存在名为「{payload.name}」的模型接入,请换一个名称") row = Provider( name=payload.name, @@ -181,7 +181,7 @@ async def update_provider( ) -> ProviderOut: row = await session.get(Provider, provider_id) if not row: - raise HTTPException(404, "这个模型接入不存在,可能已经被删了") + raise HTTPException(404, "模型接入不存在,可能已被删除") data = payload.model_dump(exclude_unset=True) before, last = _connection(row), (row.extra or {}).get(LAST_CHECK) @@ -210,7 +210,7 @@ async def delete_provider( ) -> None: row = await session.get(Provider, provider_id) if not row: - raise HTTPException(404, "这个模型接入不存在,可能已经被删了") + raise HTTPException(404, "模型接入不存在,可能已被删除") await session.delete(row) await session.commit() @@ -223,9 +223,9 @@ class TestIn(BaseModel): def _config_problem(kind: str, base_url: str | None) -> str | None: """保存或测试前就能看出来的配置错误。""" if kind not in {k["kind"] for k in catalog.PROVIDER_KINDS}: - return f"不认识「{kind}」这种接入类型" + return f"不支持「{kind}」接入类型" if kind == "openai_compatible" and not (base_url or "").strip(): - return "「OpenAI 兼容」必须填 Base URL,例如 https://api.deepseek.com/v1" + return "「OpenAI 兼容」必须填写 Base URL,例如 https://api.deepseek.com/v1" return None @@ -243,16 +243,16 @@ async def _try_model(provider: Provider, model: str | None, prompt: str) -> dict model = model or provider.default_model if not model: - return {"ok": False, "error": "还没有可测的模型", - "hint": "先在「可选模型」里加一个,或者填上默认模型", "detail": ""} + return {"ok": False, "error": "没有可测试的模型", + "hint": "请先在「可选模型」中添加一个,或填写默认模型", "detail": ""} try: chat = build_chat_model(provider, ModelSpec(model=model, max_tokens=256, timeout=_TEST_TIMEOUT)) except ProviderNotConfigured as e: - if "API Key" in str(e): - return {"ok": False, "error": "还没有填 API Key", - "hint": "填上 Key 再测;也可以在后端的环境变量里配", "detail": str(e)} - return {"ok": False, "error": not_configured(e), "hint": "", "detail": str(e)} + if e.code == "missing_key": + return {"ok": False, "error": "尚未填写 API Key", + "hint": "请填写 API Key 后再测试,也可在服务端的环境变量中配置", "detail": str(e)} + return {"ok": False, "error": not_configured(e, with_hint=False), "hint": "", "detail": str(e)} started = time.perf_counter() try: @@ -260,7 +260,7 @@ async def _try_model(provider: Provider, model: str | None, prompt: str) -> dict reply = await chat.ainvoke(prompt) except Exception as e: # noqa: BLE001 reason, hint = explain(e) - return {"ok": False, "error": f"测试没通过:{reason}", "hint": hint, "detail": raw(e), + return {"ok": False, "error": f"测试未通过:{reason}", "hint": hint, "detail": raw(e), "model": model} usage = getattr(reply, "usage_metadata", None) or {} @@ -280,7 +280,7 @@ async def test_provider( """真发一次请求验证配置。设置页的"测试连接"按钮调它。""" row = await session.get(Provider, provider_id) if not row: - raise HTTPException(404, "这个模型接入不存在,可能已经被删了") + raise HTTPException(404, "模型接入不存在,可能已被删除") result = await _try_model(row, payload.model, payload.prompt) # 只记默认模型的结果:拿别的模型测出 invalid_model,不等于这个接入连不上 if (payload.model or row.default_model) == row.default_model: @@ -406,7 +406,7 @@ async def probe_provider_models( data = resp.json() except Exception as e: # noqa: BLE001 reason, hint = explain(e) - return {"ok": False, "error": f"没拿到模型列表:{reason}", "hint": hint, + return {"ok": False, "error": f"未能获取模型列表:{reason}", "hint": hint, "detail": raw(e), "models": [], "url": url} models = [m.get("id", "") for m in (data.get("data") or []) if isinstance(m, dict) and m.get("id")] return {"ok": True, "models": models, "url": url} diff --git a/backend/app/api/tools.py b/backend/app/api/tools.py index 6fcbbca2..bdc7a34d 100644 --- a/backend/app/api/tools.py +++ b/backend/app/api/tools.py @@ -100,20 +100,20 @@ class RunToolIn(BaseModel): def _builtin_effect(name: str, args: dict[str, Any]) -> str: if name == "file_write": - path = args.get("path") or "(没填路径)" + path = args.get("path") or "(未填写路径)" if args.get("append"): - return f"会往 playground 工作目录里的「{path}」追加内容" - return f"会在 playground 工作目录里写入「{path}」,同名文件会被覆盖" + return f"将向工作目录中的「{path}」追加内容" + return f"将在工作目录中写入「{path}」,同名文件会被覆盖" if name == "http_request": - return (f"会向 {args.get('url') or '(没填地址)'} 发一个 {args.get('method') or 'GET'} 请求" + return (f"将向 {args.get('url') or '(未填写地址)'} 发送 {args.get('method') or 'GET'} 请求" "(内网和回环地址会被拦截)") if name == "shell_exec": - return f"会在沙箱里执行命令:{str(args.get('command') or '')[:120]}" + return f"将在沙箱中执行命令:{str(args.get('command') or '')[:120]}" if name == "python_exec": - return "会在沙箱里执行这段 Python 代码" + return "将在沙箱中执行这段 Python 代码" if name == "run_code": lang = args.get("language") or "python" - return f"会在沙箱里执行这段 {lang} 代码" + (",并且允许联网" if args.get("network") else "") + return f"将在沙箱中执行这段 {lang} 代码" + (",且允许联网" if args.get("network") else "") return f"「{name}」有副作用" @@ -124,22 +124,22 @@ async def _side_effect(name: str, args: dict[str, Any], session: AsyncSession) - return _builtin_effect(name, args) if spec.dangerous else None if name.startswith("mcp:"): server, _, tool = name[4:].partition("/") - return (f"会调用 MCP 服务「{server}」上的工具「{tool}」。它是外部进程," - "会做什么由它自己决定,这里预知不了") + return (f"将调用 MCP 服务「{server}」上的工具「{tool}」。该工具由外部进程提供," + "具体行为无法预先确定") row = (await session.execute( select(CustomTool).where(CustomTool.name == name) )).scalar_one_or_none() if row is not None: cfg = row.config or {} if row.kind == "http": - return (f"会调用自定义接口「{name}」" - f"({cfg.get('method') or 'GET'} {cfg.get('url') or '(没填地址)'})") - return f"会在沙箱里执行自定义工具「{name}」的代码" + return (f"将调用自定义接口「{name}」" + f"({cfg.get('method') or 'GET'} {cfg.get('url') or '(未填写地址)'})") + return f"将在沙箱中执行自定义工具「{name}」的代码" # 数据源工具:只读源上的查询没有副作用,可写源上的写操作有 tools = await build_tools([name], ToolContext(run_id="playground", node_id="playground"), session=session) if tools and call_is_dangerous(tools[0], name, args): - return f"会在可写数据源上执行写操作:{str(args.get('sql') or '')[:120]}" + return f"将在可写数据源上执行写操作:{str(args.get('sql') or '')[:120]}" return None @@ -161,7 +161,7 @@ async def run_tool( if effect: # 只说后果,不说怎么确认:弹窗还是再点一次是界面的事,写死在这里 # 放进确认框里读起来就不对 - raise HTTPException(409, f"{effect}。在工具库里执行不经过审批,确认后才会执行。") + raise HTTPException(409, f"{effect}。在工具库中执行不经过审批,确认后才会执行。") ctx = ToolContext(run_id="playground", node_id="playground", sandbox_session=payload.sandbox_session) @@ -245,9 +245,9 @@ async def create_custom( payload: CustomToolIn, session: AsyncSession = Depends(get_session) ) -> CustomToolOut: if (await session.execute(select(CustomTool).where(CustomTool.name == payload.name))).scalar_one_or_none(): - raise HTTPException(409, f"已经有叫「{payload.name}」的工具了,换个名字") + raise HTTPException(409, f"已存在名为「{payload.name}」的工具,请换一个名称") if payload.name in all_specs(): - raise HTTPException(409, f"「{payload.name}」和内置工具重名了,换个名字") + raise HTTPException(409, f"「{payload.name}」与内置工具重名,请换一个名称") _refuse_bad_schema(payload.parameters) row = CustomTool(**payload.model_dump()) session.add(row) @@ -262,7 +262,7 @@ async def update_custom( ) -> CustomToolOut: row = await session.get(CustomTool, tool_id) if not row: - raise HTTPException(404, "这个工具不存在,可能已经被删了") + raise HTTPException(404, "工具不存在,可能已被删除") _refuse_bad_schema(payload.parameters) for key, value in payload.model_dump().items(): setattr(row, key, value) @@ -275,7 +275,7 @@ async def update_custom( async def delete_custom(tool_id: str, session: AsyncSession = Depends(get_session)) -> None: row = await session.get(CustomTool, tool_id) if not row: - raise HTTPException(404, "这个工具不存在,可能已经被删了") + raise HTTPException(404, "工具不存在,可能已被删除") await session.delete(row) await session.commit() @@ -295,7 +295,7 @@ async def _trial(row: CustomTool, args: dict[str, Any]) -> dict[str, Any]: if problem: # 手写的参数定义写坏了:是配置的事,不是「后端内部出错」 return {"ok": False, "error": problem, - "hint": '参数定义是 JSON Schema,写成 {"type": "object", "properties": ' + "hint": '参数定义是 JSON Schema,格式如 {"type": "object", "properties": ' '{"n": {"type": "integer", "description": "…"}}, "required": ["n"]}', "detail": "", "duration_ms": 0} try: @@ -312,10 +312,10 @@ async def _trial(row: CustomTool, args: dict[str, Any]) -> dict[str, Any]: if isinstance(result, ToolFailure): detail = str(result.get("error") or "") if "exit_code" in result: - error = f"代码运行出错(退出码 {result['exit_code']})" - hint = "看下面的报错改代码;调用时传的参数在 args 变量里(一个 dict)" + error = f"代码执行出错(退出码 {result['exit_code']})" + hint = "请根据下方报错修改代码;调用时传入的参数在 args 变量中(一个 dict)" else: - error = f"工具执行失败:{detail.splitlines()[0] if detail else '没有说明'}" + error = f"工具执行失败:{detail.splitlines()[0] if detail else '未提供说明'}" hint = "HTTP 工具只能访问公网地址,内网、回环地址会被拦截" if "拦截" in detail else "" return {"ok": False, "error": error, "hint": hint, "detail": json.dumps(dict(result), ensure_ascii=False), "duration_ms": took(), @@ -335,11 +335,11 @@ class CustomToolDraftIn(BaseModel): def _draft_problem(kind: str, config: dict[str, Any]) -> str | None: if kind not in ("http", "python"): - return f"不认识「{kind}」这种工具类型:只有 http 和 python 两种" + return f"不支持「{kind}」工具类型:仅支持 http 和 python" if kind == "http" and not str(config.get("url") or "").strip(): - return "还没填接口地址" + return "尚未填写接口地址" if kind == "python" and not str(config.get("code") or "").strip(): - return "还没写代码" + return "尚未填写代码" return None @@ -364,7 +364,7 @@ async def test_custom( ) -> dict[str, Any]: row = await session.get(CustomTool, tool_id) if not row: - raise HTTPException(404, "这个工具不存在,可能已经被删了") + raise HTTPException(404, "工具不存在,可能已被删除") return await _trial(row, payload.args) @@ -421,7 +421,7 @@ async def create_server( payload: McpIn, session: AsyncSession = Depends(get_session) ) -> McpOut: if (await session.execute(select(McpServer).where(McpServer.name == payload.name))).scalar_one_or_none(): - raise HTTPException(409, f"已经有叫「{payload.name}」的 MCP 服务了,换个名字") + raise HTTPException(409, f"已存在名为「{payload.name}」的 MCP 服务,请换一个名称") row = McpServer(**payload.model_dump()) session.add(row) await session.commit() @@ -435,7 +435,7 @@ async def update_server( ) -> McpOut: row = await session.get(McpServer, server_id) if not row: - raise HTTPException(404, "这个 MCP 服务不存在,可能已经被删了") + raise HTTPException(404, "MCP 服务不存在,可能已被删除") before, old_name, was_enabled = _mcp_connection(row), row.name, row.enabled for key, value in payload.model_dump().items(): setattr(row, key, value) @@ -454,7 +454,7 @@ async def update_server( async def delete_server(server_id: str, session: AsyncSession = Depends(get_session)) -> None: row = await session.get(McpServer, server_id) if not row: - raise HTTPException(404, "这个 MCP 服务不存在,可能已经被删了") + raise HTTPException(404, "MCP 服务不存在,可能已被删除") await session.delete(row) await session.commit() mcp_manager.invalidate(row.name) @@ -466,7 +466,7 @@ async def probe_server( ) -> dict[str, Any]: row = await session.get(McpServer, server_id) if not row: - raise HTTPException(404, "这个 MCP 服务不存在,可能已经被删了") + raise HTTPException(404, "MCP 服务不存在,可能已被删除") import time started = time.perf_counter() diff --git a/backend/app/api/workflows.py b/backend/app/api/workflows.py index 5584b71e..26924e0d 100644 --- a/backend/app/api/workflows.py +++ b/backend/app/api/workflows.py @@ -17,9 +17,9 @@ from app.engine.schema import GraphSpec, NodeType, validate_graph router = APIRouter(prefix="/api/workflows", tags=["workflows"]) -_GONE = "这个工作流不存在,可能已经被删了" +_GONE = "工作流不存在,可能已被删除" _LEVELS = ("published", "governed") -_BAD_LEVEL = "发布档位只能选「已发布」或「受管」" +_BAD_LEVEL = "发布级别只能是「已发布」或「受管」" class WorkflowIn(BaseModel): @@ -154,7 +154,7 @@ async def delete_workflow( ) ) if live: - raise HTTPException(409, f"这个工作流还有 {live} 次运行在进行,现在删除它们会失去归属。先停止运行,再删除") + raise HTTPException(409, f"该工作流还有 {live} 次运行正在进行,现在删除会使这些运行失去所属工作流。请先停止运行,再删除") await session.delete(workflow) await session.commit() @@ -228,7 +228,7 @@ async def get_version( ) ).scalar_one_or_none() if not snapshot: - raise HTTPException(404, f"「{workflow.name}」没有 v{version} 这个版本") + raise HTTPException(404, f"「{workflow.name}」不存在 v{version} 版本") graph = snapshot.graph or {} fields: list[dict[str, Any]] = [] @@ -262,7 +262,7 @@ async def restore_version( ) ).scalar_one_or_none() if not snapshot: - raise HTTPException(404, f"没有 v{version} 这个版本") + raise HTTPException(404, f"不存在 v{version} 版本") workflow.graph = snapshot.graph workflow.version += 1 @@ -317,12 +317,12 @@ async def publish_workflow( ) ).scalar_one_or_none() if not snapshot: - raise HTTPException(404, f"没有 v{version} 这个版本:画布上的改动还没保存,先保存一次再发布") + raise HTTPException(404, f"不存在 v{version} 版本:画布上的修改还没有保存,请先保存再发布") try: spec = GraphSpec.model_validate(snapshot.graph) except Exception as e: # noqa: BLE001 - return {"ok": False, "issues": [{"level": "error", "message": f"工作流的结构读不懂:{graph_error(e)}"}]} + return {"ok": False, "issues": [{"level": "error", "message": f"无法解析工作流结构:{graph_error(e)}"}]} issues = [i.model_dump() for i in publish_issues(spec, level=payload.level)] if any(i["level"] == "error" for i in issues): @@ -403,7 +403,7 @@ async def _gate_context(session: AsyncSession, spec: GraphSpec) -> tuple[dict[st def _unreadable(level: str, e: Exception) -> dict[str, Any]: return {"level": level, "ok": False, "fixes": [], "issues": [ {"level": "error", "node_id": None, "edge_id": None, "field": None, "code": None, "fix": None, - "message": f"工作流的结构读不懂:{graph_error(e)}"}]} + "message": f"无法解析工作流结构:{graph_error(e)}"}]} @router.post("/{workflow_id}/publish-check") @@ -443,7 +443,7 @@ async def autofix( except Exception as e: # noqa: BLE001 bad = _unreadable(payload.level, e) return {"graph": graph, "changes": [], "ops": [], "applied": [], "rejected": [ - {"fix_id": fid, "reason": "工作流的结构读不懂,没法应用修复"} for fid in payload.apply], + {"fix_id": fid, "reason": "无法解析工作流结构,不能应用修复"} for fid in payload.apply], "remaining": bad["issues"], "fixes": [], "handoff": [], "assist": None, "ok": False} versions, cards = await _gate_context(session, spec) out = apply_fixes(graph, payload.apply, payload.choices, level=payload.level, versions=versions, cards=cards) @@ -451,7 +451,7 @@ async def autofix( # 人在选项里选了「交给 Copilot」(handoff),和点「交给 Copilot」是一回事 if payload.assist or out["handoff"]: if out["ok"]: - out["assist"] = {"ok": True, "summary": "修复之后已经没有挡住发布的错误,没有再交给 Copilot", + out["assist"] = {"ok": True, "summary": "修复后已没有阻止发布的错误,未再交给助手", "questions": []} return out from app.api.copilot import assist_publish_fix @@ -461,7 +461,7 @@ async def autofix( out["assist"] = {"ok": helped["accepted"], "summary": helped["summary"], "questions": helped["questions"]} if helped["accepted"]: fixed = helped["graph"] - out["changes"] += diff_changes(out["graph"], fixed, fix_id="assist", label="Copilot 的修改") + out["changes"] += diff_changes(out["graph"], fixed, fix_id="assist", label="助手的修改") out["ops"] += helped["ops"] out["applied"].append("assist") after = apply_fixes(fixed, [], level=payload.level, versions=versions, cards=cards) @@ -481,7 +481,7 @@ async def validate(payload: ValidateIn) -> dict[str, Any]: try: spec = GraphSpec.model_validate(payload.graph) except Exception as e: # noqa: BLE001 - return {"ok": False, "issues": [{"level": "error", "message": f"工作流的结构读不懂:{graph_error(e)}"}]} + return {"ok": False, "issues": [{"level": "error", "message": f"无法解析工作流结构:{graph_error(e)}"}]} result = validate_graph(spec) return result.model_dump() @@ -498,5 +498,5 @@ async def variables(payload: ValidateIn) -> dict[str, Any]: try: spec = GraphSpec.model_validate(payload.graph) except Exception as e: # noqa: BLE001 - return {"variables": [], "issues": [{"level": "error", "message": f"工作流的结构读不懂:{graph_error(e)}"}]} + return {"variables": [], "issues": [{"level": "error", "message": f"无法解析工作流结构:{graph_error(e)}"}]} return analyze(spec).model_dump() diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py index 2ed707e9..94cc3966 100644 --- a/backend/app/core/errors.py +++ b/backend/app/core/errors.py @@ -10,7 +10,7 @@ 运行记录里是两句话。现在认异常的规则只有下面这一张表,两个入口只在一件事上分叉: TypeError、KeyError 这类「程序自己的毛病」—— -- 接口里冒出来的,是后端的 bug,原文里全是内部符号,说「后端内部出错了」; +- 接口里冒出来的,是后端的 bug,原文里全是内部符号,说「服务端内部错误」; - 节点里冒出来的,多半是工具被传错了参数、用户代码取错了字段,说清是哪个参数、 哪个字段,模型和人才知道该改什么。 @@ -81,8 +81,16 @@ def _scrub(text: str) -> str: return " ".join(text.split())[:240] -def _known(e: BaseException, *, sniff: bool) -> tuple[str, str] | None: - """两种场景说法一样的那些:鉴权、找不到、限流、对方故障、超时、网络、格式、文件。 +#: classify() 的返回值:错误属于哪一类。调用方按类别给场景专用的说法(比如测数据库连接时, +#: 网络不通要说主机和端口,不说 API),不要拿 explain() 返回的文字做比较——文字会改,类别不会 +AUTH, NOT_FOUND, RATE_LIMIT, SERVER, TIMEOUT, NETWORK = "auth", "not_found", "rate_limit", "server", "timeout", "network" +BAD_JSON, VALIDATION, PERMISSION, FILE_MISSING, OVERFLOW, BUG = ( + "bad_json", "validation", "permission", "file_missing", "overflow", "bug") + + +def _known(e: BaseException, *, sniff: bool) -> tuple[str, str, str] | None: + """两种场景说法一样的那些:鉴权、找不到、限流、服务方故障、超时、网络、格式、文件。 + 返回 (类别, 原因, 怎么办)。 sniff:类名认不出时要不要按原文字面猜。SDK 抛出来的裸异常要猜(原文就是 "Connection refused");执行层的异常常常是已经拼好的一句话、里头套着具体原因, @@ -94,42 +102,52 @@ def _known(e: BaseException, *, sniff: bool) -> tuple[str, str] | None: if status in (401, 403) or names & _AUTH or "invalid api key" in low or "unauthorized" in low: code = f"({status})" if status else "" - return (f"鉴权没通过{code}:对方拒绝了这把密钥", - "核对 API Key 有没有填错、过期,或者这个账号有没有这个模型的权限") + return (AUTH, f"鉴权失败{code}:服务方拒绝了当前 API Key", + "请检查 API Key 是否填写正确、是否过期,以及该账号是否有权使用此模型") if status == 404 or "NotFoundError" in names: - return "对方说找不到(404)", "核对地址的路径(常见的是少了或多了 /v1)和模型名" + return (NOT_FOUND, "请求的地址或模型不存在(404)", + "请检查地址路径(常见问题是多了或少了 /v1)和模型名") if status == 429 or "RateLimitError" in names: - return "请求太频繁,或者额度用完了(429)", "等一会儿再试;频繁出现就检查账号额度" + return RATE_LIMIT, "请求过于频繁或额度已用完(429)", "请稍后重试;频繁出现时请检查账号额度" if isinstance(status, int) and status >= 500: - return f"对方服务出错了(HTTP {status})", "这是对方的问题,多半是暂时的,稍后再试" + return SERVER, f"服务方内部错误(HTTP {status})", "通常是暂时性故障,请稍后重试" if isinstance(e, TimeoutError) or names & _TIMEOUT or "timed out" in low: - return ("等待超时:对方没有在限定时间内响应", - "对方可能很忙或者网络不稳,稍后再试;一直超时就检查地址和网络") + return (TIMEOUT, "等待超时:服务方未在限定时间内响应", + "服务方可能繁忙或网络不稳定,请稍后重试;持续超时请检查地址和网络") if isinstance(e, ConnectionError) or names & _NETWORK or any(s in low for s in _UNREACHABLE): - return ("连不上对方的服务:网络不通,或者服务没有启动", - "核对地址和端口,确认服务已经启动、这台机器访问得到它") + return (NETWORK, "无法连接服务:网络不通或服务未启动", + "请检查地址和端口,确认服务已启动且本机可以访问") if isinstance(e, json.JSONDecodeError): - return "返回的内容不是合法的 JSON", "地址多半指到了网页而不是 API,核对 Base URL" + return BAD_JSON, "返回内容不是合法的 JSON", "地址可能指向了网页而非 API,请检查 Base URL" if "ValidationError" in names and callable(getattr(e, "errors", None)): - return f"参数不对:{_first_validation(e)}", "" + return VALIDATION, f"参数有误:{_first_validation(e)}", "" if isinstance(e, PermissionError): - return "没有权限访问需要的文件或资源", "" + return PERMISSION, "没有权限访问所需的文件或资源", "" if isinstance(e, FileNotFoundError): - return f"找不到文件{'「' + str(e.filename) + '」' if e.filename else ''}", "" + return FILE_MISSING, f"找不到文件{'「' + str(e.filename) + '」' if e.filename else ''}", "" if isinstance(e, (OverflowError, MemoryError)): text = str(e).strip() - return f"数据超出了能处理的范围{':' + _scrub(text) if text else ''}", "" + return OVERFLOW, f"数据超出了可处理的范围{':' + _scrub(text) if text else ''}", "" return None -def explain(e: BaseException) -> tuple[str, str]: - """接口层:(原因, 怎么办)。原因是一句人话;说不出怎么办时第二项是空串。""" +def classify(e: BaseException) -> str | None: + """错误属于哪一类(上面那组常量),认不出返回 None。和 explain() 的判断是同一套规则。""" known = _known(e, sniff=True) if known: - return known + return known[0] + return BUG if _names(e) & _BUG else None + + +def explain(e: BaseException) -> tuple[str, str]: + """接口层:(原因, 怎么办)。原因是一句人话;说不出怎么办时第二项是空串。 + 要按错误类别换说法的,用 classify() 拿类别,不要比较这里返回的文字。""" + known = _known(e, sniff=True) + if known: + return known[1], known[2] if _names(e) & _BUG: - return "后端内部出错了", "这不是你操作的问题;把技术细节发给维护者" - return first_line(e) or "出了一个没有说明的错误", "" + return "服务端内部错误", "与你的操作无关,请将技术细节提供给维护者" + return first_line(e) or "发生了未说明原因的错误", "" def describe_exception(e: BaseException) -> str: @@ -137,7 +155,7 @@ def describe_exception(e: BaseException) -> str: text = str(e).strip() if isinstance(e, TypeError): if m := re.search(r"unexpected keyword argument '(\w+)'", text): - return f"参数对不上:它不接受名为「{m.group(1)}」的参数" + return f"参数不匹配:不接受名为「{m.group(1)}」的参数" if m := re.search(r"missing \d+ required (?:positional |keyword-only )?arguments?: (.+)$", text): wanted = "、".join(re.findall(r"'(\w+)'", m.group(1))) or m.group(1) return f"缺少必填参数「{wanted}」" @@ -145,8 +163,8 @@ def describe_exception(e: BaseException) -> str: return f"缺少字段「{e.args[0] if e.args else '?'}」" known = _known(e, sniff=False) if known: - return known[0] - return _scrub(text) or "没有给出原因的内部错误" + return known[1] + return _scrub(text) or "内部错误(未提供原因)" def message(e: BaseException, lead: str = "") -> str: @@ -162,9 +180,14 @@ def payload(e: BaseException, lead: str = "") -> dict[str, Any]: return {"ok": False, "error": f"{lead}{reason}", "hint": hint, "detail": raw(e)} -def not_configured(e: BaseException) -> str: - """模型接入没配好时的原话用的是内部叫法(provider 'x'、base_url),换成设置页上的说法。""" - text = re.sub(r"provider '([^']*)'", r"模型接入「\1」", str(e)) +def not_configured(e: BaseException, *, with_hint: bool = True) -> str: + """模型接入没配好(ProviderNotConfigured)给用户看的那句话。运行失败原因、助手、设置页都经过这里。 + + with_hint=False 只要「缺了什么」、不要「去哪里补」:设置页的测试弹窗本来就在接入的编辑框里, + 助手那边自己另说去哪里。别处抛的同类异常(没有 reason 字段)原话里可能还是内部叫法 + (provider 'x'、base_url),一并换成设置页上的说法。""" + text = str(e) if with_hint else str(getattr(e, "reason", "") or e) + text = re.sub(r"provider '([^']*)'", r"模型接入「\1」", text) text = re.sub(r"模型 '([^']*)'", r"模型「\1」", text) return text.replace("base_url", "Base URL").rstrip("。") @@ -179,7 +202,9 @@ def _first_validation(e: Any) -> str: msg = str(err.get("msg") or "").removeprefix("Value error, ") if _has_cjk(msg): return msg - return f"「{loc}」{'缺了' if err.get('type') == 'missing' else '格式不对'}" if loc else "格式不对" + if not loc: + return "格式有误" + return f"缺少「{loc}」" if err.get("type") == "missing" else f"「{loc}」格式有误" def graph_error(e: BaseException) -> str: @@ -200,12 +225,12 @@ def graph_error(e: BaseException) -> str: where = f"第 {loc[1] + 1} 个{'节点' if loc[0] == 'nodes' else '连线'}" field = str(loc[2]) if len(loc) > 2 else "" if err.get("type") == "enum" and field == "type": - return f"{where}的类型「{err.get('input')}」不认识{more}" + return f"{where}的类型「{err.get('input')}」无法识别{more}" if err.get("type") == "missing": - return f"{where}缺了「{field}」{more}" + return f"{where}缺少「{field}」{more}" if _has_cjk(msg): return f"{where}:{msg}{more}" - return f"{where}的「{field or '内容'}」格式不对{more}" + return f"{where}的「{field or '内容'}」格式有误{more}" if _has_cjk(msg): return msg + more - return f"「{'.'.join(str(p) for p in loc) or '整体'}」格式不对{more}" + return f"「{'.'.join(str(p) for p in loc) or '整体'}」格式有误{more}" diff --git a/backend/app/data/engine.py b/backend/app/data/engine.py index 2733d24a..b89d8e51 100644 --- a/backend/app/data/engine.py +++ b/backend/app/data/engine.py @@ -125,7 +125,7 @@ def build_url(source: Any, *, reveal: bool = False) -> str: service = options.pop("service_name", None) or source.database sid = options.pop("sid", None) if not service and not sid: - raise ValueError("Oracle 需要在 options 里给 service_name 或 sid(也可以填在库名里)") + raise ValueError("Oracle 需要填写 service_name 或 SID(也可填在「数据库」中)") tail = f"?service_name={service}" if service else f"?sid={sid}" query = "&".join(f"{k}={v}" for k, v in options.items()) return f"{driver}://{auth}{host}/{tail}{('&' + query) if query else ''}" @@ -183,8 +183,8 @@ def query_timeout_problem(options: dict[str, Any] | None) -> str | None: if value is None or str(value).strip() == "": return None if _timeout_value(value) is None: - return (f"查询时限要填 {MIN_QUERY_TIMEOUT_S} 到 {MAX_QUERY_TIMEOUT_S} 之间的秒数," - f"比如 60;现在填的是「{value}」") + return (f"查询时限需要填写 {MIN_QUERY_TIMEOUT_S} 到 {MAX_QUERY_TIMEOUT_S} 之间的秒数," + f"例如 60;当前为「{value}」") return None @@ -202,7 +202,7 @@ def mask_columns_problem(options: dict[str, Any] | None) -> str | None: return None if isinstance(raw, str) or (isinstance(raw, list) and all(isinstance(c, str) for c in raw)): return None - return f"遮罩的列要填列名,用逗号分开,比如「phone, email」;现在填的是「{raw}」" + return f"遮罩的列需要填写列名,用逗号分隔,例如「phone, email」;当前为「{raw}」" def query_timeout(source: Any) -> float: @@ -529,7 +529,7 @@ async def run_query( columns, rows, truncated, types = await _bounded( engine.connect, kind, limits, - f"查询超过 {_seconds(limits.timeout_seconds)}s 被中断。加上 WHERE 条件或 LIMIT 缩小范围。", + f"查询超过 {_seconds(limits.timeout_seconds)} 秒被中断。请添加 WHERE 条件或 LIMIT 缩小范围。", _read, ) return QueryResult( @@ -609,7 +609,7 @@ async def _run_write( # engine.begin():正常退出提交,出错(包括数据库按时限停下)回滚 columns, rows = await _bounded( engine.begin, kind, limits, - f"写操作超过 {_seconds(limits.timeout_seconds)}s 被中断,已回滚。", _write, + f"写操作超过 {_seconds(limits.timeout_seconds)} 秒被中断,已回滚。", _write, ) return QueryResult( columns=columns, diff --git a/backend/app/data/guard.py b/backend/app/data/guard.py index 6a100937..399ef994 100644 --- a/backend/app/data/guard.py +++ b/backend/app/data/guard.py @@ -140,9 +140,9 @@ _ALL_READINGS: tuple[_Reading, ...] = (_GENERIC, *dict.fromkeys( r for readings in _READINGS.values() for r in readings)) _AMBIGUOUS = ( - "这条 SQL 里的引号、反斜杠或注释,在数据库的不同设置下会读成不同的语句" - "(比如 MySQL 的 NO_BACKSLASH_ESCAPES、ANSI_QUOTES)。" - "字符串里的单引号写成两个单引号 '',不要用反斜杠转义;注释删掉再试" + "这条 SQL 中的引号、反斜杠或注释,在数据库的不同设置下会被解析成不同的语句" + "(例如 MySQL 的 NO_BACKSLASH_ESCAPES、ANSI_QUOTES)。" + "字符串中的单引号请写成两个单引号 '',不要用反斜杠转义;请删除注释后重试" ) _DOLLAR_TAG = re.compile(r"\$(?:[^\W\d]\w*)?\$") @@ -350,15 +350,15 @@ def _blank_quoted(sql: str, *, identifiers: bool = True, dialect: str | None = N def _pragma_write_reason(stmt: str, reading: _Reading = _GENERIC) -> str | None: match = _PRAGMA.match(_joined(_tokens(stmt, reading)).strip()) if not match: - return "看不出这条 PRAGMA 读的是什么" + return "无法判断这条 PRAGMA 读取的内容" name, rest = match.group(1).lower(), match.group(2).strip() if rest.startswith("="): return f"PRAGMA {name} = … 会改数据库设置" if name in _PRAGMA_READ_WITH_ARG or (name in _PRAGMA_READ_NO_ARG and not rest): return None return ( - f"PRAGMA {name}{' ' + rest if rest else ''} 不在只读白名单里" - "(看表结构用 table_info / index_list / foreign_key_list)" + f"PRAGMA {name}{' ' + rest if rest else ''} 不在允许的只读语句范围内" + "(查看表结构请用 table_info / index_list / foreign_key_list)" ) @@ -381,7 +381,7 @@ def _write_reason(stmt: str, reading: _Reading = _GENERIC) -> str | None: hidden = _HIDDEN_WRITE.search(_blanked(tokens, identifiers=True)) if hidden: word = " ".join(hidden.group(1).split()).upper() - return f"语句里有 {word}——以查询开头的语句也能写数据" + return f"语句中包含 {word}:以查询开头的语句也可能写入数据" call = _SIDE_EFFECT_CALL.search(_blanked(tokens, identifiers=False)) if call: return f"{call.group(1)}() 有副作用" @@ -394,7 +394,7 @@ def _write_reason_any(stmt: str, readings: tuple[_Reading, ...]) -> str | None: if reasons[0]: return reasons[0] other = next((r for r in reasons[1:] if r), None) - return f"数据库换一种设置来读的话,{other}。{_AMBIGUOUS}" if other else None + return f"在数据库的其他设置下,{other}。{_AMBIGUOUS}" if other else None def _one_view(sql: str, readings: tuple[_Reading, ...]) -> list[str] | None: @@ -413,18 +413,18 @@ def check(sql: str, *, readonly: bool, source_name: str = "", dialect: str | Non 不知道的话按所有方言、所有设置的读法各判一遍,任何一种读法不过都拒。 """ if not sql or not sql.strip(): - raise SqlRejected("SQL 是空的") + raise SqlRejected("SQL 为空") readings = _readings(dialect) statements = _one_view(sql, readings) if statements is None: raise SqlRejected(_AMBIGUOUS) if not statements: - raise SqlRejected("SQL 里没有可执行的语句") + raise SqlRejected("SQL 中没有可执行的语句") if len(statements) > 1: raise SqlRejected( f"一次只能执行一条语句,这里有 {len(statements)} 条。" - "拆成多次调用——分号拼接的语句不会被执行。" + "请拆成多次调用,分号拼接的语句不会被执行。" ) stmt = statements[0] @@ -434,12 +434,12 @@ def check(sql: str, *, readonly: bool, source_name: str = "", dialect: str | Non verb = first_verb(stmt, dialect=dialect) if not verb: - raise SqlRejected("看不出这条 SQL 要做什么(没有识别到关键字)") + raise SqlRejected("无法识别这条 SQL 的操作类型(未识别到关键字)") if verb in _ALWAYS_DENIED: raise SqlRejected( f"{verb.upper()} 属于结构变更或权限操作,任何数据源上都不允许。" - "这类操作请在数据库客户端里人工执行。" + "这类操作请在数据库客户端中手动执行。" ) if readonly: @@ -449,7 +449,7 @@ def check(sql: str, *, readonly: bool, source_name: str = "", dialect: str | Non raise SqlRejected( f"{where}是只读的:{reason},不被允许。" "只能执行不改数据的 SELECT / WITH / SHOW / DESCRIBE / EXPLAIN。" - "确实需要写入的话,请在设置里另建一个关闭了只读的数据源。" + "如确需写入,请在「数据」页另建一个未勾选「只读」的数据源。" ) return stmt diff --git a/backend/app/data/introspect.py b/backend/app/data/introspect.py index 65be8813..8df4048c 100644 --- a/backend/app/data/introspect.py +++ b/backend/app/data/introspect.py @@ -239,9 +239,9 @@ def why_empty(cache: dict[str, Any]) -> str: 要先解决超时或换 schema。以前两者说的是同一句话。 """ if not cache.get("failed"): - return "还没有探查过结构" + return "尚未探查结构" err = str(cache.get("error") or "").strip() - return f"结构探查失败了:{err[:200]}" if err else "结构探查失败了" + return f"结构探查失败:{err[:200]}" if err else "结构探查失败" def _empty_summary(source: Any, cache: dict[str, Any]) -> str: @@ -325,13 +325,13 @@ def describe_table(source: Any, table: str) -> str: # "没有 X。现有的对象:(还没探查过结构)",白花一整步 return ( f"数据源「{source.name}」的结构信息不可用({why_empty(cache)})," - "所以无法判断有没有这张表。请直接查数据字典" + "因此无法判断是否存在这张表。请直接查询数据字典" "(information_schema.tables / columns,SQLite 用 sqlite_master)。" ) available = "、".join( m.get("qualified", n) for n, m in list(tables.items())[:30] ) - return f"数据源「{source.name}」里没有 {table}。现有的对象:{available}" + return f"数据源「{source.name}」中没有 {table}。现有的对象:{available}" head = f"{'视图' if meta.get('is_view') else '表'} {meta.get('qualified', table)}" if meta.get("comment"): diff --git a/backend/app/data/tabular.py b/backend/app/data/tabular.py index 1c539f39..007900a3 100644 --- a/backend/app/data/tabular.py +++ b/backend/app/data/tabular.py @@ -242,7 +242,7 @@ def _read_excel(raw: bytes, *, header_row: int) -> list[tuple[str, list[list[Any from openpyxl import load_workbook except ImportError as e: raise UnsupportedTable( - "要读 Excel 得先装解析库:pip install 'agentlab-backend[docs]'" + "读取 Excel 需要安装解析库:pip install 'agentlab-backend[docs]'" ) from e try: # read_only 走流式,几十万行也不会把整个工作簿读进内存; @@ -250,9 +250,9 @@ def _read_excel(raw: bytes, *, header_row: int) -> list[tuple[str, list[list[Any book = load_workbook(io.BytesIO(raw), read_only=True, data_only=True) except Exception as e: # noqa: BLE001 # 这句话原样进上传的 400:异常类名留在日志(from e),界面上只说能照着做的 - reason = "文件不是有效的 .xlsx(可能损坏,或者只是改了扩展名)" if isinstance(e, zipfile.BadZipFile) \ + reason = "文件不是有效的 .xlsx(可能已损坏,或只是修改了扩展名)" if isinstance(e, zipfile.BadZipFile) \ else describe_exception(e) - raise UnsupportedTable(f"这个 Excel 读不开:{reason}。在 Excel 里另存为 .xlsx 或 .csv 再传") from e + raise UnsupportedTable(f"无法打开该 Excel 文件:{reason}。请在 Excel 中另存为 .xlsx 或 .csv 后重新上传") from e out: list[tuple[str, list[list[Any]]]] = [] for sheet in book.worksheets: @@ -262,7 +262,7 @@ def _read_excel(raw: bytes, *, header_row: int) -> list[tuple[str, list[list[Any out.append((sheet.title, rows)) book.close() if not out: - raise UnsupportedTable("这个 Excel 里没有任何有内容的工作表") + raise UnsupportedTable("该 Excel 文件中没有包含内容的工作表") return out @@ -279,11 +279,11 @@ def read_tables( return _read_csv(raw, filename, header_row=header_row) if ext in _LEGACY_EXCEL: raise UnsupportedTable( - f"读不了 {filename}:.xls 是老的二进制格式,需要外部转换器。" - "请在 Excel 里另存为 .xlsx 或 .csv 再传。" + f"无法读取 {filename}:.xls 是旧版二进制格式,需要外部转换器。" + "请在 Excel 中另存为 .xlsx 或 .csv 后重新上传。" ) raise UnsupportedTable( - f"读不了 {filename}:只认 Excel(.xlsx)和 CSV / TSV。" + f"无法读取 {filename}:仅支持 Excel(.xlsx)和 CSV / TSV。" ) @@ -345,5 +345,5 @@ def load_into( conn.close() if not report.tables: - raise UnsupportedTable("文件里没有读到任何数据行") + raise UnsupportedTable("文件中没有数据行") return report diff --git a/backend/app/engine/autofix.py b/backend/app/engine/autofix.py index c61d9471..65e2618f 100644 --- a/backend/app/engine/autofix.py +++ b/backend/app/engine/autofix.py @@ -30,6 +30,7 @@ from app.engine.governance import ( exit_text_fields, publish_issues, ) +from app.engine.labels import CHOICE_LABEL, contract_label, field_label, option_label, q from app.engine.schema import ( CLAIMS_JUDGE, JUDGE_ON_UNSUPPORTED, @@ -67,10 +68,10 @@ _WARNING_FIXES = {"governed": frozenset({"contract.strict_off", "contract.claims #: 别的 choice 拿节点 id 当候选值,节点 id 恰好叫 copilot 的报告撰写节点照样是个普通候选 HANDOFF = "copilot" -ASSIST_ONLY = "这一处是结构性的问题,要交给 Copilot:请求里带上 assist: true" -STALE = "这处问题现在已经没有了(修复 id 过期),重新检查一次" -SOLVED = "前面的修复已经一并解决了这一处" -NEED_CHOICE = "这一处要你来选:{label}" +ASSIST_ONLY = "这一处属于结构性问题,需要交给助手处理" +STALE = "这一处问题已不存在,请重新检查" +SOLVED = "前面的修复已一并解决了这一处" +NEED_CHOICE = "这一处需要你选择:{label}" #: 修复和 Copilot 兜底只许改节点配置、补节点和连线。其余的图操作(删节点、删连线)和 #: 任何不认识的操作(发布、改级别…)一律当降低要求处理 @@ -147,12 +148,12 @@ def _as_list(value: Any) -> list[Any]: def _cards_choice(ctx: _Ctx, node: GraphNode, before: Any, field: str) -> dict[str, Any]: cards = ctx.upstream(node.id, NodeType.METRICS) if len(cards) == 1: - return _auto(f"出具契约的指标来自上游唯一的口径卡「{cards[0].title}」(metrics_from)", field, before, + return _auto(f"出具契约的「指标来自」设为上游唯一的口径卡「{cards[0].title}」", field, before, [cards[0].id]) if cards: - return _choice("选出具契约的指标来自哪几张口径卡(metrics_from)", field, _node_options(cards), + return _choice("选择出具契约的「指标来自」:从哪几个口径卡取指标", field, _node_options(cards), multiple=True) - return _assist("出口上游没有口径卡,出具契约的 metrics_from 无处可指", field) + return _assist("成果节点上游没有口径卡,出具契约的「指标来自」无处可选", field) def _plan_metrics_from_missing(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: @@ -169,8 +170,8 @@ def _plan_metrics_from_invalid(ctx: _Ctx, issue: dict[str, Any], node: GraphNode == NodeType.METRICS] if keep: bad = [str(s) for s in _as_list(before) if s not in keep and str(s).strip()] - return _auto(f"出具契约的 metrics_from 去掉不存在的 {'、'.join(bad) or '空项'}", "contract.metrics_from", - before, keep) + return _auto(f"从出具契约的「指标来自」中去掉不存在的{'、'.join(map(q, bad)) or '空项'}", + "contract.metrics_from", before, keep) return _cards_choice(ctx, node, before, "contract.metrics_from") @@ -181,11 +182,11 @@ def _reports_choice(ctx: _Ctx, node: GraphNode, before: Any) -> dict[str, Any]: field = "contract.report_from" reports = ctx.upstream(node.id, NodeType.REPORT) if len(reports) == 1: - return _auto(f"出具契约核对上游唯一的「报告撰写」节点「{reports[0].title}」的文档(report_from)", field, + return _auto(f"出具契约的「报告来自」设为上游唯一的「报告撰写」节点「{reports[0].title}」", field, before, reports[0].id) if reports: - return _choice("选出具契约核对哪个「报告撰写」节点的文档(report_from)", field, _node_options(reports)) - return _assist("出口上游没有「报告撰写」节点:要在出口前面加一个,出具契约才有文档可核对", field) + return _choice("选择出具契约的「报告来自」:核对哪个「报告撰写」节点的文档", field, _node_options(reports)) + return _assist("成果节点上游没有「报告撰写」节点:需要在成果节点之前添加一个,出具契约才有文档可核对", field) def _plan_report_from_missing(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: @@ -213,10 +214,10 @@ def _plan_exit_fields(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) if not bad: return None named = [f"「{name}」" for _, name, _ in bad if name is not None] - action = f"把成果字段{'、'.join(named)}改成取" if named else "给出口配一个成果字段 result,取" + action = f"把成果字段{'、'.join(named)}改为取" if named else "为成果节点添加成果字段 result,取" reports = ctx.upstream(node.id, NodeType.REPORT) if not reports: - return _assist(f"「{node.title}」上游没有报告撰写节点:要在出口前面加一个,{action}它的正文", "fields") + return _assist(f"「{node.title}」上游没有报告撰写节点:需要在成果节点之前添加一个,{action}它的正文", "fields") options = [{**o, "hint": f"{o['hint']} · {_report_text(o['value'])}"} for o in _node_options(reports)] pinned = _contract(node).get("report_from") default = pinned if pinned in {r.id for r in reports} else reports[0].id if len(reports) == 1 else None @@ -243,7 +244,8 @@ def _plan_report_policy(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None keys = list(writes) preview = ({"field": keys[0], "before": before[keys[0]], "after": writes[keys[0]]} if len(keys) == 1 else {"field": "、".join(keys), "before": before, "after": writes}) - return {"kind": "auto", "label": f"给「{node.title}」写明 " + "、".join(f"{k}: {v}" for k, v in writes.items()), + said = "、".join(f"「{field_label(k)}」设为「{option_label(k, v)}」" for k, v in writes.items()) + return {"kind": "auto", "label": f"将「{node.title}」的{said}", "field": keys[0], "preview": preview, "_set": writes} @@ -254,11 +256,12 @@ def _plan_claims(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> di return None before = node.config.get("claims") if ctx.level == "governed": - return _auto(f"把「{node.title}」的 claims 改成 require_citation:受管出具要求每句结论挂引用", "claims", - before, "require_citation") - hints = {"off": "结论句不参与判档,和以前一样", "require_citation": "没挂引用的结论句计入缺口,按出具档位降档"} - options = [{"value": v, "label": v, "hint": hints[v]} for v in REPORT_CLAIMS] - return _choice(f"选「{node.title}」的结论句策略(claims)", "claims", options) + return _auto(f"将「{node.title}」的「{field_label('claims')}」改为「{option_label('claims', 'require_citation')}」:" + "受管级别出具要求每句结论挂依据", "claims", before, "require_citation") + # value 是配置里的枚举值,label 和节点检查器的选项文字一致 + hints = {"off": "结论句未附依据也不影响出具档位", "require_citation": "未附依据的结论句计入缺口"} + options = [{"value": v, "label": CHOICE_LABEL["claims"][v], "hint": hints[v]} for v in REPORT_CLAIMS] + return _choice(f"选择「{node.title}」的「{field_label('claims')}」如何处理", "claims", options) def _plan_judge_budget(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: @@ -275,25 +278,29 @@ def _plan_judge_budget(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) base = copy.deepcopy(judge) if isinstance(judge, dict) else {} amount = JUDGE_DEFAULTS["report_max_cost_usd"] options = [ - {"value": amount, "label": f"每份报告最多 ${amount:g}", "hint": "系统默认的每份报告上限;写进节点以后,改设置不影响这份报告"}, - {"value": None, "label": "不限(写 null)", "hint": JUDGE_UNLIMITED}, + {"value": amount, "label": f"每份报告最多 ${amount:.2f}", "hint": "系统默认的每份报告上限;写入节点后,修改设置不影响这份报告"}, + {"value": None, "label": "不限", "hint": JUDGE_UNLIMITED}, ] - return _choice(f"给「{node.title}」的结论句裁判写每份报告的预算(judge.max_cost_usd)", "judge.max_cost_usd", + return _choice(f"为「{node.title}」的结论句裁判设置每份报告的金额上限", "judge.max_cost_usd", options, _judge=base) +#: 「交给助手」候选的说明 +_ASSIST_PREVIEW = "助手的修改同样只是预览,需要你决定的事项会交给你确认" + + def _plan_cells_undeclared(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: """没有口径卡的受管图没写 cells:报告里的数要么直接引用查询单元格(写 cells: true),要么登记成口径卡 指标(交给 Copilot 加卡、改引用)。受管级别打开 cells 要作者显式决定,所以只给选项,不替人选。""" if node is None: return None options = [ - {"value": True, "label": "写 cells: true(保留单元格引用)", - "hint": "报告里的数直接点得开查询结果里的那一格,每一格都对照快照核对"}, - {"value": HANDOFF, "label": "交给 Copilot:加一张口径卡,把数登记成指标", - "hint": "Copilot 改的同样只是预览,要人拿主意的会原样问你", "handoff": True}, + {"value": True, "label": "开启「单元格引用」", + "hint": "报告中的数字可直接查看查询结果中的对应单元格,每个单元格都对照快照核对"}, + {"value": HANDOFF, "label": "交给助手:添加口径卡,把数字登记为指标", + "hint": _ASSIST_PREVIEW, "handoff": True}, ] - return _choice(f"「{node.title}」的报告只能引用查询单元格:写 cells: true,还是改成口径卡指标?", + return _choice(f"「{node.title}」的报告只能引用查询单元格:开启「单元格引用」,还是改为引用口径卡指标?", "contract.cells", options) @@ -303,34 +310,34 @@ def _plan_compute_input(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None if node is None: return None options = [ - {"value": "source", "label": "它在取数:标成 source(取数)", - "hint": "evidence_role = source,口径卡读它时记得下出处"}, - {"value": HANDOFF, "label": "它在做计算:交给 Copilot 把计算挪进口径卡", - "hint": "Copilot 改的同样只是预览,要人拿主意的会原样问你", "handoff": True}, + {"value": "source", "label": "负责取数:将「证据角色」设为「取数」", + "hint": "口径卡读取它时会记录出处"}, + {"value": HANDOFF, "label": "负责计算:交给助手把计算移到口径卡", + "hint": _ASSIST_PREVIEW, "handoff": True}, ] - return _choice(f"「{node.title}」的产出喂给了口径卡:它是在取数,还是在做计算?", "evidence_role", options) + return _choice(f"「{node.title}」的产出提供给了口径卡:它负责取数,还是负责计算?", "evidence_role", options) def _plan_cite_fields(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: if node is None: return None - return _auto(f"打开「{node.title}」的 cite_fields:每个字段都核对到查询结果里的那一格", "cite_fields", + return _auto(f"开启「{node.title}」的「按出处核对字段」:每个字段都核对到查询结果中的对应单元格", "cite_fields", node.config.get("cite_fields"), True) def _plan_agent_schema(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: - return _assist(f"给「{_title(node)}」配 output_schema:交哪些字段、什么类型要你或 Copilot 定,自动修复不替你编;" - "配好之后再开 cite_fields", "output_schema") + return _assist(f"为「{_title(node)}」配置「结构化输出 Schema」:输出哪些字段、字段类型需要由你或助手确定," + "自动修复不会代为填写;配置好后再开启「按出处核对字段」", "output_schema") def _plan_model_input(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: - return _assist(f"「{_title(node)}」写的数进了口径卡:要换成 Agent(配 output_schema、开 cite_fields)或「调用工具」" - "节点取数。修复不删节点,Copilot 会拟一个改法") + return _assist(f"「{_title(node)}」写的数字进入了口径卡:需要改用 Agent(配置「结构化输出 Schema」、开启" + "「按出处核对字段」)或「调用工具」节点取数。修复不会删除节点,助手会拟定一个修改方案") def _plan_text_bypass(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: - return _assist(f"「{_title(node)}」写的文字要改由报告撰写节点来写:在它和出口之间加一个报告撰写节点,出口改成取" - f"报告的正文。修复不删节点,「{_title(node)}」会留在图上") + return _assist(f"「{_title(node)}」写的文字需要改由报告撰写节点撰写:在它和成果节点之间添加一个报告撰写节点," + f"成果节点改为取报告的正文。修复不会删除节点,「{_title(node)}」会保留在工作流中") def _plan_report_from_invalid(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: @@ -350,7 +357,7 @@ def _plan_report_metrics_from(ctx: _Ctx, issue: dict[str, Any], node: GraphNode added = cards[0] if len(cards) == 1 and cards[0].id not in keep else None after = [*keep, *([added.id] if added else [])] bad = [str(s) for s in _as_list(before) if s not in keep and str(s).strip()] - label = f"「{node.title}」的 metrics_from " + (f"去掉无效的 {'、'.join(bad)}" if bad else "改成口径卡节点的 id 列表") + label = f"「{node.title}」的「指标来自」" + (f"去掉无效的{'、'.join(map(q, bad))}" if bad else "改为口径卡节点列表") return _auto(label + (f",补上上游唯一的口径卡「{added.title}」" if added else ""), "metrics_from", before, after) @@ -373,16 +380,16 @@ def _plan_required(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> if isinstance(s, str) and getattr(ctx.nodes.get(s), "type", None) == NodeType.METRICS] options = _metric_options(ctx, named or ctx.upstream(node.id, NodeType.METRICS)) if not options: - return _assist("列不出口径卡里的指标,没法给出 required 的候选", "contract.required") + return _assist("无法列出口径卡中的指标,因此无法提供「必需指标」的候选", "contract.required") # 不给默认:哪些指标缺了就不予出具,是作者的决定 - return _choice("选受管出具必需的指标(required):缺了其中任何一个就不予出具", "contract.required", options, + return _choice("选择受管级别出具的「必需指标」:缺少其中任何一个都将不予出具", "contract.required", options, multiple=True) def _plan_strict(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: if node is None: return None - return _auto("把出具契约设为 strict:没有出处的数字直接拦下,而不是只降档", "contract.strict", + return _auto("开启出具契约的「严格模式」:没有出处的数字直接拦截,而不只是降档", "contract.strict", _contract(node).get("strict"), True) @@ -394,14 +401,15 @@ def _plan_claims_ignored(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | Non claims = _contract(node).get("claims") if not isinstance(claims, dict): return None - return _auto("把出具契约 claims 的 on_uncited 改成 degrade:受管级别的正式运行本来就这么办,写法和实际一致", + return _auto(f"将出具契约的「{contract_label('on_uncited')}」改为「{option_label('on_uncited', 'degrade')}」,与受管级别正式运行的" + "实际处理保持一致", "contract.claims.on_uncited", claims.get("on_uncited"), "degrade") def _plan_approval(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: if node is None: return None - return _auto(f"把「{node.title}」的审批策略改成「仅危险工具需要审批」", "approval", node.config.get("approval"), + return _auto(f"将「{node.title}」的审批策略改为「{option_label('approval', 'dangerous')}」", "approval", node.config.get("approval"), "dangerous") @@ -409,7 +417,7 @@ def _plan_default_approval(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | N followers = [n.title for n in ctx.spec.nodes if n.type == NodeType.AGENT and n.config.get("tools") and n.config.get("approval") in (None, "")] who = "、".join(f"「{t}」" for t in followers[:3]) + (f" 等 {len(followers)} 个节点" if len(followers) > 3 else "") - return _auto(f"把全图默认的审批策略改成「仅危险工具需要审批」({who or '跟随它的节点'}一并生效)", + return _auto(f"将{field_label('defaults')}中的审批策略改为「{option_label('approval', 'dangerous')}」({who or '跟随默认设置的节点'}一并生效)", "defaults.approval", ctx.spec.defaults.get("approval"), "dangerous") @@ -419,32 +427,32 @@ def _plan_subgraph(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> wf = node.config.get("workflow_id") version = ctx.versions.get(wf) if wf else None if isinstance(version, int) and not isinstance(version, bool) and version > 0: - return _auto(f"把「{node.title}」钉到上游当前的发布版本 v{version}", "workflow_version", + return _auto(f"将「{node.title}」固定到上游当前的发布版本 v{version}", "workflow_version", node.config.get("workflow_version"), version) # 上游没发布过:不替人挑一个草稿版本钉上去 - return _assist(f"「{node.title}」嵌套的工作流还没有发布版本,没法替你钉:先发布它,或者请 Copilot 看看", + return _assist(f"「{node.title}」嵌套的工作流还没有发布版本,无法自动固定版本。请先发布该工作流,或交给助手处理", "workflow_version") def _plan_no_contract(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: if node is None: - return _assist("出口不止一个(或者没有出口),该给哪个出口写契约说不准") + return _assist("工作流中有多个成果节点(或没有成果节点),无法确定应为哪个节点生成出具契约") cards = ctx.upstream(node.id, NodeType.METRICS) reports = ctx.upstream(node.id, NodeType.REPORT) if len(cards) != 1 or len(reports) != 1: - return _assist(f"「{node.title}」上游的口径卡、报告撰写节点不是恰好各一个,契约该指向哪个说不准", "contract") + return _assist(f"「{node.title}」上游的口径卡和报告撰写节点不是各恰好一个,无法确定出具契约应指向哪个", "contract") options = _metric_options(ctx, cards) if not options: - return _assist(f"列不出口径卡「{cards[0].title}」里的指标,没法给出 required 的候选", "contract") - return _choice(f"给「{node.title}」生成出具契约:核对「{reports[0].title}」的文档,指标来自「{cards[0].title}」," - "再选出必需的指标(required)", "contract", options, multiple=True, + return _assist(f"无法列出口径卡「{cards[0].title}」中的指标,因此无法提供「必需指标」的候选", "contract") + return _choice(f"为「{node.title}」生成出具契约:核对「{reports[0].title}」的文档,指标来自「{cards[0].title}」," + "再选择「必需指标」", "contract", options, multiple=True, _skeleton={"report_from": reports[0].id, "metrics_from": [cards[0].id], "strict": True}) def _plan_supervisor(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: # 修复不许删节点、不许覆盖或换类型,Copilot 替换不了它,只能拟一个拆分方案交给人 - return _assist(f"「{_title(node)}」要换成固定编排的 Agent 或「模型调用」节点:修复不能删节点," - "Copilot 只会给出拆分建议,替换要你来做") + return _assist(f"「{_title(node)}」需要改为配置固定的 Agent 或「模型调用」节点:修复不能删除节点," + "助手只会给出拆分建议,替换需要由你完成") def _plan_not_object(ctx: _Ctx, issue: dict[str, Any], node: GraphNode | None) -> dict[str, Any] | None: @@ -671,12 +679,12 @@ def _chosen(fix: dict[str, Any], choices: dict[str, Any]) -> tuple[Any, str]: allowed = [o["value"] for o in fix.get("options") or []] if fix.get("multiple"): if not isinstance(value, list) or not value: - return None, f"至少选一个:{fix['label']}" + return None, f"请至少选择一项:{fix['label']}" if any(v not in allowed for v in value): - return None, f"选的 {'、'.join(str(v) for v in value if v not in allowed)} 不在候选里" + return None, f"所选的{'、'.join(q(v) for v in value if v not in allowed)}不在候选项中" return [v for v in allowed if v in value], "" if value not in allowed: - return None, f"选的 {value!r} 不在候选里" + return None, f"所选的「{value}」不在候选项中" return value, "" @@ -733,7 +741,7 @@ def apply_fixes(graph: dict[str, Any] | GraphSpec, fix_ids: list[str], choices: try: trial_spec = GraphSpec.model_validate(trial) except Exception: # noqa: BLE001 - 修复规则把图改坏了:丢弃,不交给人一张存不回去的图 - rejected.append({"fix_id": fid, "reason": "改完的图结构读不懂,这条修复已丢弃"}) + rejected.append({"fix_id": fid, "reason": "修复后的工作流结构无法解析,已放弃这项修复"}) continue trial_issues = publish_issues(trial_spec, level=level) # choice 里人亲手选的值不算「替人决定」(比如把沙箱代码标成取数);别的降低要求照样拦 @@ -793,9 +801,9 @@ def worse(before: list[Any], after: list[Any]) -> str | None: seen = {_sig(i) for i in b_err} new = [i for i in a_err if _sig(i) not in seen] if new: - return f"改完会冒出新的问题:{new[0].get('message')}" + return f"修改后出现了新的问题:{new[0].get('message')}" if len(a_err) > len(b_err): - return f"改完错误反而变多了({len(b_err)} → {len(a_err)})" + return f"修改后错误增加了({len(b_err)} → {len(a_err)})" return None @@ -819,11 +827,11 @@ def judge(before: list[Any], after: list[Any], *, target: tuple[str, str | None] still = [i for i in a if hit(i)] if still: - return f"改完这处问题还在:{still[0].get('message')}" + return f"修改后这一处问题仍然存在:{still[0].get('message')}" if not any(i.get("level") == "error" for i in b if hit(i)): return None if len(a_err) >= len(b_err): - return "改完错误没有变少" + return "修改后错误没有减少" return None @@ -846,9 +854,15 @@ def _name(node: dict[str, Any]) -> str: return str((node.get("data") or {}).get("label") or node.get("id")) +def _title_of(nodes: dict[str, dict[str, Any]], node_id: Any) -> str: + """节点 id 换成画布上的名字;图里没有这个节点时照写 id。给人看的拒绝理由里不写节点 id。""" + node = nodes.get(str(node_id)) + return _name(node) if node is not None else str(node_id) + + #: 审批策略从严到宽:每次调用都审批 > 仅危险工具需要审批 > 全部自动放行 _APPROVAL_RANK = {"never": 0, "dangerous": 1, "always": 2} -_APPROVAL_LABEL = {"never": "全部自动放行", "dangerous": "仅危险工具需要审批", "always": "每次调用都审批"} +_APPROVAL_LABEL = {k: option_label("approval", k) for k in _APPROVAL_RANK} def _approval(value: Any) -> str | None: @@ -876,14 +890,14 @@ def _approval_lowered(who: str, prev: str | None, now: str | None, *, inherited: return None if fallback in _APPROVAL_RANK and _APPROVAL_RANK[fallback] >= _APPROVAL_RANK.get(prev, 0): return None - return (f"去掉了{who}的审批策略(原来是{_approval_word(prev)}),会退回" - + (f"全图默认的{_approval_word(fallback)}" if fallback else "全局设置,可能是「全部自动放行」")) + return (f"删除了{who}的审批策略(原为{_approval_word(prev)}),将改为跟随" + + (f"{field_label('defaults')}中的{_approval_word(fallback)}" if fallback else f"全局设置,可能为「{option_label('approval', 'never')}」")) if now not in _APPROVAL_RANK: - return f"把{who}的审批策略改成了不认识的值 {now!r}" + return f"将{who}的审批策略改为无法识别的值「{now}」" base = prev if prev is not None else inherited if base in _APPROVAL_RANK and _APPROVAL_RANK[now] < _APPROVAL_RANK[base]: - was = _approval_word(base) + ("" if prev is not None else "(跟随全图默认)") - return f"把{who}的审批策略从{was}放宽成了{_approval_word(now)}" + was = _approval_word(base) + ("" if prev is not None else f"(跟随{field_label('defaults')})") + return f"将{who}的审批策略从{was}放宽为{_approval_word(now)}" return None @@ -902,21 +916,21 @@ def _contract_loosened(name: str, prior: Any, contract: Any, *, cells_chosen: bo had = set(_numbers(prior.get("allow_numbers"))) extra = [n for n in dict.fromkeys(_numbers(contract.get("allow_numbers"))) if n not in had] if extra: - out.append(f"往「{name}」出具契约的 allow_numbers 里加了 {'、'.join(extra)}(不带出处也能放行的数)") + out.append(f"在「{name}」出具契约的「{contract_label('allow_numbers')}」中新增了 {'、'.join(extra)}(这些数字无需出处即可通过)") if contract.get("cells") is True and prior.get("cells") is not True and not cells_chosen: - out.append(f"替你打开了「{name}」出具契约的 cells(允许报告直接引用查询单元格),这要你自己决定") + out.append(f"开启了「{name}」出具契约的「单元格引用」(允许报告直接引用查询单元格),这一项需要由你决定") was, now = _claims_rank(prior.get("claims")), _claims_rank(contract.get("claims")) if was is not None and now is not None: looser = [f"{what}{words[a]} → {words[b]}" for (what, words), a, b in zip(_CLAIMS_AXES, was, now) if b < a] if looser: - out.append(f"把「{name}」出具契约的 claims 往宽里改了({';'.join(looser)})") + out.append(f"放宽了「{name}」出具契约对结论句的要求({';'.join(looser)})") return out #: 契约 claims 的严格程度分两样,各自从宽到严:没挂依据的结论句(不查 < 查了不算缺口 ignore < 计入缺口降档 #: degrade < 不予出具 withhold),证据不支持的结论句(不裁判 < 裁判、降档 < 裁判、不予出具)。judge 两样都管: #: 挂依据的要求和 require_citation 一样,另外按裁判的判定判档 -_CLAIMS_AXES = (("没挂依据的结论句", ("不检查", "只标出来", "计入缺口", "不予出具")), +_CLAIMS_AXES = (("未附依据的结论句", ("不检查", "仅标注", "计入缺口", "不予出具")), ("证据不支持的结论句", ("不裁判", "降档出具", "不予出具"))) @@ -966,20 +980,20 @@ def forbidden_changes(before: dict[str, Any], after: dict[str, Any], for op in ops or []: kind = op.get("op") if kind == "remove_node": - reasons.append(f"想删节点「{op.get('id')}」") + reasons.append(f"删除节点「{_title_of(old, op.get('id'))}」") elif kind == "remove_edge": - reasons.append(f"想删连线 {op.get('source')} → {op.get('target')}") + reasons.append(f"删除连线「{_title_of(old, op.get('source'))}」→「{_title_of(old, op.get('target'))}」") elif kind == "add_node": # Copilot 的改图流程遇到已有的 id 会拿新节点整个盖掉旧的:配置、位置全丢,类型也可能换了 added = op.get("node") target = added.get("id") if isinstance(added, dict) else None if target is not None and str(target) in old: - reasons.append(f"想用新节点覆盖已有的「{_name(old[str(target)])}」(等于删了重建)") + reasons.append(f"用新节点覆盖已有的「{_name(old[str(target)])}」(等于删除后重建)") elif kind not in _GRAPH_OPS: - reasons.append(f"用了修复不许用的操作 {kind}(只能改节点配置、补节点和连线)") - reasons += [f"删了节点「{_name(n)}」" for nid, n in old.items() if nid not in new] + reasons.append(f"使用了修复不允许的操作 {kind}(只能修改节点配置、添加节点和连线)") + reasons += [f"删除了节点「{_name(n)}」" for nid, n in old.items() if nid not in new] kept = {_edge_key(e) for e in after.get("edges") or [] if isinstance(e, dict)} - reasons += [f"删了连线 {s} → {t}" for s, t, _ in + reasons += [f"删除了连线「{_title_of(old, s)}」→「{_title_of(old, t)}」" for s, t, _ in dict.fromkeys(_edge_key(e) for e in before.get("edges") or [] if isinstance(e, dict)) if (s, t, _) not in kept and (s, t) not in rewired] old_default = _approval((before.get("defaults") or {}).get("approval")) @@ -992,12 +1006,12 @@ def forbidden_changes(before: dict[str, Any], after: dict[str, Any], and (nid, str(was.get("type")), str(node.get("type"))) not in retyped: from app.engine.schema import type_label - reasons.append(f"把「{_name(was)}」从{_type_word(was.get('type'), type_label)}换成了" - f"{_type_word(node.get('type'), type_label)}(等于删了重建)") + reasons.append(f"将「{_name(was)}」从{_type_word(was.get('type'), type_label)}换成了" + f"{_type_word(node.get('type'), type_label)}(等于删除后重建)") approval, prior_approval = _approval(cfg.get("approval")), _approval(prev.get("approval")) if approval == "never" and prior_approval != "never": - reasons.append(f"把「{name}」的审批策略改成了「全部自动放行」" if was - else f"新加的「{name}」审批策略是「全部自动放行」") + reasons.append(f"将「{name}」的审批策略改为「{option_label('approval', 'never')}」" if was + else f"新增的「{name}」审批策略为「{option_label('approval', 'never')}」") elif why := _approval_lowered(f"「{name}」", prior_approval, approval, inherited=old_default, fallback=new_default): reasons.append(why) @@ -1005,34 +1019,34 @@ def forbidden_changes(before: dict[str, Any], after: dict[str, Any], reasons += _contract_loosened(name, prior, contract, cells_chosen=(nid, "contract.cells") in chosen) if node.get("type") == "code" and cfg.get("evidence_role") == "source" \ and prev.get("evidence_role") != "source" and (nid, "evidence_role") not in chosen: - reasons.append((f"替你把「{name}」标成了取数(evidence_role: source)" if was - else f"新加的「{name}」标成了取数(evidence_role: source)") - + ",它是在取数还是在算要你自己决定") + reasons.append((f"将「{name}」的「证据角色」设为「取数」" if was + else f"新增的「{name}」的「证据角色」为「取数」") + + ":它负责取数还是计算需要由你决定") if was is None: continue if was.get("type") == node.get("type") == "report": reasons += _report_loosened(name, prev, cfg, before.get("defaults"), after.get("defaults")) if was.get("type") == node.get("type") == "agent" and prev.get("cite_fields") is True \ and cfg.get("cite_fields") is not True: - reasons.append(f"关掉了「{name}」的 cite_fields(字段不再逐个核对到查询结果)") + reasons.append(f"关闭了「{name}」的「按出处核对字段」(字段不再逐一核对到查询结果)") elif was.get("type") == node.get("type") == "agent" and prev.get("cite_fields") is True \ and prev.get("output_schema") and not cfg.get("output_schema"): - reasons.append(f"删掉了「{name}」的 output_schema(cite_fields 随之失效,字段不再逐个核对到查询结果)") + reasons.append(f"删除了「{name}」的「结构化输出 Schema」(「按出处核对字段」随之失效,字段不再逐一核对到查询结果)") if prev.get("workflow_version") and not cfg.get("workflow_version"): - reasons.append(f"取消了「{name}」钉住的版本") + reasons.append(f"取消了「{name}」固定的版本") if not isinstance(prior, dict) or not prior: continue if not isinstance(contract, dict) or not contract: - reasons.append(f"删掉或清空了「{name}」的出具契约") + reasons.append(f"删除或清空了「{name}」的出具契约") continue if prior.get("strict") and not contract.get("strict"): - reasons.append(f"把「{name}」出具契约的 strict 改成了 false") + reasons.append(f"关闭了「{name}」出具契约的「严格模式」") dropped = [m for m in _as_list(prior.get("required")) if m not in _as_list(contract.get("required"))] if dropped: - reasons.append(f"删掉了「{name}」出具契约 required 里的 {'、'.join(map(str, dropped))}") + reasons.append(f"从「{name}」出具契约的「必需指标」中删除了 {'、'.join(map(str, dropped))}") if new_default == "never" and old_default != "never": - reasons.append("把全图默认的审批策略改成了「全部自动放行」") - elif why := _approval_lowered("全图默认", old_default, new_default, inherited=None, fallback=None): + reasons.append(f"将{field_label('defaults')}中的审批策略改为「{option_label('approval', 'never')}」") + elif why := _approval_lowered(field_label("defaults"), old_default, new_default, inherited=None, fallback=None): reasons.append(why) return reasons @@ -1064,14 +1078,14 @@ def _report_loosened(name: str, prev: dict[str, Any], cfg: dict[str, Any], old_d if was not in _CLAIMS_ORDER or (was == "off" and now not in _CLAIMS_ORDER): continue if now not in _CLAIMS_ORDER: - out.append(f"把「{name}」的 claims 从 {was} 改成了不认识的 {now}") + out.append(f"将「{name}」的「{field_label('claims')}」从「{option_label('claims', was)}」改为无法识别的「{now}」") continue if _CLAIMS_ORDER.index(now) >= _CLAIMS_ORDER.index(was): continue elif not (was == strict and now != strict): continue - out.append(f"把「{name}」的 {key} 从 {was} 放宽成了 {now}" - + ("(去掉了写明的值,运行时退回缺省)" if cfg.get(key) in (None, "") else "")) + out.append(f"将「{name}」的「{field_label(key)}」从「{option_label(key, was)}」放宽为「{option_label(key, now)}」" + + ("(删除了已设置的值,运行时改用默认值)" if cfg.get(key) in (None, "") else "")) if effective(prev, old_defaults, "claims", "off") == effective(cfg, new_defaults, "claims", "off") \ == CLAIMS_JUDGE and (why := _judge_loosened(name, prev, cfg, old_defaults, new_defaults)): out.append(why) @@ -1096,18 +1110,22 @@ def _judge_loosened(name: str, prev: dict[str, Any], cfg: dict[str, Any], old_de (old_block, old_inherited), (new_block, new_inherited) = block(prev, old_defaults), block(cfg, new_defaults) if written(old_block) != "withhold" or (raw := written(new_block)) == "withhold": return None - was = "withhold" + ("(跟随全图默认)" if old_inherited else "") + def said(value: str) -> str: + return f"「{option_label('on_unsupported', value)}」" + + was = said("withhold") + (f"(跟随{field_label('defaults')})" if old_inherited else "") if raw in JUDGE_ON_UNSUPPORTED: - now = f"{raw}" + ("(跟随全图默认)" if new_inherited else "") + now = said(raw) + (f"(跟随{field_label('defaults')})" if new_inherited else "") elif raw not in (None, ""): - now = f"认不出的 {raw}(运行时按 degrade)" + now = f"无法识别的「{raw}」(运行时按{said('degrade')}处理)" elif new_inherited: - now = "degrade(跟随全图默认,那里没写 on_unsupported,运行时退回缺省)" + now = said("degrade") + f"(跟随{field_label('defaults')};其中未设置此项,运行时使用默认值)" elif old_inherited: - now = "degrade(节点上另写了 judge,整个用节点的、不再跟随全图默认,没写 on_unsupported 就退回缺省)" + now = said("degrade") + (f"(节点上另行设置了{field_label('judge')},将整体使用节点的设置、不再跟随" + f"{field_label('defaults')};节点未设置此项,运行时使用默认值)") else: - now = "degrade(去掉了写明的值,运行时退回缺省)" - return f"把「{name}」的 judge.on_unsupported 从 {was}{'' if old_inherited else ' '}放宽成了 {now}" + now = said("degrade") + "(删除了已设置的值,运行时使用默认值)" + return f"将「{name}」的「{field_label('judge.on_unsupported')}」从{was}放宽为{now}" def _type_word(node_type: Any, type_label: Callable[[Any], str]) -> str: @@ -1126,7 +1144,7 @@ def diff_changes(before: dict[str, Any], after: dict[str, Any], *, fix_id: str, if was is None: out.append({"fix_id": fix_id, "node_id": nid, "node_title": _name(node), "field": None, "before": None, "after": {"type": node.get("type"), "config": copy.deepcopy(_cfg(node))}, - "label": f"{label}:新加节点"}) + "label": f"{label}:新增节点"}) continue if was.get("type") != node.get("type"): # forbidden_changes 现在就拒掉换类型;万一哪天放行,预览里也得看得出节点换了类型 @@ -1146,5 +1164,5 @@ def diff_changes(before: dict[str, Any], after: dict[str, Any], *, fix_id: str, if isinstance(edge, dict) and _edge_key(edge) not in known: out.append({"fix_id": fix_id, "node_id": None, "node_title": "", "field": "edge", "before": None, "after": {"source": edge.get("source"), "target": edge.get("target"), - "sourceHandle": edge.get("sourceHandle")}, "label": f"{label}:新加连线"}) + "sourceHandle": edge.get("sourceHandle")}, "label": f"{label}:新增连线"}) return out diff --git a/backend/app/engine/compiler.py b/backend/app/engine/compiler.py index 5df9de17..07c70658 100644 --- a/backend/app/engine/compiler.py +++ b/backend/app/engine/compiler.py @@ -55,7 +55,7 @@ def _wrap( async def _execute(state: GraphState) -> dict[str, Any]: if runner is None: - raise NodeError(node.id, f"没有实现的节点类型:{node.type}") + raise NodeError(node.id, f"不支持的节点类型:{node.type}") # 允许节点配置跳过条件,不用为了"有时不执行"专门加一个分支节点 skip_if = node.config.get("skip_if") @@ -65,7 +65,7 @@ def _wrap( if eval_condition(skip_if, template_context(state)): ctx.emit(EventType.NODE_SKIPPED, node_type=str(node.type), label=node.title, - reason=f"skip_if 成立:{skip_if}") + reason=f"满足跳过条件:{skip_if}") return {"nodes": {node.id: {"skipped": True}}} retries = int(node.config.get("retries", 0) or 0) @@ -141,7 +141,7 @@ def _wrap( ctx.emit( EventType.LOG, level="warn", - message=f"第 {attempt + 1} 次失败({_describe(e)}),准备重试", + message=f"第 {attempt + 1} 次执行失败({_describe(e)}),即将重试", code="node_retry", ) await asyncio.sleep(backoff * (2**attempt)) @@ -325,7 +325,7 @@ def compile_graph(spec: GraphSpec, run_ctx: RunContext) -> StateGraph: # 入口 entries = spec.entry_nodes() if not entries: - raise ValueError("这个工作流没有入口节点") + raise ValueError("工作流没有起始节点") for node in entries: builder.add_edge(START, node.id) diff --git a/backend/app/engine/evidence.py b/backend/app/engine/evidence.py index 2b497848..2e2965c3 100644 --- a/backend/app/engine/evidence.py +++ b/backend/app/engine/evidence.py @@ -51,6 +51,7 @@ from app.core.artifact_store import canonical_json, content_hash from app.core.artifact_store import load as load_artifact from app.engine.expressions import CellError, cell_value, column_kind, locate_cell from app.engine.issuance import _tolerance, extract_numbers, number_allowance +from app.engine.labels import option_label DOC_SCHEMA = "agentlab.report/1" @@ -460,7 +461,7 @@ def is_number(value: Any) -> bool: def _decimal(value: int | float) -> Decimal: if isinstance(value, float): if not math.isfinite(value): - raise RenderError(f"{value} 不是一个有限的数") + raise RenderError(f"{value} 不是有限的数值") return Decimal(repr(value)) return Decimal(value) @@ -490,7 +491,7 @@ def _digits(d: Decimal, places: int | None, *, group: bool, strip: bool = False, ctx = _ctx(d, -exp) q = d.quantize(Decimal(1).scaleb(exp), context=ctx) if q.is_zero() and not d.is_zero(): - raise RenderError(zero or f"{_shown(d)} 按 {-exp} 位小数显示为 0,看不出真实的值") + raise RenderError(zero or f"{_shown(d)} 按 {-exp} 位小数显示为 0,无法看出真实的值") if places is None or strip: q = q.normalize(context=ctx) if q.is_zero(): @@ -527,43 +528,43 @@ def render_number( """ fmt = fmt or DEFAULT_FORMAT if fmt not in FORMATS: - raise RenderError(f"format 只能是 {' / '.join(FORMATS)},写的是 {fmt!r}") + raise RenderError(f"显示格式只能是 {' / '.join(FORMATS)},当前为「{fmt}」") if value is None: return MISSING if not is_number(value): if conv: - raise RenderError(f"「{_clean(str(value))[:40]}」不是数,不能换算成 {conv}") + raise RenderError(f"「{_clean(str(value))[:40]}」不是数值,不能换算为「{conv}」") if isinstance(value, bool): return "是" if value else "否" return _clean(str(value)) if decimals is not None and (isinstance(decimals, bool) or not isinstance(decimals, int) or not -MAX_PLACES <= decimals <= MAX_PLACES): - raise RenderError(f"小数位要是 -{MAX_PLACES} 到 {MAX_PLACES} 的整数,写的是 {decimals!r}") + raise RenderError(f"小数位需要是 -{MAX_PLACES} 到 {MAX_PLACES} 的整数,当前为「{decimals}」") try: return _render_numeric(_decimal(value), unit=unit, decimals=decimals, fmt=fmt, conv=conv) except RenderError: raise except (ArithmeticError, ValueError) as e: # decimal 的 InvalidOperation 也在这里 - raise RenderError(f"{value!r} 按规则渲染不出来({type(e).__name__})") from e + raise RenderError(f"「{value}」无法按规则显示") from e def _render_numeric(d: Decimal, *, unit: str, decimals: int | None, fmt: str, conv: str | None) -> str: if d.adjusted() >= _MAX_DIGITS: - raise RenderError(f"这个数有 {d.adjusted() + 1} 位,太大了,没法按规则显示") + raise RenderError(f"该数值有 {d.adjusted() + 1} 位,超出可显示的范围") ratio = fmt == "percent_of_ratio" group = fmt != "plain" shown = _shown(d) if conv in _CONV_SCALE: if ratio: - raise RenderError(f"这个指标是比率,不能换算成 {conv}") + raise RenderError(f"该指标是比率,不能换算为「{conv}」") scaled = _ctx(d).divide(d, _CONV_SCALE[conv]) return _digits(scaled, 2, group=True, strip=True, - zero=f"{shown} 换算成「{conv}」后显示为 0,精度不够:去掉换算,或者换小一级的单位" + zero=f"{shown} 换算为「{conv}」后显示为 0,精度不够:请去掉换算,或换用小一级的单位" ) + conv + unit - rounded = f"{shown} 按 |{conv} 显示为 0,精度不够:去掉换算,或者换成 |.N 多留几位小数" + rounded = f"{shown} 按 |{conv} 显示为 0,精度不够:请去掉换算,或改用 |.N 多保留几位小数" if conv == "pct": if "%" in unit or "%" in unit: - raise RenderError("这个指标本身就是百分数(单位是 %),不能再换算成 pct") + raise RenderError("该指标本身是百分数(单位为 %),不能再换算为 pct") places = max(decimals - 2, 0) if decimals is not None else 1 return _digits(_ctx(d).multiply(d, 100), places, group=group, zero=rounded) + "%" @@ -572,11 +573,11 @@ def _render_numeric(d: Decimal, *, unit: str, decimals: int | None, fmt: str, co elif conv and (m := _CONV_PLACES.match(conv)): places = int(m.group(1)) elif conv: - raise RenderError(f"不认识的换算 |{conv},只支持 万 / 亿 / pct / int / .N(N 为 0–6)") + raise RenderError(f"无法识别的换算 |{conv},只支持 万 / 亿 / pct / int / .N(N 为 0–6)") else: - rounded = (f"{shown} 按口径卡的小数位({decimals})显示为 0,精度不够:口径卡要多留几位小数" + rounded = (f"{shown} 按口径卡的小数位({decimals})显示为 0,精度不够:请在口径卡中增加小数位" if decimals is not None else - f"{shown} 太小:不写小数位时最多留 10 位小数,显示为 0。口径卡要写 decimals") + f"{shown} 太小:未设置小数位时最多保留 10 位小数,显示为 0。请在口径卡中设置小数位") places = (max(decimals - 2, 0) if ratio else decimals) if decimals is not None else None if ratio: return _digits(_ctx(d).multiply(d, 100), places, group=group, zero=rounded) + "%" @@ -611,7 +612,7 @@ def render_cell(value: Any, conv: str | None = None, *, kind: str | None = None) except RenderError: raise except (ArithmeticError, ValueError) as e: - raise RenderError(f"{value!r} 按规则渲染不出来({type(e).__name__})") from e + raise RenderError(f"「{value}」无法按规则显示") from e if isinstance(value, (dict, list)): value = json.dumps(value, ensure_ascii=False, default=str) return render_number(value, fmt=DEFAULT_FORMAT, conv=conv).replace("|", "¦") @@ -634,13 +635,43 @@ MARKER_RE = re.compile( SUPPORTED_KINDS = frozenset({"m", "i", "see", "v", "table", "t", "c", "q"}) #: 三期起没有「以后才支持」的标记了;留着这个名字给老代码 import LATER_KINDS: frozenset[str] = frozenset() -#: 这次运行没冻结表结构(没查过库、升级前的运行)时,t / c 仍按一期判为解析不了,原因还是这一句 -LATER_REASON = "这种引用在后续版本支持" +#: 这次运行没冻结表结构(没查过库、升级前的运行)时,t / c 仍按一期判为解析不了,原因是这一句 +LATER_REASON = "本次运行没有记录表结构,无法核对表名和字段名" +#: 升级前(二期)组装的文档里存的原因原文。只拿来认出那样的老文档(_phase_two_cite),不再显示给人: +#: 它说的是「以后才支持」,而那份文档真正的情况是生成于升级前 +LEGACY_LATER_REASON = "这种引用在后续版本支持" +#: 认出二期文档后显示的原因 +PHASE_TWO_REASON = "这份报告生成于系统升级前,当时不解析这类引用" #: 沙箱代码节点的产出不能直接引用:它能做任意计算,那种数要进口径卡、留下代入式 -CODE_REASON = "沙箱算出来的数要进口径卡" +CODE_REASON = "沙箱代码计算出的数字不能直接引用,需先登记到口径卡" #: 受管级别的正式出具,契约里没写 "cells": true 时复核按这个原因拒掉单元格引用 -CELLS_REASON = "受管出具要在契约里声明 cells" -NODE_FIELD_REASON = "节点字段引用在后续版本支持:数要从查询单元格 [[v:Q1.r0.列]] 或口径卡指标 [[m:…]] 来" +CELLS_REASON = "受管级别出具需要在出具契约中开启「单元格引用」" +#: 节点字段引用:给人看的原因,和交回写作者改写时的指令(_Reason 的 fix) +NODE_FIELD_REASON = "不支持引用节点字段:数字需来自查询单元格或口径卡指标" +NODE_FIELD_FIX = "节点字段引用在后续版本支持:数要从查询单元格 [[v:Q1.r0.列]] 或口径卡指标 [[m:…]] 来" + + +class _Reason(str): + """解析不了的原因、核对出的问题:字面是给人看的一句话(证据面板、出具横幅、节点报错都显示它), + fix 是交回写作者(模型)改写时用的指令,照旧写明标记该怎么写(存成 for_model,describe_violations 用它)。 + + 两者共用一个字段时,写给模型的「单元格要写成 Q<编号>.r<行>.<列>」「别凭空猜」原样显示在界面上。 + 用 str 的子类,是为了让原来传字符串的地方(_unresolved、_violation 的 message)不用改签名。 + """ + + fix: str + + def __new__(cls, text: str, fix: str) -> "_Reason": + obj = super().__new__(cls, text) + obj.fix = fix + return obj + + +def _fix_of(reason: Any) -> dict[str, str]: + """{"for_model": 给模型的指令};原因本身就是给模型的那句(没有另写)时为空。键不叫 fix:前端的问题条目里 + fix 是修复 id。""" + fix = getattr(reason, "fix", None) + return {"for_model": fix} if fix and fix != str(reason) else {} #: 整表:不写 rows 时取前几行、最多几行、不写 cols 时最多几列 TABLE_DEFAULT_ROWS = 5 TABLE_MAX_ROWS = 20 @@ -794,7 +825,7 @@ def build_catalog( "alias": f"N:{node_id}", "kind": "node_output", "eid": make_eid("node_output", entry.get("artifact"), {}), "locator": {}, "code": True, **{k: entry[k] for k in ("node_id", "exec", "artifact", "code_sha", "role", "language") if k in entry}, - "label": f"沙箱代码 {node_id}({entry.get('role') or 'compute'})", + "label": f"沙箱代码 {node_id}({option_label('evidence_role', entry.get('role') or 'compute')})", } continue if entry.get("kind") == "query": @@ -837,12 +868,14 @@ def build_catalog( # -------------------------------------------------------------------------- ENTITY_KINDS = frozenset({"table", "column"}) -UNKNOWN_ENTITY_REASON = "本次运行的表结构快照、查询用到的表、查询结果列里都没有这个名字,可能是编造的名字" +UNKNOWN_ENTITY_REASON = "疑似不存在的名称:本次运行的表结构快照、查询用到的表和查询结果列中都没有这个名称" +#: 交回写作者(模型)改写时说的那句,保留原来给模型的写法 +_UNKNOWN_ENTITY_FOR_MODEL = "本次运行的表结构快照、查询用到的表、查询结果列里都没有这个名字,可能是编造的名字" #: 表结构快照不全(库里的表太多、只存了一部分)时找不到的名字:可能在没存下来的表里,只能说核对不了 -UNVERIFIED_ENTITY_REASON = ("这个数据源的表太多,表结构快照只存了一部分,查询用到的表、查询结果列里也没有这个名字," - "核对不了它存不存在") +UNVERIFIED_ENTITY_REASON = "表结构快照仅包含部分表,查询用到的表和查询结果列中也没有这个名称,无法核实它是否存在" #: 报告节点写了 entities: off:作者有意关掉了表名、字段名核对 -ENTITIES_OFF_REASON = "这个报告节点关掉了表名、字段名核对(entities: off),[[t:]] / [[c:]] 不解析:直接写名字就行" +ENTITIES_OFF_REASON = "该报告节点已关闭表名、字段名核对,相关标记不会解析" +ENTITIES_OFF_FIX = "这个报告节点关掉了表名、字段名核对(entities: off),[[t:]] / [[c:]] 不解析:直接写名字就行" def _add_origin(entry: dict[str, Any], origin: dict[str, Any]) -> None: @@ -1064,10 +1097,11 @@ def closest_entities(name: str, catalog: dict[str, Any], *, limit: int = 3) -> l def _unresolved(marker: dict[str, Any], alias: str, ev_kind: str, reason: str, *, rendered: str | None = None) -> dict[str, Any]: - """解析不了的引用。rendered 是正文里显示的字:缺值显示「—」,其余是占位 ⟦?m:gmvx⟧。""" + """解析不了的引用。rendered 是正文里显示的字:缺值显示「—」,其余是占位 ⟦?m:gmvx⟧。 + reason 是 _Reason 时另记 for_model(给模型的改写指令);存进文档前去掉(_stored)。""" kind, body = marker["kind"], marker.get("body", "") return {"ref": marker.get("ref") or "", "alias": alias, "kind": ev_kind, - "role": _ROLE.get(kind, "value"), "status": "unresolved", "reason": reason, + "role": _ROLE.get(kind, "value"), "status": "unresolved", "reason": str(reason), **_fix_of(reason), "rendered": rendered if rendered is not None else placeholder(kind, body)} @@ -1077,9 +1111,10 @@ def _metric_alias(ref: str, catalog: dict[str, Any]) -> tuple[str | None, str]: return alias, "" doubles = sorted(a for a in catalog if a.startswith("m:") and a.endswith(f".{ref}")) if doubles: - return None, (f"指标 {ref} 同时出现在好几张口径卡里,要写成带卡名的形式:" - + "、".join(f"[[{a}]]" for a in doubles[:4])) - return None, f"目录里没有指标 {ref}(能用的指标见证据目录)" + return None, _Reason(f"指标「{ref}」同时出现在多张口径卡中,无法确定引用的是哪一个", + f"指标 {ref} 同时出现在好几张口径卡里,要写成带卡名的形式:" + + "、".join(f"[[{a}]]" for a in doubles[:4])) + return None, _Reason(f"引用的指标「{ref}」不存在", f"目录里没有指标 {ref}(能用的指标见证据目录)") # -------------------------------------------------------------------------- @@ -1135,10 +1170,10 @@ class _Snapshots: if problem == "missing": return None, f"没有{noun}" if problem == "tampered": - return None, f"的{noun}和哈希对不上,疑似被改过" + return None, f"的{noun}与哈希不一致,疑似被修改" if problem == "absent": - return None, f"的{noun}取不回来(工件 {key[:12]}… 不存在)" - return None, f"的{noun}取不回来({problem})" + return None, f"的{noun}已不存在,无法读取" + return None, f"的{noun}无法读取" def _load(self, artifact: str) -> tuple[Any, str | None]: if not artifact: @@ -1169,7 +1204,7 @@ def parse_cell_ref(ref: str) -> dict[str, Any] | None: def _query_entry(alias: str, catalog: dict[str, Any]) -> tuple[dict[str, Any] | None, str]: entry = catalog.get(alias) if entry is None: - return None, f"目录里没有 {alias}(能引用的查询见证据目录)" + return None, _Reason(f"引用的查询结果 {alias} 不存在", f"目录里没有 {alias}(能引用的查询见证据目录)") if entry.get("kind") != "query": return None, f"{alias} 不是查询结果,不能按单元格引用" if entry.get("code"): @@ -1185,11 +1220,12 @@ def _resolve_cell(marker: dict[str, Any], catalog: dict[str, Any], snaps: _Snaps if node: alias = f"N:{node.group('node')}" entry = catalog.get(alias) or {} - return _unresolved(marker, alias, "node_field", CODE_REASON if entry.get("code") else NODE_FIELD_REASON) + return _unresolved(marker, alias, "node_field", + CODE_REASON if entry.get("code") else _Reason(NODE_FIELD_REASON, NODE_FIELD_FIX)) parsed = parse_cell_ref(ref) if parsed is None: - return _unresolved(marker, ref.split(".")[0], "cell", - "单元格要写成 Q<编号>.r<行>.<列>(行号从 0 数),比如 [[v:Q1.r0.amount]]") + return _unresolved(marker, ref.split(".")[0], "cell", _Reason( + "单元格引用格式无法识别", "单元格要写成 Q<编号>.r<行>.<列>(行号从 0 数),比如 [[v:Q1.r0.amount]]")) alias = parsed["alias"] if not cells_allowed: return _unresolved(marker, alias, "cell", CELLS_REASON) @@ -1231,15 +1267,15 @@ def _table_plan(marker: dict[str, Any], catalog: dict[str, Any], snaps: _Snapsho """ alias = marker.get("ref") or "" - def fail(reason: str) -> tuple[None, dict[str, Any]]: - return None, _unresolved(marker, alias, "query", reason) + def fail(reason: str, fix: str | None = None) -> tuple[None, dict[str, Any]]: + return None, _unresolved(marker, alias, "query", _Reason(reason, fix) if fix else reason) if not cells_allowed: return fail(CELLS_REASON) _, *rest = (marker.get("body") or "").split() or [""] odd = [p for p in rest if p.partition("=")[0] not in _TABLE_OPTIONS or "=" not in p] if odd: - return fail(f"不认识的选项 {odd[0]}:整表只支持 cols=列a,列b 和 rows=0-4") + return fail(f"整表引用中有无法识别的选项「{odd[0]}」", f"不认识的选项 {odd[0]}:整表只支持 cols=列a,列b 和 rows=0-4") options = marker.get("options") or {} entry, why = _query_entry(alias, catalog) if entry is None: @@ -1252,36 +1288,42 @@ def _table_plan(marker: dict[str, Any], catalog: dict[str, Any], snaps: _Snapsho if "cols" in options: wanted = [c.strip() for c in options["cols"].split(",") if c.strip()] if not wanted: - return fail("cols= 后面要写列名,用逗号分开") + return fail("整表引用的 cols 没有写列名", "cols= 后面要写列名,用逗号分开") missing = [c for c in wanted if c not in columns] if missing: - return fail(f"{alias} 没有列「{missing[0]}」,有:{'、'.join(columns[:12])}") + return fail(f"引用的查询结果 {alias} 中没有列「{missing[0]}」", + f"{alias} 没有列「{missing[0]}」,有:{'、'.join(columns[:12])}") if len(wanted) > TABLE_MAX_COLS: - return fail(f"整表最多 {TABLE_MAX_COLS} 列,cols= 写了 {len(wanted)} 列") + return fail(f"整表最多 {TABLE_MAX_COLS} 列,当前选了 {len(wanted)} 列", + f"整表最多 {TABLE_MAX_COLS} 列,cols= 写了 {len(wanted)} 列") else: wanted = columns if len(wanted) > TABLE_MAX_COLS: - return fail(f"{alias} 有 {len(columns)} 列,整表最多 {TABLE_MAX_COLS} 列:用 cols=列a,列b 挑出要的列") + return fail(f"{alias} 有 {len(columns)} 列,超过整表上限 {TABLE_MAX_COLS} 列", + f"{alias} 有 {len(columns)} 列,整表最多 {TABLE_MAX_COLS} 列:用 cols=列a,列b 挑出要的列") if not wanted: - return fail(f"{alias} 没有列,列不出表") + return fail(f"{alias} 没有列,无法生成表格") if not rows: - return fail(f"{alias} 是空的(0 行),没有可以列的行") + return fail(f"{alias} 为空(0 行),无法生成表格") if "rows" in options: span = _TABLE_ROWS.match(options["rows"].strip()) first, last = (int(span.group(1)), int(span.group(2) or span.group(1))) if span else (1, 0) if last < first: - return fail(f"rows 要写成 0-4 这样从小到大的行号范围(从 0 数),写的是 {options['rows']}") + return fail(f"整表引用的行号范围格式有误,当前为「{options['rows']}」", + f"rows 要写成 0-4 这样从小到大的行号范围(从 0 数),写的是 {options['rows']}") if last - first + 1 > TABLE_MAX_ROWS: - return fail(f"整表最多 {TABLE_MAX_ROWS} 行,rows={options['rows']} 是 {last - first + 1} 行:" + return fail(f"整表最多 {TABLE_MAX_ROWS} 行,当前选了 {last - first + 1} 行", + f"整表最多 {TABLE_MAX_ROWS} 行,rows={options['rows']} 是 {last - first + 1} 行:" "挑出要的行,或者分成几张表") if last >= len(rows): - return fail(f"{alias} 只有 {len(rows)} 行,没有第 {last} 行(从 0 数)") + return fail(f"{alias} 只有 {len(rows)} 行,没有第 {last} 行(行号从 0 开始)") else: first, last = 0, min(TABLE_DEFAULT_ROWS, len(rows)) - 1 for c in wanted: if not c.strip() or c != c.strip() or _UNSAFE_COLUMN.search(c) \ or len(f"[[v:{alias}.r{last}.{c}]]") > MARKER_MAX: - return fail(f"列名「{_clean(c)[:30]}」写不进表格(空的、首尾有空格、带方括号竖线换行,或者太长):" + return fail(f"列名「{_clean(c)[:30]}」无法放进表格(为空、首尾有空格、含方括号 / 竖线 / 换行,或过长)", + f"列名「{_clean(c)[:30]}」写不进表格(空的、首尾有空格、带方括号竖线换行,或者太长):" "在 SQL 里给它起个别名再查") lines = ["| " + " | ".join(_clean(c) for c in wanted) + " |", "| " + " | ".join("---" for _ in wanted) + " |"] @@ -1346,9 +1388,10 @@ def resolve_marker(marker: dict[str, Any], catalog: dict[str, Any], *, cells_all if kind == "q": return _resolve_quote(marker, catalog, _snapshots(loader)) if kind not in ("m", "i"): - return _unresolved(marker, f"{kind}:{ref}", kind, - f"不认识的引用类型 {kind}:只支持 m(口径卡指标)、v(查询单元格)、table(整表)、" - "i(运行输入)、t / c(表 / 字段)、q(引文)、see(依据)") + return _unresolved(marker, f"{kind}:{ref}", kind, _Reason( + f"引用类型「{kind}」无法识别", + f"不认识的引用类型 {kind}:只支持 m(口径卡指标)、v(查询单元格)、table(整表)、" + "i(运行输入)、t / c(表 / 字段)、q(引文)、see(依据)")) conv = marker.get("conv") if kind == "m": @@ -1358,8 +1401,8 @@ def resolve_marker(marker: dict[str, Any], catalog: dict[str, Any], *, cells_all return _unresolved(marker, f"m:{ref}", ev_kind, why) entry = catalog[alias] if entry.get("value") is None: - return _unresolved(marker, alias, ev_kind, f"指标「{entry.get('name') or ref}」这次没有值(缺输入)," - "不能写进报告", rendered=MISSING) + return _unresolved(marker, alias, ev_kind, f"指标「{entry.get('name') or ref}」本次没有值(缺少输入)," + "无法写入报告", rendered=MISSING) try: rendered = render_metric(entry, conv) except RenderError as e: @@ -1368,9 +1411,9 @@ def resolve_marker(marker: dict[str, Any], catalog: dict[str, Any], *, cells_all ev_kind, alias = "input", f"i:{ref}" entry = catalog.get(alias) if entry is None: - return _unresolved(marker, alias, ev_kind, f"运行输入里没有 {ref}") + return _unresolved(marker, alias, ev_kind, f"运行输入中没有「{ref}」") if entry.get("value") in (None, ""): - return _unresolved(marker, alias, ev_kind, f"运行输入 {ref} 是空的", rendered=MISSING) + return _unresolved(marker, alias, ev_kind, f"运行输入「{ref}」为空", rendered=MISSING) try: rendered = render_number(entry["value"], fmt="plain", conv=conv) except RenderError as e: @@ -1395,18 +1438,20 @@ def _resolve_entity(marker: dict[str, Any], catalog: dict[str, Any], snaps: _Sna alias = f"{kind}:{ref}" index = snaps.entities(catalog) if not snaps.entities_on: - return _unresolved(marker, alias, ev_kind, ENTITIES_OFF_REASON) + return _unresolved(marker, alias, ev_kind, _Reason(ENTITIES_OFF_REASON, ENTITIES_OFF_FIX)) if not index.active: return _unresolved(marker, alias, ev_kind, LATER_REASON) if not ref or not _IDENTIFIER.match(ref): - return _unresolved(marker, alias, ev_kind, "表名、字段名要写成 [[t:表名]]、[[c:表名.字段名]]," - "名字是字母或下划线开头的标识符") + return _unresolved(marker, alias, ev_kind, _Reason( + "表名、字段名引用格式无法识别", + "表名、字段名要写成 [[t:表名]]、[[c:表名.字段名]],名字是字母或下划线开头的标识符")) hit = index.find(ref, ev_kind) if hit is None: if index.find(ref, other): right = "c" if kind == "t" else "t" - return _unresolved(marker, alias, ev_kind, f"{ref} 是{'字段' if kind == 't' else '表'}," - f"不是{'表' if kind == 't' else '字段'}:写成 [[{right}:{ref}]]") + return _unresolved(marker, alias, ev_kind, _Reason( + f"「{ref}」是{'字段' if kind == 't' else '表'},不是{'表' if kind == 't' else '字段'}", + f"{ref} 是{'字段' if kind == 't' else '表'},不是{'表' if kind == 't' else '字段'}:写成 [[{right}:{ref}]]")) if index.unsure(ref): cite = _unresolved(marker, alias, ev_kind, UNVERIFIED_ENTITY_REASON, rendered=ref) cite["unverified"] = True @@ -1486,21 +1531,23 @@ def _resolve_quote(marker: dict[str, Any], catalog: dict[str, Any], snaps: _Snap quote = _clean(str(marker.get("quote") or "")) entry = catalog.get(alias) if entry is None: - return _unresolved(marker, alias, "quote", f"目录里没有 {alias}(能引原话的知识库检索见证据目录)") + return _unresolved(marker, alias, "quote", _Reason( + f"引用的检索结果 {alias} 不存在", f"目录里没有 {alias}(能引原话的知识库检索见证据目录)")) if entry.get("kind") != "retrieval": - return _unresolved(marker, alias, "quote", f"{alias} 不是知识库检索:引文只能引检索命中的原文") + return _unresolved(marker, alias, "quote", f"{alias} 不是知识库检索结果,引文只能引用检索命中的原文") if not quote: - return _unresolved(marker, alias, "quote", "引文是空的:写成 [[q:K1|原话]]") + return _unresolved(marker, alias, "quote", _Reason("引文为空", "引文是空的:写成 [[q:K1|原话]]")) hits, why = snaps.hits(alias, entry.get("artifact")) if why: return _unresolved(marker, alias, "quote", why) if len(normalize_quote(quote)) < QUOTE_MIN: - return _unresolved(marker, alias, "quote", f"引文太短(至少 {QUOTE_MIN} 个字),看不出是不是原话", + return _unresolved(marker, alias, "quote", f"引文太短(至少 {QUOTE_MIN} 个字),无法确认是否为原文", rendered=quote) found = find_quote(quote, hits) if found is None: - return _unresolved(marker, alias, "quote", f"{alias} 的命中片段里找不到这句原话(空白归一化后逐字比对):" - "引文要一字不差地抄原文", rendered=quote) + return _unresolved(marker, alias, "quote", _Reason( + f"在 {alias} 的检索结果中找不到这段引文的原文", + f"{alias} 的命中片段里找不到这句原话(空白归一化后逐字比对):引文要一字不差地抄原文"), rendered=quote) at, start, end = found hit = hits[at] locator = {"hit": at, "start": start, "end": end} @@ -1521,34 +1568,35 @@ def resolve_support(ref: str, catalog: dict[str, Any], *, loader: Loader | _Snap base = {"ref": ref, "role": "support"} if sep and kind in ("t", "c"): cite = _resolve_entity({"kind": kind, "ref": body, "body": body}, catalog, _snapshots(loader)) - return {**base, **{k: cite[k] for k in ("alias", "kind", "status", "eid", "locator", "reason", "unknown", - "unverified") if k in cite}} + return {**base, **{k: cite[k] for k in ("alias", "kind", "status", "eid", "locator", "reason", "for_model", + "unknown", "unverified") if k in cite}} if sep and kind == "q": return {**base, "alias": ref, "kind": "quote", "status": "unresolved", - "reason": "引文不能当依据:依据写那次检索的编号,比如 [[see:K1]]"} + "reason": "引文不能作为依据,依据应引用检索结果的编号", + "for_model": "引文不能当依据:依据写那次检索的编号,比如 [[see:K1]]"} alias: str | None = None locator: dict[str, Any] = {} - why = f"目录里没有 {ref}" + why: str = _Reason(f"引用的依据「{ref}」不存在", f"目录里没有 {ref}") if sep and kind == "m": alias, why = _metric_alias(body, catalog) elif sep and kind == "i": alias = ref if ref in catalog else None - why = f"运行输入里没有 {body}" + why = f"运行输入中没有「{body}」" elif sep: - why = f"不认识的依据写法 {ref}:写 m:指标、i:输入,或者 Q1 / K1 这样的编号" + why = _Reason(f"依据「{ref}」的写法无法识别", f"不认识的依据写法 {ref}:写 m:指标、i:输入,或者 Q1 / K1 这样的编号") elif m := _ROW_REF.match(ref): alias = m.group("alias") if m.group("alias") in catalog else None if alias and m.group("row") is not None: row, total = int(m.group("row")), catalog[alias].get("rows") if isinstance(total, int) and row >= total: - alias, why = None, f"{m.group('alias')} 只有 {total} 行,没有第 {row} 行(从 0 数)" + alias, why = None, f"{m.group('alias')} 只有 {total} 行,没有第 {row} 行(行号从 0 开始)" else: locator = {"row": row} elif f"m:{ref}" in catalog: alias = f"m:{ref}" # 漏写了 m: 前缀的指标 id,意思没有歧义 if alias is None: return {**base, "alias": ref, "kind": kind if sep else "unknown", "status": "unresolved", - "reason": why} + "reason": str(why), **_fix_of(why)} entry = catalog[alias] return {**base, "alias": alias, "kind": entry["kind"], "status": "resolved", "eid": entry["eid"], "locator": {**(entry.get("locator") or {}), **locator}} @@ -2056,6 +2104,12 @@ def _bare_link(name: str, catalog: dict[str, Any], index: _EntityIndex) -> tuple return None +def _stored(cite: dict[str, Any]) -> dict[str, Any]: + """存进文档的样子:去掉 for_model。那是交回写作者改写时用的指令,复核时按目录重新解析会再得到, + 文档里只留给人看的 reason。""" + return {k: v for k, v in cite.items() if k != "for_model"} if "for_model" in cite else cite + + def _entity_segment(name: str, hit: tuple[str, str], catalog: dict[str, Any], *, code: bool) -> dict[str, Any]: kind, alias = hit entry = catalog[alias] @@ -2217,9 +2271,9 @@ def compose_doc( plain(cursor, marker["start"]) cursor = marker["end"] if marker["kind"] == "see": - see.extend(resolve_support(r, catalog, loader=snaps) for r in marker["refs"]) + see.extend(_stored(resolve_support(r, catalog, loader=snaps)) for r in marker["refs"]) continue - cite = resolve_marker(marker, catalog, cells_allowed=cells_allowed, loader=snaps) + cite = _stored(resolve_marker(marker, catalog, cells_allowed=cells_allowed, loader=snaps)) ok = cite["status"] == "resolved" seg = { "kind": _SEG_KIND.get(marker["kind"]) @@ -2395,7 +2449,15 @@ def find_segment(doc: dict[str, Any], segment_id: str) -> tuple[dict, dict, dict def _violation(code: str, message: str, **extra: Any) -> dict[str, Any]: - return {"code": code, "message": message, **{k: v for k, v in extra.items() if v is not None}} + """一处问题。message 给人看;message 是 _Reason 时另记 for_model,交回写作者改写时用(describe_violations)。""" + return {"code": code, "message": str(message), **_fix_of(message), + **{k: v for k, v in extra.items() if v is not None}} + + +def _unresolved_message(label: str, ref: str, cite: dict[str, Any]) -> str: + """「引用 [[m:gmv]] 无法解析:…」。cite 带 for_model 的,给模型的那句照旧写原来的说法。""" + text = f"{label} [[{ref}]] 无法解析:{cite['reason']}" + return _Reason(text, f"{label} [[{ref}]] 解析不了:{cite['for_model']}") if cite.get("for_model") else text def verify_doc( @@ -2445,10 +2507,10 @@ def verify_doc( **({"unknown_entities": 0, "unverified_entities": 0} if layered else {}), "see": 0, "uncited_claims": 0, "violations": 0} if not isinstance(doc, dict): - violations.append(_violation("bad_schema", "报告文档不是一个对象")) + violations.append(_violation("bad_schema", "报告文档格式有误")) return {"ok": False, "violations": violations, "stats": stats, "uncited": uncited} if doc.get("schema") != DOC_SCHEMA: - violations.append(_violation("bad_schema", f"不认识的报告文档格式 {doc.get('schema')!r}")) + violations.append(_violation("bad_schema", f"报告文档格式「{doc.get('schema')}」无法识别")) markdown = str(doc.get("markdown") or "") masks: list[tuple[int, int]] = [] # 引用渲染出来的字 @@ -2471,7 +2533,7 @@ def verify_doc( if tiled and (not intact or span[0] != pos): tiled = False violations.append(_violation("segment_mismatch", - f"片段 {seg.get('id')} 和正文对不上:文档可能被改过", + f"报告的第 {stats['segments']} 个片段与正文不一致,文档可能被修改过", segment=seg.get("id"), unit=unit.get("id"))) if intact: pos = span[1] @@ -2486,7 +2548,7 @@ def verify_doc( syntax.append((span[0], span[1])) else: violations.append(_violation("structural_text", - f"结构片段里夹带了内容「{text[:30]}」", **where)) + f"排版片段中混入了正文内容「{text[:30]}」", **where)) elif seg.get("ref"): ref = str(seg["ref"]) cite = _phase_two_cite(seg, ref, text) \ @@ -2504,15 +2566,15 @@ def verify_doc( violations.append(_violation("unverified_entity", _unverified_message(cite.get("ref") or ref), ref=ref, **where)) elif not ok: - violations.append(_violation("unresolved_ref", f"引用 [[{ref}]] 解析不了:{cite['reason']}", + violations.append(_violation("unresolved_ref", _unresolved_message("引用", ref, cite), ref=ref, **where)) elif not matches: violations.append(_violation( - "render_mismatch", f"片段「{text}」和引用 [[{ref}]] 重新渲染出来的「{shown}」" - "对不上", ref=ref, **where)) + "render_mismatch", f"片段「{text}」与引用 [[{ref}]] 重新渲染的结果「{shown}」" + "不一致", ref=ref, **where)) elif (seg.get("cite") or {}).get("eid") not in (None, cite["eid"]): - violations.append(_violation("eid_mismatch", f"引用 [[{ref}]] 记的证据标识和目录里的不一致," - "文档可能被改过", ref=ref, **where)) + violations.append(_violation("eid_mismatch", f"引用 [[{ref}]] 记录的证据标识与本次运行的证据" + "不一致,文档可能被修改过", ref=ref, **where)) good = ok and matches expected = "deterministic" if good else "none" if seg.get("kind") == "number": @@ -2546,7 +2608,7 @@ def verify_doc( # 已经为这一段报过别的问题,状态不对是它的推论,不再重复 if expected is not None and state != expected and len(violations) == found: violations.append(_violation("state_mismatch", - f"片段「{text[:30]}」标的状态是 {state},核对下来应该是 {expected}", + f"片段「{text[:30]}」记录的核对状态与重新核对的结果不一致,文档可能被修改过", **where)) for support in unit.get("see") or []: stats["see"] += 1 @@ -2562,7 +2624,7 @@ def verify_doc( span=list(unit.get("span") or []) or None)) else: violations.append(_violation("unresolved_ref", - f"依据 [[see:{again['ref']}]] 解析不了:{again['reason']}", + _unresolved_message("依据", f"see:{again['ref']}", again), ref=again["ref"], unit=unit.get("id"), span=list(unit.get("span") or []) or None)) if kind == "claim" and not cited: @@ -2572,13 +2634,14 @@ def verify_doc( uncited.append({"unit": unit.get("id"), "span": list(where) if ok_span else None, "text": markdown[where[0]:where[1]] if ok_span else ""}) if tiled and pos != len(markdown): - violations.append(_violation("segment_mismatch", "正文末尾有一段不在任何片段里:文档可能被改过")) + violations.append(_violation("segment_mismatch", "正文末尾有一段不属于任何片段,文档可能被修改过")) masks += _header_masks(list(doc.get("blocks") or []), catalog) for token in _bare_numbers(markdown, masks, allow_numbers, syntax): owner = next(((sid, uid) for s, e, sid, uid in owners if s <= token.start < e), (None, None)) violations.append(_violation( - "uncited_number", f"数字「{token.raw}」没有出处:要写成引用标记(比如 [[m:指标id]]),不能直接写数字", + "uncited_number", _Reason(f"数字「{token.raw}」没有出处:报告中直接写出了数字,系统无法核对", + f"数字「{token.raw}」没有出处:要写成引用标记(比如 [[m:指标id]]),不能直接写数字"), span=[token.start, token.end], text=token.raw, context=_context(markdown, token.start, token.end), segment=owner[0], unit=owner[1])) @@ -2595,28 +2658,32 @@ def verify_doc( def _phase_two_cite(seg: dict[str, Any], ref: str, text: str) -> dict[str, Any] | None: - """升级前(二期)组装的文档里的 t / c / q:那时一律判为解析不了,正文是占位,原因是 LATER_REASON。 + """升级前(二期)组装的文档里的 t / c / q:那时一律判为解析不了,正文是占位,原因是 LEGACY_LATER_REASON。 这样的文档升级后才被复核(运行停在报告和出口之间)时,按当时的规矩查:正文确实是占位、确实 没有出处,记解析不了——不能因为今天解析得了,就把它判成「渲染对不上」(完整性问题,出口记缺口)。 - 只认「原因是 LATER_REASON 并且正文恰好是占位」的片段:自称二期却显示了别的字的,照现在的规矩查。 + 只认「原因是 LEGACY_LATER_REASON(或现在的 LATER_REASON)并且正文恰好是占位」的片段:自称二期却显示了 + 别的字的,照现在的规矩查。 """ kind, _, body = ref.partition(":") stored = seg.get("cite") - if kind not in ("t", "c", "q") or not isinstance(stored, dict) or stored.get("reason") != LATER_REASON \ + said = stored.get("reason") if isinstance(stored, dict) else None + if kind not in ("t", "c", "q") or said not in (LATER_REASON, LEGACY_LATER_REASON) \ or text != placeholder(kind, body): return None alias = stored.get("alias") if isinstance(stored.get("alias"), str) else ref + reason = PHASE_TWO_REASON if said == LEGACY_LATER_REASON else LATER_REASON return {"ref": body, "alias": alias, "kind": stored.get("kind") or kind, "role": _ROLE.get(kind, "value"), - "status": "unresolved", "reason": LATER_REASON, "rendered": text} + "status": "unresolved", "reason": reason, "rendered": text} def _unknown_message(name: str) -> str: - return f"「{name}」{UNKNOWN_ENTITY_REASON}:只写本次运行的表结构、查询里真实存在的表名和字段名" + return _Reason(f"「{name}」{UNKNOWN_ENTITY_REASON}", + f"「{name}」{_UNKNOWN_ENTITY_FOR_MODEL}:只写本次运行的表结构、查询里真实存在的表名和字段名") def _unverified_message(name: str) -> str: - return f"「{name}」核对不了:{UNVERIFIED_ENTITY_REASON}" + return f"「{name}」无法核实:{UNVERIFIED_ENTITY_REASON}" def uncited_claims(doc: dict[str, Any]) -> list[dict[str, Any]]: @@ -2820,11 +2887,12 @@ def _retrieval_prompt(entry: dict[str, Any], snaps: _Snapshots) -> list[str]: def describe_violations(violations: list[dict[str, Any]], *, limit: int = 20) -> str: - """违规清单的文字版:给写作者的修复指令、给节点的报错,都用这一份。""" + """违规清单的文字版,交回写作者(模型)改写用:有 for_model(给模型的改写指令)的用它, + 没有的用 message。给人看的报错直接用 message,不经过这里。""" lines = [] for v in violations[:limit]: where = f"(…{v['context']}…)" if v.get("context") else "" - lines.append(f"- {v['message']}{where}") + lines.append(f"- {v.get('for_model') or v['message']}{where}") if len(violations) > limit: lines.append(f"- …另有 {len(violations) - limit} 处") return "\n".join(lines) @@ -2839,7 +2907,7 @@ def describe_violations(violations: list[dict[str, Any]], *, limit: int = 20) -> # -------------------------------------------------------------------------- GUESS_SCHEMA = "agentlab.guess/1" -GUESS_NOTE = "猜测的来源,不能当证据:按数值在这次运行已封存的查询结果和口径卡里找相同的值,同值的巧合很多" +GUESS_NOTE = "猜测的来源,不能当证据:按数值在本次运行已封存的查询结果和口径卡中查找相同的值,数值相同的巧合很多" #: 每个数字最多给几个候选 MAX_CANDIDATES = 3 diff --git a/backend/app/engine/expressions.py b/backend/app/engine/expressions.py index f23360d0..09ac4e15 100644 --- a/backend/app/engine/expressions.py +++ b/backend/app/engine/expressions.py @@ -234,9 +234,9 @@ def _table_of(table: Any) -> dict[str, Any]: data = json.loads(data) except ValueError: # 查库失败时工具交回的是一句话(「查询失败:…」):原话照搬,比「不是 JSON」有用 - raise CellError(f"要的是查询结果,拿到的是「{data.strip()[:80]}」") from None + raise CellError(f"需要查询结果,实际得到的是「{data.strip()[:80]}」") from None if not isinstance(data, dict) or not isinstance(data.get("rows"), list): - raise CellError("第一个参数要是查询结果:查询工具交回的 JSON 文本,或者 {columns, rows}") + raise CellError("第一个参数需要是查询结果:查询工具返回的 JSON 文本,或 {columns, rows} 结构") return data @@ -245,30 +245,30 @@ def locate_cell(table: Any, row: Any, column: Any) -> tuple[Any, str]: data = _table_of(table) rows = data["rows"] if isinstance(row, bool) or not isinstance(row, int): - raise CellError(f"行号要是从 0 数的整数,写的是 {row!r}") + raise CellError(f"行号需为从 0 开始的整数,当前为「{row}」") if not rows: - raise CellError("这份查询结果是空的(0 行)") + raise CellError("查询结果为空(0 行)") if not 0 <= row < len(rows): - raise CellError(f"要第 {row} 行,但这份查询结果只有 {len(rows)} 行(从 0 数)") + raise CellError(f"请求第 {row} 行,但查询结果只有 {len(rows)} 行(行号从 0 开始)") record = rows[row] columns = [str(c) for c in data.get("columns") or []] if isinstance(record, dict): columns = columns or [str(k) for k in record] if isinstance(column, int) and not isinstance(column, bool): if not 0 <= column < len(columns): - raise CellError(f"要第 {column} 列,但只有 {len(columns)} 列(从 0 数)") + raise CellError(f"请求第 {column} 列,但查询结果只有 {len(columns)} 列(列号从 0 开始)") column = columns[column] elif not isinstance(column, str): - raise CellError(f"列要写列名,或者从 0 数的列号,写的是 {column!r}") + raise CellError(f"列需填写列名或从 0 开始的列号,当前为「{column}」") if isinstance(record, dict): if column not in record: - raise CellError(f"没有列「{column}」,有:{'、'.join(columns[:12])}") + raise CellError(f"没有列「{column}」,可用的列:{'、'.join(columns[:12])}") return record[column], column if column not in columns: - raise CellError(f"没有列「{column}」,有:{'、'.join(columns[:12])}") + raise CellError(f"没有列「{column}」,可用的列:{'、'.join(columns[:12])}") index = columns.index(column) if not isinstance(record, (list, tuple)) or index >= len(record): - raise CellError(f"第 {row} 行没有「{column}」这一格") + raise CellError(f"第 {row} 行中没有「{column}」对应的单元格") return record[index], column @@ -329,7 +329,19 @@ _NODE_NAMES = { "ListComp": "列表推导式", "SetComp": "集合推导式", "DictComp": "字典推导式", "GeneratorExp": "生成器表达式", "Lambda": "lambda", "JoinedStr": "f-string", "NamedExpr": ":=", "Slice": "切片 a[i:j]", "Starred": "* 展开", "Await": "await", + "Set": "集合写法", } +#: 不支持的运算符给人看的写法:报错里写符号,不写 Python 的类名(BitOr) +_OP_SYMBOLS = { + "BitOr": "|", "BitAnd": "&", "BitXor": "^", "LShift": "<<", "RShift": ">>", "MatMult": "@", + "Invert": "~", +} + + +def _unsupported(name: str) -> str: + """「表达式中不支持列表推导式」「表达式中不支持 lambda」:英文写法前面空一格。""" + label = _NODE_NAMES.get(name, name) + return f"表达式中不支持{' ' if label[:1].isascii() else ''}{label}" @@ -365,24 +377,24 @@ def _check_static(tree: ast.Expression) -> list[str]: if isinstance(node, ast.BinOp) and type(node.op) not in _BIN_OPS: if isinstance(node.op, ast.BitOr): raise ExpressionError( - "表达式里没有 | 过滤器(那是模板的写法):取长度写 len(x),大小写写 upper(x) / lower(x)" + "表达式中不支持 | 过滤器(那是模板的写法):取长度请写 len(x),转换大小写请写 upper(x) / lower(x)" ) - raise ExpressionError(f"不支持的运算符 {type(node.op).__name__}") + op_name = type(node.op).__name__ + raise ExpressionError(f"不支持运算符 {_OP_SYMBOLS.get(op_name, op_name)}") if not isinstance(node, _ALLOWED_NODES): if isinstance(node, ast.Set): - raise ExpressionError("表达式里不支持集合 {…}:要判断是不是其中之一,用列表 x in ['a', 'b']") - name = type(node).__name__ - raise ExpressionError(f"表达式里不允许出现 {_NODE_NAMES.get(name, name)}") + raise ExpressionError("表达式中不支持集合写法 {…}:如需判断是否属于其中之一,请使用列表,例如 x in ['a', 'b']") + raise ExpressionError(_unsupported(type(node).__name__)) if isinstance(node, ast.Call): if not isinstance(node.func, ast.Name) or node.func.id not in _SAFE_FUNCS: called = node.func.id if isinstance(node.func, ast.Name) else ast.unparse(node.func) - raise ExpressionError(f"不认识的函数 {called}(),能用的只有:{'、'.join(_SAFE_FUNCS)}") + raise ExpressionError(f"不支持函数 {called}(),可用的函数:{'、'.join(_SAFE_FUNCS)}") elif isinstance(node, ast.Attribute) and node.attr.startswith("_"): raise ExpressionError("不允许访问私有属性") elif (isinstance(node, ast.Constant) and isinstance(node.value, str) and _TEMPLATE_RE.search(node.value)): raise ExpressionError( - f"字符串 {node.value!r} 里的 {{{{ }}}} 不会被渲染——表达式不过模板,直接写路径,比如 vars.x" + f"字符串「{node.value}」中的 {{{{ }}}} 不会被渲染:表达式不经过模板渲染,请直接写路径,例如 vars.x" ) elif (isinstance(node, ast.Name) and node.id not in EXPRESSION_ROOTS and node.id not in _SAFE_FUNCS and node.id not in _LITERAL_NAMES): @@ -400,12 +412,12 @@ def parse_expression(expr: str) -> tuple[ast.Expression, list[str], list[str]]: try: tree = ast.parse(text, mode="eval") except SyntaxError as e: - hint = "(判断相等要写 ==)" if re.search(r"(?])=(?!=)", text) else "" + hint = "(判断相等请写 ==)" if re.search(r"(?])=(?!=)", text) else "" raise ExpressionError(f"表达式语法错误:{e.msg}{hint}") from e unbrace = _Unbrace() tree = ast.fix_missing_locations(unbrace.visit(tree)) if sum(1 for _ in ast.walk(tree)) > _MAX_NODES: - raise ExpressionError("表达式太复杂") + raise ExpressionError("表达式过于复杂") unknown = _check_static(tree) return tree, unbrace.found, unknown @@ -620,7 +632,7 @@ def eval_expression(expr: str, ctx: dict[str, Any]) -> Any: return _eval(node.body) if _eval(node.test) else _eval(node.orelse) if isinstance(node, ast.Call): if not isinstance(node.func, ast.Name) or node.func.id not in _SAFE_FUNCS: - raise ExpressionError("只能调用白名单函数") + raise ExpressionError("只能调用允许的函数") args = [_eval(a) for a in node.args] kwargs = {kw.arg: _eval(kw.value) for kw in node.keywords if kw.arg} return _SAFE_FUNCS[node.func.id](*args, **kwargs) @@ -632,7 +644,7 @@ def eval_expression(expr: str, ctx: dict[str, Any]) -> Any: for k, v in zip(node.keys, node.values) if k is not None } - raise ExpressionError(f"表达式里不允许出现 {type(node).__name__}") + raise ExpressionError(_unsupported(type(node).__name__)) return _eval(tree) diff --git a/backend/app/engine/governance.py b/backend/app/engine/governance.py index fb172a22..9bdd07d3 100644 --- a/backend/app/engine/governance.py +++ b/backend/app/engine/governance.py @@ -7,6 +7,7 @@ from typing import Any, Callable from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession +from app.engine.labels import contract_label, field_label, judge_label, option_label, q from app.engine.schema import ( CLAIMS_JUDGE, GraphNode, @@ -25,11 +26,7 @@ from app.engine.schema import ( # 就是"上周和这周的数其实不可比,但报表看起来一切正常"。 UPGRADE_POLICIES = {"recompute", "dual", "incomparable"} -UPGRADE_POLICY_LABELS = { - "recompute": "用新口径回算历史", - "dual": "并排双印新旧口径", - "incomparable": "标注与历史不可比", -} +UPGRADE_POLICY_LABELS = {k: option_label("upgrade_policy", k) for k in ("recompute", "dual", "incomparable")} def lint_for_publish(spec: GraphSpec, *, level: str) -> ValidationResult: @@ -58,38 +55,38 @@ def lint_for_publish(spec: GraphSpec, *, level: str) -> ValidationResult: if node.type == NodeType.SUPERVISOR: # 全动态规划属于探索层。受管模板里出现它,等于把 XAgent 搬上了生产线。 flag( - f"{who}:受管模板不允许全动态规划的节点——谁来做、做几轮都由模型临场" - "决定,属于探索层。改用固定编排的 Agent 或「模型调用」节点", + f"{who}:受管级别不允许使用全动态规划的节点,其分工和轮数由模型在运行时决定," + "无法事先审核。请改用配置固定的 Agent 或「模型调用」节点", code="governed.supervisor", node_id=node.id, hard=True, ) elif node.type == NodeType.SUBGRAPH: if not cfg.get("workflow_version"): flag( - f"{who}没有钉住版本,口径会随上游最新版漂移。在节点里选定一个版本", + f"{who}没有固定版本,口径会随上游最新版本变化。请在节点中选定一个版本", code="governed.subgraph_unpinned", node_id=node.id, hard=True, field="workflow_version", ) elif node.type == NodeType.AGENT: tools = cfg.get("tools") or [] if cfg.get("approval") == "never" and tools: flag( - f"{who}的审批策略是「全部自动放行」,受管模板要求危险工具至少人工确认。" - "改成「仅危险工具需要审批」", + f"{who}的审批策略是「{option_label('approval', 'never')}」,受管级别要求危险工具至少经过人工审批。" + f"请改为「{option_label('approval', 'dangerous')}」", code="governed.agent_approval_never", node_id=node.id, hard=True, field="approval", ) elif cfg.get("approval") in (None, "") and spec.defaults.get("approval") == "never" and tools: # 节点自己没写,运行时跟随全图默认(context.approval_mode:节点 > 图级 defaults > 全局)。 # 全图默认写着全部自动放行,这个 agent 就是全部自动放行,只是没写在它自己身上 flag( - f"{who}没写自己的审批策略,跟随全图默认的「全部自动放行」,受管模板要求危险工具至少" - "人工确认。把全图默认改成「仅危险工具需要审批」,或者在这个节点上单独设置", + f"{who}没有设置审批策略,跟随{field_label('defaults')}中的「{option_label('approval', 'never')}」;受管级别要求危险工具至少" + f"经过人工审批。请将{field_label('defaults')}中的审批策略改为「{option_label('approval', 'dangerous')}」,或在该节点上单独设置", code="governed.default_approval_never", node_id=node.id, hard=True, field="approval", ) if not tools: - flag(f"{who}没有配任何可用工具,通常意味着它该是个「模型调用」节点", + flag(f"{who}没有配置可用工具,建议改用「模型调用」节点", code="governed.agent_no_tools", node_id=node.id, field="tools") elif len(tools) > 10: flag( - f"{who}的可用工具有 {len(tools)} 个,边界过宽(白名单衰减的前兆)", + f"{who}的可用工具有 {len(tools)} 个,授权范围过宽,建议只保留完成任务所需的工具", code="governed.agent_tools_wide", node_id=node.id, field="tools", ) elif node.type == NodeType.OUTPUT: @@ -99,14 +96,14 @@ def lint_for_publish(spec: GraphSpec, *, level: str) -> ValidationResult: _lint_contract(contract, node_id=node.id, spec=spec, flag=flag, strict=strict) elif node.type == NodeType.CODE: if cfg.get("network"): - flag(f"{who}打开了「允许联网」:受管模板建议把取数收敛到「调用工具」节点" - "(那里有取数快照)", code="governed.code_network", node_id=node.id, field="network") + flag(f"{who}开启了「允许联网」:受管级别建议把取数集中到「调用工具」节点" + "(那里会保存取数快照)", code="governed.code_network", node_id=node.id, field="network") _lint_evidence(spec, flag, strict=strict) if strict and not has_contract_output: result.add( - "受管模板至少要有一个「成果 / 出具」节点声明出具契约,否则三档出具无从谈起", + "受管级别要求至少一个「成果」节点声明出具契约,否则无法判定出具档位", level="error", code="governed.no_contract", ) return result @@ -162,13 +159,13 @@ def _lint_contract( sources = [sources] if not sources and contract_needs_metrics(contract): - flag("出具契约没有声明 metrics_from(指标来自哪个「口径卡」节点),叙述里的数字无从回指", + flag("出具契约没有设置「指标来自」(提供指标的口径卡),叙述中的数字无法对应到指标", code="contract.metrics_from_missing", node_id=node_id, hard=True, field="contract.metrics_from") for src in sources: if src not in metric_nodes: flag( - f"出具契约的 metrics_from 指向 {src!r},但工作流里没有这个「口径卡」节点" - "(写错了,或者那个节点还没建)", + f"出具契约的「指标来自」选择了{q(src)},但工作流中没有这个口径卡节点" + "(可能填写有误,或该节点尚未创建)", code="contract.metrics_from_invalid", node_id=node_id, hard=True, field="contract.metrics_from", ) @@ -176,8 +173,8 @@ def _lint_contract( # 用不上 narrative。report_from 指错了(不是报告撰写节点、不在出口上游)由 validate_graph # 报 error(contract.report_from_invalid),发布时两者一起过,照样挡住 if contract.get("report_from") in (None, "") and not str(contract.get("narrative") or "").strip(): - flag("出具契约既没有声明 report_from(核对哪个「报告撰写」节点的文档),也没有声明 narrative" - "(叙述),数字回指校验不会执行", code="contract.report_from_missing", node_id=node_id, hard=True, + flag("出具契约既没有设置「报告来自」(核对哪个「报告撰写」节点的文档),也没有填写「叙述」," + "不会执行数字核对", code="contract.report_from_missing", node_id=node_id, hard=True, field="contract.report_from") # 引用模式下整张图没有口径卡(只引查询单元格的问数据图):没有指标可列,strict + cells 已经保证 @@ -186,28 +183,29 @@ def _lint_contract( cells_only = contract.get("report_from") not in (None, "") and not metric_nodes if strict and not (contract.get("required") or []) and not cells_only: flag( - "受管模板的出具契约必须声明 required(必需指标),否则「不予出具」这一档永远触发不了", + "受管级别的出具契约必须设置「必需指标」,否则「不予出具」这一档无法触发", code="contract.required_missing", node_id=node_id, hard=True, field="contract.required", ) # 没有口径卡的图,报告里的数只能直接引用查询单元格;受管正式运行不认没声明的单元格引用, # 报告撰写节点(numbers strict、on_violation fail)每次都会失败。写不写要作者定:修复给选项 if strict and cells_only and contract.get("cells") is not True: flag( - "这张图没有口径卡,报告里的数只能直接引用查询单元格:受管出具要在契约里写 cells: true," - "否则正式运行里一个数都引用不了,报告撰写节点每次都会失败(也可以加一张口径卡,把数登记成指标)", + "工作流中没有口径卡,报告中的数字只能直接引用查询单元格。受管级别需要在出具契约中开启「单元格引用」," + "否则正式运行时报告撰写节点无法引用任何数字而失败;也可以添加口径卡,把数字登记为指标", code="contract.cells_undeclared", node_id=node_id, hard=True, field="contract.cells", ) if strict and not contract.get("strict"): flag( - "受管模板建议把出具契约设为 strict:非 strict 下未回指的数字只降档不拦截", + "受管级别建议开启出具契约的「严格模式」:未开启时,无法追溯出处的数字只会使出具降档,不会被拦截", code="contract.strict_off", node_id=node_id, field="contract.strict", ) claims = contract.get("claims") if strict and isinstance(claims, dict) and claims.get("on_uncited") == "ignore": # 受管级别的正式运行把 ignore 当 degrade(io._claims),要求没有降低;只是写法看上去像放宽了 flag( - "出具契约的 claims 写了 on_uncited: ignore,但受管级别的正式运行里没挂依据的结论句照样计入缺口" - "(按 degrade 处理),这个写法不会生效。改成 degrade,或者更严的 withhold", + f"出具契约中「{contract_label('on_uncited')}」设为「{option_label('on_uncited', 'ignore')}」,但受管级别的" + "正式运行仍会把未附依据的结论句计入缺口,这项设置不会生效。" + f"请改为「{option_label('on_uncited', 'degrade')}」或「{option_label('on_uncited', 'withhold')}」", code="contract.claims_ignored", node_id=node_id, field="contract.claims", ) @@ -225,11 +223,12 @@ def _lint_contract( # 下次发布才按这些规则查。受管级别挡住发布,已发布级别只给警告。 # -------------------------------------------------------------------------- -#: 报告撰写节点在受管模板里要写明的三项:(配置键, 要求的值, 为什么) +#: 报告撰写节点在受管级别里要写明的三项:(配置键, 要求的值, 为什么)。给人看的时候键和值都换成 +#: labels 里的界面叫法 REPORT_POLICY = ( - ("numbers", "strict", "没有出处的裸数字判为违规"), - ("on_violation", "fail", "重写之后还违规就让节点失败,不带着问题出具"), - ("claims", "require_citation", "没挂引用的结论句计入缺口,按出具档位降档"), + ("numbers", "strict", "没有出处的数字判为违规"), + ("on_violation", "fail", "重写后仍有违规时节点失败,不带着问题出具"), + ("claims", "require_citation", "未附依据的结论句计入缺口,出具按档位降档"), ) #: 除了 REPORT_POLICY 里写的那个值,还认的更严的写法。claims: judge 在挂引用之外再请另一个模型按证据逐句 #: 裁判,不支持的按 on_unsupported 判档——比 require_citation 严,但要写预算(见 judge_budget_missing) @@ -413,9 +412,9 @@ def _untraceable_sources(graph: _Graph, exit_id: str, refs: list[Ref]) -> list[s for ref in refs: root, name, _ = ref if root in ("output", "loops") or (root in ("nodes", "vars") and not name): - out.append(f"{root} 里的值(说不准来自哪个节点)") + out.append(f"{q(root)}中的值(无法确定来自哪个节点)") elif root in ("last_message", "messages"): - out += [f"最后一条消息({_who(w)}写的)" for w in graph.last_writers(exit_id) if w.type != NodeType.REPORT] + out += [f"最后一条消息(由{_who(w)}写出)" for w in graph.last_writers(exit_id) if w.type != NodeType.REPORT] else: # 开了 cite_fields 的 agent 交的字段逐格核对过,是数据不是模型写的话——和 G2(_model_text)同一口径 out += [_who(p) for p in graph.producers(root, name) @@ -490,15 +489,15 @@ def _lint_evidence(spec: GraphSpec, flag: Callable[..., None], *, strict: bool) contract = node.config["contract"] # 两样都没写的由 contract.report_from_missing 报,这里只管「写了叙述、没写 report_from」 if contract.get("report_from") in (None, "") and str(contract.get("narrative") or "").strip(): - flag(f"{_who(node)}的出具契约用的是旧的叙述模式(narrative),没有声明 report_from:数字只能按数值" - "回头匹配,出处可能不唯一。受管出具核对「报告撰写」节点产出的文档,每个数都有唯一的出处——把 " - "report_from 指向出口上游的报告撰写节点", + flag(f"{_who(node)}的出具契约使用「叙述」核对,没有设置「报告来自」:数字只能按数值匹配,出处可能不唯一。" + "受管级别要求核对「报告撰写」节点产出的文档,每个数字都有唯一的出处。" + "请把「报告来自」设为成果节点上游的报告撰写节点", code="governed.report_from_required", node_id=node.id, hard=True, field="contract.report_from") for field, name, bad in exit_text_fields(spec, node, graph): - head = (f"{_who(node)}的成果字段「{name}」取的是{'、'.join(bad)}的产出" if name is not None - else f"{_who(node)}没有配成果字段,交出去的是{'、'.join(bad)}") - flag(f"{head}:受管出具里给人看的文字只能来自「报告撰写」节点,别的节点写的字核对不了出处。" - + ("把它改成取报告撰写节点的正文" if name is not None else "给出口配一个字段,取报告撰写节点的正文"), + head = (f"{_who(node)}的成果字段「{name}」取自{'、'.join(bad)}的产出" if name is not None + else f"{_who(node)}没有配置成果字段,输出的是{'、'.join(bad)}") + flag(f"{head}:受管级别出具时,给人看的文字只能来自「报告撰写」节点,其他节点写的文字无法追溯出处。" + + ("请改为取报告撰写节点的正文" if name is not None else "请为成果节点添加一个字段,取报告撰写节点的正文"), code="governed.exit_text_source", node_id=node.id, hard=True, field=field) # G2:每个出口都算。受管级别是 error,已发布级别是警告——和别的 G 规则一样,级别只管轻重,不管范围 @@ -511,9 +510,9 @@ def _lint_evidence(spec: GraphSpec, flag: Callable[..., None], *, strict: bool) continue flagged.add(writer.id) via = f"(经过{'、'.join(f'「{t}」' for t in indirect[0])})" if indirect else "" - flag(f"{_who(writer)}写的文字没经过「报告撰写」节点,就流进了出口「{node.title}」{via}:模型写的话不算" - "证据,里面的数字、表名都核对不了出处。改由报告撰写节点来写(它只写引用标记,数字由系统渲染)," - "出口取报告的正文", + flag(f"{_who(writer)}写的文字未经「报告撰写」节点,就进入了成果节点「{node.title}」{via}:模型写的文字不能" + "作为证据,其中的数字和表名都无法追溯出处。请改由报告撰写节点撰写(它只写引用标记,数字由系统填入)," + "成果节点改为取报告的正文", code="governed.text_bypass", node_id=writer.id, hard=True) # G3 @@ -527,16 +526,17 @@ def _lint_evidence(spec: GraphSpec, flag: Callable[..., None], *, strict: bool) continue # 写了不认识的值,validate 的 report.claims_invalid 报 also = REPORT_POLICY_ALSO.get(key, ()) if value != want and value not in also: - now = "现在没写" if value in (None, "") else f"现在是 {value}" - more = "".join(f",或者更严的 {v}" for v in also) - loose.append((key, f"{key}: {want}({why}{more};{now})")) + now = "当前未设置" if value in (None, "") else f"当前为「{option_label(key, value)}」" + more = "".join(f"或更严格的「{option_label(key, v)}」" for v in also) + loose.append((key, f"「{field_label(key)}」设为「{option_label(key, want)}」{more}({now})")) if loose: - flag(f"{_who(node)}要写明 {';'.join(text for _, text in loose)}。受管模板的报告撰写节点按最严的规则自查", + flag(f"{_who(node)}需要调整核对规则:{';'.join(text for _, text in loose)}。" + "受管级别要求报告撰写节点使用最严格的核对规则", code="governed.report_policy", node_id=node.id, hard=True, field=loose[0][0]) if judge_budget_missing(spec, node): - flag(f"{_who(node)}的结论句由模型裁判(claims: judge),却没有写每份报告的裁判预算:在 judge 里写 " - "max_cost_usd——写一个金额(美元),或者显式写 null 表示不限(" + JUDGE_UNLIMITED + ")。" - "受管出具不让裁判的花费悄悄按设置里的默认值走", + flag(f"{_who(node)}的结论句由模型裁判,但没有设置每份报告的裁判金额上限。请在「{field_label('judge')}」中" + f"填写「{judge_label('max_cost_usd')}」,或明确选择不限({JUDGE_UNLIMITED})。" + "受管级别不允许裁判费用沿用设置中的默认值", code="governed.judge_budget", node_id=node.id, hard=True, field="judge.max_cost_usd") # G4、G5 @@ -549,21 +549,22 @@ def _lint_evidence(spec: GraphSpec, flag: Callable[..., None], *, strict: bool) to = f"口径卡{'、'.join(dict.fromkeys(cards))}" cfg = feeder.config if feeder.type == NodeType.CODE and cfg.get("evidence_role") != "source": - role = "是 compute" if cfg.get("evidence_role") else "没写,按计算算" - flag(f"{_who(feeder)}的产出喂给了{to},而它的角色是计算(evidence_role {role}):沙箱里算出来的数核对" - "不了出处。它其实是在取数的话,把 evidence_role 标成 source;是在做计算的话,把计算挪进口径卡的表达式", + role = "" if cfg.get("evidence_role") else "(未设置时默认为「计算」)" + flag(f"{_who(feeder)}的产出提供给了{to},但它的「证据角色」是「计算」{role}:沙箱中计算出的数字无法追溯出处。" + "若该节点负责取数,请将「证据角色」设为「取数」;若负责计算,请把计算移到口径卡的表达式中", code="governed.caliber_compute_input", node_id=feeder.id, hard=True, field="evidence_role") elif feeder.type == NodeType.AGENT and not cfg.get("output_schema"): - flag(f"{_who(feeder)}给{to}供数,却没有配 output_schema:它交出来的是一段自由文字,口径卡读到的数核对不了" - "出处。给它配 output_schema 并开 cite_fields,每个字段都核对到查询结果里的那一格", + flag(f"{_who(feeder)}为{to}提供数据,但未配置「结构化输出 Schema」,交出的是自由文本,口径卡读取的数字" + "无法追溯出处。请配置「结构化输出 Schema」并开启「按出处核对字段」,使每个字段都核对到查询结果中的" + "对应单元格", code="governed.caliber_agent_schema", node_id=feeder.id, hard=True, field="output_schema") elif feeder.type == NodeType.AGENT and cfg.get("cite_fields") is not True: - flag(f"{_who(feeder)}给{to}供数,配了 output_schema 却没开 cite_fields:字段没有逐个核对到查询结果," - "口径卡读到的仍是模型报的数。打开 cite_fields", + flag(f"{_who(feeder)}为{to}提供数据,已配置「结构化输出 Schema」,但未开启「按出处核对字段」:字段没有" + "逐一核对到查询结果,口径卡读取的仍是模型给出的数字。请开启「按出处核对字段」", code="governed.caliber_agent_cite_fields", node_id=feeder.id, hard=True, field="cite_fields") elif feeder.type == NodeType.LLM: - flag(f"{_who(feeder)}给{to}供数:模型调用节点不调工具,写出来的数没有出处。改由 Agent(配 output_schema " - "并开 cite_fields)或「调用工具」节点取数", + flag(f"{_who(feeder)}为{to}提供数据:「模型调用」节点不调用工具,写出的数字没有出处。请改由 Agent" + "(配置「结构化输出 Schema」并开启「按出处核对字段」)或「调用工具」节点取数", code="governed.caliber_model_input", node_id=feeder.id, hard=True) @@ -585,12 +586,12 @@ async def unresolved_caliber_upgrades( if node.type == NodeType.SUBGRAPH: pinned = node.config.get("workflow_version") wf_id = node.config.get("workflow_id") - what = f"「{node.title}」(子工作流)钉在 v{pinned}" + what = f"「{node.title}」(子工作流)固定在 v{pinned}" elif node.type == NodeType.METRICS and isinstance(node.config.get("caliber_from"), dict): ref = node.config["caliber_from"] pinned, wf_id = ref.get("workflow_version"), ref.get("workflow_id") extra = {"caliber_node": ref.get("node_id")} - what = f"「{node.title}」(口径卡)钉住的口径卡在 v{pinned}" + what = f"「{node.title}」(口径卡)引用的口径卡固定在 v{pinned}" else: continue if not pinned or not wf_id or not str(pinned).isdigit(): @@ -608,8 +609,8 @@ async def unresolved_caliber_upgrades( if policy not in UPGRADE_POLICIES: errors.append( f"{what},但上游已有 v{latest}。" - f"正式运行前必须在节点上声明升版策略(upgrade_policy):" - + " / ".join(f"{k}({v})" for k, v in UPGRADE_POLICY_LABELS.items()) + f"发起正式运行前,请在节点的「{field_label('upgrade_policy')}」中选择一种处置:" + + _either(UPGRADE_POLICY_LABELS.values()) ) else: events.append( @@ -626,6 +627,12 @@ async def unresolved_caliber_upgrades( return errors, events +def _either(labels: Any) -> str: + """「甲」、「乙」或「丙」。""" + items = [f"「{v}」" for v in labels] + return items[0] if len(items) == 1 else "、".join(items[:-1]) + "或" + items[-1] + + #: 发起正式运行时记下「这次按不按受管出具」的那条事件(log · info,不进主流程) GOVERNANCE_CODE = "run_governance" @@ -637,9 +644,9 @@ def governance_note(*, governed: bool, workflow_name: str, version: int | None = 看工作流当时的 status。 """ which = f"「{workflow_name}」v{version}" if version else f"「{workflow_name}」" - message = (f"这次正式运行按受管级别出具:{which}是按受管级别发布的,之后改图、改级别都不影响这次" + message = (f"本次正式运行按受管级别出具:{which}以受管级别发布,之后修改工作流或发布级别不影响本次运行" if governed else - f"这次正式运行按已发布级别出具:{which}不是按受管级别发布的") + f"本次正式运行按已发布级别出具:{which}未以受管级别发布") return {"level": "info", "code": GOVERNANCE_CODE, "governed": governed, "message": message} diff --git a/backend/app/engine/guards.py b/backend/app/engine/guards.py index fc5e4395..8502f021 100644 --- a/backend/app/engine/guards.py +++ b/backend/app/engine/guards.py @@ -96,20 +96,20 @@ def call_key(name: str, args: dict[str, Any]) -> str: #: 收尾的原因 → (给模型的一句话, 给人看的提示) REASONS: dict[str, tuple[str, str]] = { "steps": ("步数上限用完了({max_steps} 步)", - "agent 用满了 {max_steps} 步。要跑全就把节点上的「最大步数」或设置里的默认步数调大;" - "如果它大部分步数花在逐张表查结构上,也可以在提示词里点明该查哪几张表。"), + "Agent 已用完 {max_steps} 步上限。如需完整结果,请调大节点的「最大步数」或设置中的默认步数;" + "如果大部分步数用于逐张表查询结构,可在提示词中指明要查的表。"), "stall": ("连续 {stall} 步没有拿到新信息(重复的调用,或者调用都失败了)", - "agent 连续 {stall} 步没有拿到新信息,已按查到的部分收尾。多半是提示词里的目标它查不到," - "或者工具的参数一直写不对:看一眼它最后几次调用。"), - "budget_tokens": ("这个节点的令牌预算用完了(已用 {used_tokens:,} / 上限 {budget_tokens:,})", - "agent 用完了令牌预算({budget_tokens:,}),已按查到的部分收尾。要跑全就把节点上的" - "「令牌预算」或设置里的默认预算调大,设置里也可以改成不限。"), + "Agent 连续 {stall} 步没有获得新信息,已根据已查到的内容收尾。可能是提示词中的目标无法查到," + "或工具参数持续有误,请检查 Agent 最后几次的工具调用。"), + "budget_tokens": ("这个节点的 token 预算用完了(已用 {used_tokens:,} / 上限 {budget_tokens:,})", + "Agent 已用完 token 预算({budget_tokens:,}),已根据已查到的内容收尾。如需完整结果," + "请调大节点的「token 预算」或设置中的默认预算,也可在设置中改为不限。"), "budget_usd": ("这个节点的金额预算用完了(已用 ${used_usd:.4f} / 上限 ${budget_usd:.4f})", - "agent 用完了金额预算(${budget_usd:.4f}),已按查到的部分收尾。要跑全就把节点上的" - "「金额预算」或设置里的默认预算调大,设置里也可以改成不限。"), + "Agent 已用完金额预算(${budget_usd:.2f}),已根据已查到的内容收尾。如需完整结果," + "请调大节点的「金额预算(美元)」或设置中的默认预算,也可在设置中改为不限。"), "context": ("对话已经接近模型的上下文上限(约 {used_context:,} / {window:,} token)", - "agent 的对话接近模型上下文上限,早期工具结果压缩过仍然不够,已按查到的部分收尾。" - "让它每次查更小的范围(比如 SQL 里加 LIMIT、只选需要的列),或者换一个窗口更大的模型。"), + "Agent 的对话已接近模型上下文上限,压缩早期工具结果后仍不够,已根据已查到的内容收尾。" + "请缩小每次查询的范围(如在 SQL 中加 LIMIT、只选需要的列),或换用上下文窗口更大的模型。"), } @@ -201,7 +201,7 @@ class Guard: if self.limits.budget_tokens and used_tokens >= self.limits.budget_tokens * 0.8 \ and "budget" not in self.reminded: self.reminded.add("budget") - notes.append(f"令牌预算已用 {used_tokens * 100 // self.limits.budget_tokens}%") + notes.append(f"token 预算已用 {used_tokens * 100 // self.limits.budget_tokens}%") if self.limits.budget_usd and float(usage.get("cost_usd") or 0) >= self.limits.budget_usd * 0.8 \ and "budget_usd" not in self.reminded: self.reminded.add("budget_usd") @@ -230,18 +230,17 @@ _SQUEEZED_TAIL = "⁣" # 不可见的记号:压缩过的不再压第二遍 def legacy_hint(max_steps: int, settled: bool) -> str: - """升级前的运行用的老说法(和以前一字不差)。""" + """升级前(没有护栏快照)的运行用的说法:只有步数这一种收尾原因。""" if settled: - return (f"agent 用满了 {max_steps} 步,这个结论是基于已经查到的部分给出的。" - "要跑全请把节点上的「最大步数」调大;如果它大部分步数花在逐张表" - "查结构上,也可以在提示词里点明该查哪几张表。") - return (f"agent 用满了 {max_steps} 步还没给出结论。" - "把节点上的「最大步数」调大;如果它大部分步数花在逐张表查结构上," - "也可以在提示词里点明该查哪几张表。") + return (f"Agent 已用完 {max_steps} 步上限,以上结论基于已查到的部分。" + "如需完整结果,请调大节点的「最大步数」;如果大部分步数用于逐张表查询结构," + "可在提示词中指明要查的表。") + return (f"Agent 已用完 {max_steps} 步上限,仍未给出结论。" + "请调大节点的「最大步数」;如果大部分步数用于逐张表查询结构,可在提示词中指明要查的表。") #: 结果里 limited 字段的说法,下游校验失败时拿来说明根源 LIMITED_LABEL = { - "steps": "用满了步数", "stall": "连续几步没拿到新信息", "budget_tokens": "用完了令牌预算", - "budget_usd": "用完了金额预算", "context": "对话接近上下文上限", + "steps": "步数用完", "stall": "连续多步没有获得新信息", "budget_tokens": "token 预算用完", + "budget_usd": "金额预算用完", "context": "对话接近上下文上限", } diff --git a/backend/app/engine/judge.py b/backend/app/engine/judge.py index 57400af2..0db8927e 100644 --- a/backend/app/engine/judge.py +++ b/backend/app/engine/judge.py @@ -35,7 +35,7 @@ from sqlalchemy import select from app.core.artifact_store import canonical_json, content_hash from app.core.artifact_store import load as load_artifact -from app.core.errors import describe_exception +from app.core.errors import describe_exception, not_configured from app.core.events import EventType from app.db.base import SessionLocal from app.db.models import Setting @@ -556,18 +556,29 @@ def _limit_words(key: str) -> str: def settings_problem(value: Any) -> str | None: """设置页写进来的 judge 这一组有什么问题,没问题返回 None。""" if not isinstance(value, dict): - return f"裁判设置(judge)要写成一个对象,写的是 {value!r}" + return f"「证据裁判」设置格式有误,需要是一个对象,当前为「{value}」" for key, item in value.items(): if key not in JUDGE_DEFAULTS: - return f"裁判设置里不认识「{key}」:能写的是 {'、'.join(JUDGE_DEFAULTS)}" + return (f"「证据裁判」设置中不支持「{key}」,可设置的项:" + + "、".join(f"「{SETTING_LABEL.get(k, k)}」" for k in JUDGE_DEFAULTS)) + label = SETTING_LABEL.get(key, key) if key in ("provider", "model"): if item is not None and not isinstance(item, str): - return f"{key} 要写模型接入的名字 / 模型 id(字符串),写 null 表示不指定,写的是 {item!r}" + return f"「{label}」需要填写模型接入的名称或模型 ID,留空表示不指定,当前为「{item}」" elif not _limit_ok(key, item): - return f"{key} 要写{_limit_words(key)},写 null 表示不限,写的是 {item!r}" + return f"「{label}」需要填写{_limit_words(key)},留空表示不限,当前为「{item}」" return None +#: 设置页「证据裁判」一组各项的叫法(前端 lib/terms.ts 的 JUDGE_SETTING_TEXT) +SETTING_LABEL = { + "provider": "裁判模型 · 接入", "model": "裁判模型 · 模型", + "report_max_claims": "每份报告最多裁判句数", "report_max_cost_usd": "每份报告的金额上限(美元)", + "report_timeout_s": "每份报告的时长上限(秒)", "click_max_cost_usd": "每次点击的金额上限(美元)", + "daily_max_usd": "每日金额上限(美元)", +} + + def sanitize_settings(stored: Any) -> dict[str, Any]: """库里存的 judge 一组 → 补齐默认的完整设置。存坏了的项(旧版本、手改)按默认,存了 null 的上限就是不限。""" stored = stored if isinstance(stored, dict) else {} @@ -801,24 +812,30 @@ def _unjudged(reason: str, rationale: str, *, judge: str | None, post_seal: bool def _limit_label(reason: str, budget: Budget, *, click: bool = False) -> str: if reason == "max_claims": - return f"每{'次' if click else '份报告'}最多判 {budget.max_claims} 句" + return f"每{'次点击' if click else '份报告'}最多裁判 {budget.max_claims} 句" if reason == "max_cost_usd": - return f"{'这次点击' if click else '这份报告'}的裁判金额上限 ${budget.max_cost_usd:g}" + return f"{'这次点击' if click else '这份报告'}的裁判金额上限 {_usd(budget.max_cost_usd)}" if reason == "daily_max_usd": - return f"全局每日裁判金额上限 ${budget.daily_max_usd:g}" + return f"全局每日裁判金额上限 {_usd(budget.daily_max_usd)}" return f"裁判时长上限 {budget.timeout_s:g} 秒" +def _usd(amount: Any) -> str: + """金额写两位小数($0.05);比一分钱还细的上限照实写,不四舍五入成别的数。""" + value = float(amount or 0) + return f"${value:.2f}" if round(value, 2) == value else f"${value:g}" + + def _why_unjudged(reason: str, budget: Budget, detail: str = "", *, click: bool = False) -> str: if reason in LIMITS: - return f"已到上限({_limit_label(reason, budget, click=click)}),这句没判" + return f"已达上限({_limit_label(reason, budget, click=click)}),这句未裁判" if reason == "error": - return f"裁判没跑成:{detail}"[:120] + return f"裁判失败:{detail}"[:120] if reason == "format": - return detail or "裁判给的结果格式不对,这句没判" + return detail or "裁判返回的结果格式有误,这句未裁判" if reason == "missing": - return "裁判没有给这句判定" - return "探索运行按需裁判:点开这句、请模型判断时才判" + return "裁判未对这句给出判定" + return "探索运行按需裁判:点开这句并请模型判断后才会裁判" async def run_request(request: JudgeRequest, *, spec: ModelSpec, budget: Budget, known: dict[str, Any] | None = None, @@ -850,8 +867,8 @@ async def run_request(request: JudgeRequest, *, spec: ModelSpec, budget: Budget, async with SessionLocal() as session: model, model_id = await get_chat_model(session, spec) except Exception as e: # noqa: BLE001 - 裁判模型没配好:这回判不了,报告照常 - why = str(e) if isinstance(e, ProviderNotConfigured) else describe_exception(e) - details["error"] = f"裁判模型用不了({why})" + why = not_configured(e) if isinstance(e, ProviderNotConfigured) else describe_exception(e) + details["error"] = f"裁判模型不可用({why})" judge = model_id or None priced = model is not None and pricing.find_pricing(model_id) is not None keys = {c.unit: request.unit_key(c, model_id) for c in request.cands} @@ -878,8 +895,8 @@ async def run_request(request: JudgeRequest, *, spec: ModelSpec, budget: Budget, stop(pending, "error", details["error"]) pending = [] elif pending and not priced and (budget.max_cost_usd is not None or budget.daily_max_usd is not None): - note = (f"模型「{model_id}」不在价格目录里,按令牌估不出金额:金额上限(每份报告、每次点击、每日)对它不起作用," - "费用只受句数、时长上限约束") + note = (f"模型「{model_id}」不在价格目录中,无法按 token 数估算金额:金额上限(每份报告、每次点击、每日)" + "对其无效,费用只受句数和时长上限约束") notes.append(note) emit(EventType.LOG, level="warn", code="judge_unpriced", message=note) @@ -974,9 +991,9 @@ async def run_request(request: JudgeRequest, *, spec: ModelSpec, budget: Budget, labels = "、".join(_limit_label(r, label, click=click) for r in hit) n = sum(outcome["unjudged"].get(r, 0) for r in hit) emit(EventType.LOG, level="warn", code="judge_limit", limits=hit, unjudged=n, - message=f"结论句裁判已到上限({labels}):{n} 句没判,记为未裁判;已判的保留") + message=f"结论句裁判已达上限({labels}):{n} 句未裁判,已裁判的结果保留") if failed := [g for r, g in outcome["_gaps"] if r not in LIMITS]: - emit(EventType.LOG, level="warn", code="judge_failed", message="结论句裁判没跑完:" + ";".join(failed)) + emit(EventType.LOG, level="warn", code="judge_failed", message="结论句裁判未完成:" + ";".join(failed)) outcome.pop("_gaps") return outcome @@ -995,7 +1012,7 @@ def _take(items: list[Any], batch: list[Candidate], request: JudgeRequest, verdi continue status = str(item.get("verdict") or "").strip().lower() if status not in JUDGED: - verdicts[uid] = _unjudged("format", f"裁判给的判定「{str(item.get('verdict'))[:20]}」不认识,这句没判", + verdicts[uid] = _unjudged("format", f"裁判返回的判定「{str(item.get('verdict'))[:20]}」无法识别,这句未裁判", judge=judge, post_seal=post_seal) continue used = item.get("used") if isinstance(item.get("used"), list) else [] @@ -1022,13 +1039,13 @@ def _outcome(request: JudgeRequest, verdicts: dict[str, dict[str, Any]], budget: if not n or reason == "on_demand": continue if reason in LIMITS: - text = f"有 {n} 句结论没裁判:已到上限({_limit_label(reason, label, click=click)})" + text = f"有 {n} 句结论未裁判:已达上限({_limit_label(reason, label, click=click)})" elif reason == "error": - text = f"有 {n} 句结论没裁判:裁判调用失败({details.get('error') or '原因不明'})" + text = f"有 {n} 句结论未裁判:裁判调用失败({details.get('error') or '原因不明'})" elif reason == "format": - text = f"有 {n} 句结论没裁判:裁判给的结果格式不对" + text = f"有 {n} 句结论未裁判:裁判返回的结果格式有误" else: - text = f"有 {n} 句结论裁判漏判了" + text = f"有 {n} 句结论未获得裁判结果" gaps.append((reason, text)) return { "verdicts": {c.unit: verdicts[c.unit] for c in sorted(request.cands, key=lambda c: c.order)}, diff --git a/backend/app/engine/labels.py b/backend/app/engine/labels.py new file mode 100644 index 00000000..ab73bb3b --- /dev/null +++ b/backend/app/engine/labels.py @@ -0,0 +1,176 @@ +"""配置项和取值在界面上的叫法。 + +校验、发布门禁、自动修复、升级预览、运行报错里提到节点配置时,写检查器上的中文标签, +不写键名和枚举值:用户在界面上看到的是「指标来自」「计入缺口」,从没见过 metrics_from、 +require_citation。键名只在配置界面里字段自己旁边出现。 + +叫法以前端为准:字段标签对照 frontend/src/canvas/nodeDefs.ts 的 label,出具契约里的键对照 +canvas/issues.ts 的 CONTRACT_KEYS / SUB_KEYS,结论句裁判对照 lib/terms.ts 的 JUDGE_FIELD_LABEL。 +前端改了叫法,这里跟着改;新写报错时从这里取,别在各处手写键名。 + +取值的叫法(option_label)是放进句子里的短说法:前端下拉里的选项文字后面常带一句用途说明 +(「算违规,要求重写(默认)」),句子里只取前半句。 +""" +from __future__ import annotations + +from typing import Any + +#: 节点类型的叫法,和前端 lib/terms.ts 的 NODE_TYPE_LABEL 一致 +TYPE_LABEL: dict[str, str] = { + "input": "输入", "output": "成果", "llm": "模型调用", "agent": "Agent", + "supervisor": "多 Agent 协作", "tool": "调用工具", "code": "沙箱代码", + "branch": "条件分支", "loop": "循环", "subgraph": "子工作流", + "memory": "长期记忆", "retrieve": "知识检索", "transform": "数据整形", + "human": "人工审批", "validate": "结构校验", "metrics": "口径卡", "report": "报告撰写", +} + +#: 各类节点共用的字段名(nodeDefs.ts)。同一个键在不同节点上叫法不同的,见 _FIELD_BY_TYPE +FIELD_LABEL: dict[str, str] = { + "label": "节点名称", + # 模型相关 + "model": "模型", "thinking": "思考模式", "effort": "投入程度", "temperature": "温度", + "max_tokens": "最大输出 token", + # 通用 + "approval": "审批策略", "assign_to": "结果存为变量", "skip_if": "跳过条件", + "retries": "失败重试次数", "on_error": "出错时", + # 模型调用、Agent + "system": "系统提示", "prompt": "用户提示", "skills": "挂载 Skill", + "output_schema": "结构化输出 Schema", "use_history": "带上对话历史", + "tools": "可用工具", "max_steps": "最大步数", "budget_tokens": "token 预算", + "budget_usd": "金额预算(美元)", "parallel_tools": "并行执行工具", "cite_fields": "按出处核对字段", + # 多 Agent 协作 + "goal": "团队目标", "agents": "团队成员", "max_rounds": "最多轮数", "on_exhausted": "用完轮数时", + "max_parallel": "每轮最大并行成员数", + # 调用工具、沙箱代码 + "tool": "工具", "args": "参数", "language": "语言", "code": "代码", "timeout": "超时(秒)", + "memory_mb": "内存上限(MB)", "network": "允许联网", "isolation": "隔离档位", + "fail_fast": "执行失败即中断", "evidence_role": "证据角色", + # 条件分支、循环、子工作流 + "cases": "分支", "instruction": "分类说明", "items": "列表来源", "item_var": "当前项变量名", + "condition": "继续条件", "max_iterations": "最大迭代次数", + "workflow_id": "工作流", "workflow_version": "固定版本", "upgrade_policy": "上游发布新版本时", + # 数据整形、结构校验 + "template": "模板", "expression": "表达式", "schema": "JSON Schema", "max_retries": "最多返工次数", + "repair_with_llm": "让模型修复", + # 成果、输入 + "fields": "成果字段", "contract": "出具契约", + # 报告撰写 + "instructions": "写作要求", "metrics_from": "指标来自", "numbers": "未引用的数字", + "on_violation": "重写后仍有违规时", "max_repairs": "最多重写次数", "claims": "未附依据的结论句", + "judge": "结论句裁判", "entities": "表名、字段名", + # 口径卡 + "caliber_from": "口径卡来源", "caliber": "口径名称", "caliber_version": "口径版本", + "metrics": "指标定义", "on_missing": "缺输入时", + # 全图 + "defaults": "工作流默认设置", +} + +_FIELD_BY_TYPE: dict[str, dict[str, str]] = { + "input": {"fields": "输入字段"}, + "agent": {"prompt": "任务"}, + "branch": {"mode": "判断方式", "input": "待分类内容"}, + "loop": {"mode": "循环方式"}, + "subgraph": {"input": "传入参数"}, + "memory": {"action": "操作", "scope": "作用域", "query": "检索内容", "limit": "返回条数", + "content": "记住的内容", "kind": "记忆类型", "importance": "重要程度"}, + "retrieve": {"query": "检索问题", "collection": "知识库", "limit": "返回片段数", "rerank": "重排", + "min_score": "最低分数"}, + "transform": {"mode": "方式"}, + "human": {"mode": "审批方式", "title": "标题", "message": "展示给审批人的内容", "draft": "草稿内容", + "stop_on_reject": "驳回即终止运行"}, + "validate": {"source": "待校验内容", "fail_fast": "校验失败即中断"}, +} + +#: 出具契约里的键(canvas/issues.ts 的 CONTRACT_KEYS、SUB_KEYS) +CONTRACT_KEY_LABEL: dict[str, str] = { + "metrics_from": "指标来自", "report_from": "报告来自", "required": "必需指标", "expected": "期望指标", + "strict": "严格模式", "narrative": "叙述", "cells": "单元格引用", "allow_numbers": "允许无出处的数字", + "claims": "未附依据的结论句", "on_uncited": "未附依据时", +} + +#: 报告撰写节点 judge 子配置(lib/terms.ts 的 JUDGE_FIELD_LABEL) +JUDGE_FIELD_LABEL: dict[str, str] = { + "provider": "裁判模型 · 接入", "model": "裁判模型", "max_claims": "最多裁判句数", + "max_cost_usd": "金额上限(美元)", "timeout_s": "时长上限(秒)", + "rewrite_once": "证据不支持的句子退回改写一次", "on_unsupported": "证据不支持时", +} + +#: 取值的短说法:键 → {值: 叫法}。前端下拉的选项文字去掉后半句的用途说明 +_OPTION_LABEL: dict[str, dict[str, str]] = { + "numbers": {"strict": "计为违规,要求重写", "off": "仅标注,不要求重写"}, + "on_violation": {"flag": "正常产出,并标注违规之处", "fail": "判为失败"}, + "claims": {"off": "不参与出具判档", "require_citation": "计入缺口", "judge": "计入缺口并由模型逐句判断"}, + "entities": {"link": "核对", "off": "不核对"}, + "evidence_role": {"source": "取数", "compute": "计算"}, + "on_uncited": {"ignore": "仅标注,不计入缺口", "degrade": "计入缺口、出具降档", "withhold": "不予出具"}, + "on_unsupported": {"degrade": "出具降档", "withhold": "不予出具"}, + "on_exhausted": {"fail": "判为失败", "degrade": "降档交付"}, + "on_missing": {"null": "记为空值,交给出具契约判档"}, + "on_error": {"continue": "记录错误并继续"}, + "approval": {"dangerous": "仅危险工具需要审批", "always": "每次调用都审批", "never": "全部无需审批"}, + "upgrade_policy": {"recompute": "用新口径回算历史", "dual": "新旧口径并列展示", + "incomparable": "标注与历史不可比"}, + "isolation": {"strict": "严格:microVM", "fast": "快速:系统沙箱"}, + "thinking": {"summarized": "开启并显示摘要", "adaptive": "开启但不显示", "off": "关闭"}, +} +#: 让人在几个取值之间选时的完整选项文字(发布前修复的候选),和检查器下拉一致,只去掉「(默认)」 +CHOICE_LABEL: dict[str, dict[str, str]] = { + "claims": {"off": "不处理:不参与出具判档", "require_citation": "计入缺口:出具按档位降档", + "judge": "计入缺口,并由模型逐句判断证据是否支持"}, +} +_MODE_LABEL: dict[str, dict[str, str]] = { + "branch": {"expression": "表达式判断", "llm": "让模型分类"}, + "loop": {"foreach": "遍历列表", "while": "条件成立时重复"}, + "transform": {"template": "文本模板", "expression": "表达式", "json": "JSON 模板"}, + "human": {"approve": "批准 / 驳回", "input": "补充输入", "edit": "编辑草稿"}, +} + +#: 分支、循环、人工审批的出口在画布上的叫法(nodeDefs.ts 的 handlesOf) +HANDLE_LABEL: dict[str, str] = { + "default": "其他", "body": "循环体", "done": "结束", "approved": "批准", "rejected": "驳回", +} + +#: 出具档位(lib/terms.ts 的 ISSUANCE_LABEL) +ISSUANCE_LABEL: dict[str, str] = {"formal": "完整出具", "degraded": "降档出具", "withheld": "不予出具"} + + +def type_label(node_type: Any) -> str: + """节点类型的叫法;不认识的类型原样返回。""" + return TYPE_LABEL.get(str(node_type), str(node_type)) + + +def field_label(key: str, node_type: Any = None) -> str: + """节点配置键的叫法。带点号的路径逐段翻译:「出具契约 · 指标来自」「结论句裁判 · 金额上限(美元)」。 + 认不出的段原样留着——宁可露一个键名,也不编一个界面上没有的名字。""" + head, _, rest = str(key).partition(".") + kind = str(node_type) if node_type is not None else "" + base = _FIELD_BY_TYPE.get(kind, {}).get(head) or FIELD_LABEL.get(head) or head + if not rest: + return base + sub = JUDGE_FIELD_LABEL if head == "judge" else CONTRACT_KEY_LABEL + return " · ".join([base, *(sub.get(part, part) for part in rest.split("."))]) + + +def contract_label(key: str) -> str: + """出具契约里一个键的叫法(不带「出具契约」前缀)。""" + return CONTRACT_KEY_LABEL.get(key, key) + + +def judge_label(key: str) -> str: + """judge 子配置一项的叫法(不带「结论句裁判」前缀)。""" + return JUDGE_FIELD_LABEL.get(key, key) + + +def option_label(key: str, value: Any, node_type: Any = None) -> str: + """某个配置键取某个值时的叫法。认不出的值原样返回,交给调用方加引号。""" + last = str(key).rsplit(".", 1)[-1] + if last == "mode" and node_type is not None: + return _MODE_LABEL.get(str(node_type), {}).get(str(value), str(value)) + if isinstance(value, bool): + return "开启" if value else "关闭" + return _OPTION_LABEL.get(last, {}).get(str(value), str(value)) + + +def q(text: Any) -> str: + """加「」:给用户看的值一律这样括起来,不用 repr 的英文单引号。""" + return f"「{text}」" diff --git a/backend/app/engine/nodes/control.py b/backend/app/engine/nodes/control.py index f8d208bb..0b44b8c7 100644 --- a/backend/app/engine/nodes/control.py +++ b/backend/app/engine/nodes/control.py @@ -19,7 +19,7 @@ async def run_branch(state: GraphState, ctx: NodeContext) -> dict[str, Any]: """条件分支。两种模式:表达式判断,或让模型做语义分类。""" cases = ctx.cfg("cases", []) or [] if not cases: - raise NodeError(ctx.node.id, "分支节点没有配置任何条件") + raise NodeError(ctx.node.id, "「条件分支」节点没有配置任何条件") mode = ctx.cfg("mode", "expression") tctx = template_context(state) @@ -39,9 +39,9 @@ async def run_branch(state: GraphState, ctx: NodeContext) -> dict[str, Any]: chosen, reason = key, f"命中条件:{expr}" break except ExpressionError as e: - raise NodeError(ctx.node.id, f"分支条件写错了({expr}):{e}") from e + raise NodeError(ctx.node.id, f"分支条件有误({expr}):{e}") from e else: - reason = "所有条件都不满足,走 default" + reason = "所有条件都不满足,走「其他」出口" ctx.emit(EventType.EDGE_TAKEN, branch=chosen, reason=reason, mode=mode) return { @@ -155,13 +155,13 @@ async def run_loop(state: GraphState, ctx: NodeContext) -> dict[str, Any]: try: keep_going = eval_condition(condition, tctx) except ExpressionError as e: - raise NodeError(ctx.node.id, f"循环条件写错了:{e}") from e + raise NodeError(ctx.node.id, f"循环条件有误:{e}") from e hit_limit = cursor >= max_iter if hit_limit: ctx.emit( EventType.LOG, level="warn", - message=f"循环达到上限 {max_iter} 次,强制退出", code="loop_limit", + message=f"循环已达上限 {max_iter} 次,已强制结束", code="loop_limit", ) decision = "body" if keep_going else "done" diff --git a/backend/app/engine/nodes/human.py b/backend/app/engine/nodes/human.py index 95103aab..83e83d95 100644 --- a/backend/app/engine/nodes/human.py +++ b/backend/app/engine/nodes/human.py @@ -26,7 +26,7 @@ async def run_human(state: GraphState, ctx: NodeContext) -> dict[str, Any]: "kind": "human_node", "node_id": ctx.node.id, "mode": mode, - "title": ctx.render_str(ctx.cfg("title", "需要你确认"), state), + "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), @@ -47,7 +47,7 @@ async def run_human(state: GraphState, ctx: NodeContext) -> dict[str, Any]: "__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 '未说明原因'}") + raise NodeError(ctx.node.id, f"人工驳回:{result['note'] or '未说明原因'}") else: # edit / input # 驳回在这两种模式下以前是个摆设:__decision__ 硬编码成 approved, # approved 字段看都不看。界面上按钮在、toast 说"已驳回",运行却照常 @@ -86,7 +86,7 @@ async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]: schema = ctx.cfg("schema") if not schema: - raise NodeError(ctx.node.id, "校验节点需要一个 JSON Schema") + raise NodeError(ctx.node.id, "「结构校验」节点需要填写 JSON Schema") source_cfg = ctx.cfg("source", "{{ last_message }}") original = ctx.render(source_cfg, state) if not isinstance(source_cfg, str) else ctx.render_str(source_cfg, state) @@ -123,7 +123,7 @@ async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]: updates["vars"] = {var_name: value} return updates except jsonschema.ValidationError as e: - path = "/".join(str(p) for p in e.absolute_path) or "(根)" + path = "/".join(str(p) for p in e.absolute_path) or "(根)" errors = [f"{path}: {e.message}"] if not invented: @@ -137,7 +137,7 @@ async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]: result = {"valid": False, "data": value, "attempts": attempt, "errors": errors} if ctx.cfg("fail_fast", True): - raise NodeError(ctx.node.id, f"结构化校验未通过:{'; '.join(errors)}{_upstream_cut_short(state, ctx)}") + raise NodeError(ctx.node.id, f"结构化校验未通过:{';'.join(errors)}{_upstream_cut_short(state, ctx)}") return {"nodes": {ctx.node.id: result}, **({"usage": usage} if usage else {})} @@ -151,14 +151,14 @@ def _upstream_cut_short(state: GraphState, ctx: NodeContext) -> str: nodes = ctx.run.spec.node_map() cut = [ - f"「{nodes[nid].title if nid in nodes else nid}」{LIMITED_LABEL.get(out['limited'], '提前收了尾')}" + f"「{nodes[nid].title if nid in nodes else nid}」因{LIMITED_LABEL.get(out['limited'], '达到上限')}" for nid, out in (state.get("nodes") or {}).items() if isinstance(out, dict) and out.get("limited") ] if not cut: return "" - return (f"。上游{'、'.join(cut)},没等查全就收了尾,缺的字段多半出在这里:" - "看它的收尾提示,把对应的上限调大或者缩小它要查的范围") + return (f"。上游{'、'.join(cut)}提前结束,缺失的字段很可能源于此。" + "请查看其结束提示,调大相应上限或缩小查询范围") def _coerce_json(raw: Any) -> tuple[Any, str | None]: @@ -312,19 +312,19 @@ def _invented(value: Any, original: Any, schema: dict[str, Any]) -> list[str]: return elif isinstance(node, (int, float)): if not known_number(float(node)): - found.append(f"{path or '(根)'}={node}") + found.append(f"{path or '(根)'}={node}") elif isinstance(node, str): s = node.strip() if not s: if '""' not in text: - found.append(f'{path or "(根)"}=""') + found.append(f'{path or "(根)"}=""') return if s in allowed: return if _NUMBER.fullmatch(s): # 写成字符串的数字照数字查:"0" 不能因为 SQL 里有个 > 0 就算有出处 if not known_number(float(s.replace(",", ""))): - found.append(f"{path or '(根)'}={s[:40]}") + found.append(f"{path or '(根)'}={s[:40]}") return if s.lower() in lowered: return @@ -333,7 +333,7 @@ def _invented(value: Any, original: Any, schema: dict[str, Any]) -> list[str]: known_number(float(p)) if p[0].isdigit() else p.lower() in lowered for p in pieces ) if not ok: - found.append(f"{path or '(根)'}={s[:40]}") + found.append(f"{path or '(根)'}={s[:40]}") walk(value, "") return found diff --git a/backend/app/engine/nodes/io.py b/backend/app/engine/nodes/io.py index e3e5ca01..2fc964ad 100644 --- a/backend/app/engine/nodes/io.py +++ b/backend/app/engine/nodes/io.py @@ -185,7 +185,7 @@ def _apply_contract( # 不能当作"这次没有指标要查" unresolved.append(source) if unresolved: - gaps.append(f"指标源未解析:{', '.join(unresolved[:5])}") + gaps.append(f"指标来源未解析:{'、'.join(unresolved[:5])}") # 引用模式下,缺输入记成空值的指标(口径卡 on_missing=null)就是缺:报告里引用不了它, # 也不能因为 id 在清单里就算「齐了」。旧模式照旧只看 id,行为不变 @@ -207,9 +207,9 @@ def _apply_contract( # 模板取不到路径时 render 出来是空串,所以"声明了叙述但渲染成空"必须单独识别: # 节点改名、vars 写错都会让回指校验静默变成空操作 if declared_narrative.strip() and not narrative.strip(): - gaps.append("叙述模板渲染为空(路径可能写错了)") + gaps.append("叙述模板渲染为空(路径可能有误)") elif not declared_narrative.strip(): - gaps.append("契约没有声明叙述,数字回指未执行") + gaps.append("出具契约未设置「叙述」,未执行数字追溯") trace = ( trace_numbers(narrative, metrics, allow=contract.get("allow_numbers")) @@ -220,7 +220,7 @@ def _apply_contract( # 声明了 metrics_from 却一个指标都没收到,同样是"没查成" if sources and not metrics: - gaps.append("指标集为空,叙述里的数字无从回指") + gaps.append("指标集为空,叙述中的数字无法追溯") # 上游有协作团队用完轮数、按降档交付的:叙述里的话不是调度者认可的结论, # 数字全都对得上也不能盖「完整出具」 @@ -228,7 +228,7 @@ def _apply_contract( for node_id, payload in nodes.items(): if isinstance(payload, dict) and payload.get("exhausted"): gaps.append(f"协作团队「{titles.get(node_id, node_id)}」用完 {payload.get('rounds', '?')} " - "轮仍未完成,交来的是成员最后的原话") + "轮仍未完成,交付的是成员最后的回复") tier = decide_tier( missing_required=missing_required, @@ -319,26 +319,26 @@ def _check_citations( 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}」不是报告撰写节点,引用核对未执行") + gaps.append(f"出具契约的「报告来自」指向的「{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}」没有产出报告文档(没跑到、被跳过或者失败了)," - "引用核对未执行") + gaps.append(f"报告撰写节点「{node.title}」没有产出报告文档(未执行、被跳过或失败)," + "未执行引用核对") return out out["doc_artifact"] = doc_artifact try: doc = load(doc_artifact) except ValueError: - gaps.append(f"报告「{node.title}」的文档和它的哈希对不上,疑似被改过,引用核对未执行") + gaps.append(f"报告「{node.title}」的文档与其哈希不一致,可能已被修改,未执行引用核对") return out if not isinstance(doc, dict): - gaps.append(f"报告「{node.title}」的文档在工件库里取不回来,引用核对未执行") + 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}」的文档和这次运行里它的产出对不上,引用核对未执行") + gaps.append(f"报告「{node.title}」的文档与本次运行中的产出不一致,未执行引用核对") return out catalog = report_catalog(state, spec, node) @@ -366,15 +366,15 @@ def _check_citations( broken.append(v["message"]) if broken: more = f"等 {len(broken)} 处" if len(broken) > 1 else "" - gaps.append(f"报告「{node.title}」的文档没通过复核:{broken[0]}{more}") + gaps.append(f"报告「{node.title}」的文档未通过复核:{broken[0]}{more}") unknown, unverified = suspicious["unknown_entity"], suspicious["unverified_entity"] if unknown and governed: # 用户拍板:可疑实体在受管级别的正式出具里按「有缺口」降档,不拦截——反引号里的一个业务词 # 也可能被当成名字,为它不予出具太重;探索运行、已发布级别只标注 names = "".join(f"「{n}」" for n in dict.fromkeys(u["name"] for u in unknown[:5])) more = "等" if len(unknown) > 5 else "" - gaps.append(f"报告「{node.title}」里有 {len(unknown)} 处可疑实体({names}{more}):本次运行的表结构、查询、" - "结果列里都没有这些名字,可能是编造的") + gaps.append(f"报告「{node.title}」中有 {len(unknown)} 处可疑实体({names}{more}):本次运行的表结构、查询和" + "结果列中都没有这些名字,可能是编造的") if unknown or unverified: # 表结构快照不全时核对不了的名字(unverified)在哪个级别都只标注 out["entities"] = {"unknown": unknown[:_LISTED], "unverified": unverified[:_LISTED], @@ -411,7 +411,7 @@ def _check_citations( for name in edited: gaps.append(f"成果字段「{name}」改动了报告,无法逐段对应") if not (mine and mine["verbatim"]) and not edited: - gaps.append(f"成果里没有哪个字段是报告「{node.title}」的原文:读者看到的内容没有经过引用核对") + gaps.append(f"成果中没有任何字段是报告「{node.title}」的原文:读者看到的内容未经过引用核对") return out @@ -439,7 +439,7 @@ def _claims(out: dict[str, Any], contract: dict[str, Any], payload: dict[str, An 这里只标注。契约要 judge、报告节点却没开的,照实记缺口:出口替不了报告节点去裁判。 数的是这里重新核对出来的 uncited,不信文档里记的 cites。升级前写的报告(节点产出里没有 claims 这个键, - 包括跨着升级还没跑完的运行)一律不管,契约写了也照旧记「这一版还不支持」。 + 包括跨着升级还没跑完的运行)一律不管,契约写了也只记一条缺口:报告生成于升级前,结论句未核对。 """ written = payload.get("claims") if isinstance(payload, dict) else None # 报告节点升级后才在产出里记 claims(off 也记):没有这个键就是升级前写的报告 @@ -453,11 +453,10 @@ def _claims(out: dict[str, Any], contract: dict[str, Any], payload: dict[str, An wanted = declared.get("on_uncited") if isinstance(declared, dict) else None asks.append(wanted if wanted in _ON_UNCITED else "degrade") elif name not in (None, "", "off"): - out["gaps"].append("契约声明了结论句检查(claims),这一版还不支持,结论句没有核对") + out["gaps"].append("出具契约要求核对结论句,但这份报告生成于系统升级前,没有结论句核对记录,结论句未核对") judged = upgraded and written == "judge" if upgraded and name == "judge" and not judged: - out["gaps"].append(f"契约要求结论句由模型裁判(claims: judge),报告「{title}」没有开 claims: judge," - "结论句没有裁判") + out["gaps"].append(f"出具契约要求结论句由模型裁判,但报告「{title}」未开启模型裁判,结论句未裁判") if not asks: return on_uncited = max(asks, key=_ON_UNCITED.index) @@ -478,7 +477,7 @@ def _claims(out: dict[str, Any], contract: dict[str, Any], payload: dict[str, An if not isinstance(summary, dict): # 报告节点开了 judge、文档里却没有裁判摘要(不该发生):当作没判,不能判完整出具 summary = {"mode": "inline", "counts": {}, "unjudged": {}, "limits_hit": [], "complete": False, - "gaps": ["开了 claims: judge,文档里却没有裁判结果,结论句没有裁判"]} + "gaps": ["已开启模型裁判,但文档中没有裁判结果,结论句未裁判"]} asked = [summary.get("on_unsupported")] if name == "judge" and isinstance(declared, dict): asked.append(declared.get("on_unsupported")) @@ -572,11 +571,11 @@ async def run_transform(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if mode == "expression": expr = ctx.cfg("expression", "") if not expr: - raise NodeError(ctx.node.id, "整形节点没有填表达式") + raise NodeError(ctx.node.id, "「数据整形」节点还没有填写表达式") try: output = eval_expression(expr, tctx) except ExpressionError as e: - raise NodeError(ctx.node.id, f"表达式错误:{e}") from e + raise NodeError(ctx.node.id, f"表达式有误:{e}") from e elif mode == "template": output = ctx.render_str(ctx.cfg("template", ""), state) elif mode == "json": @@ -587,7 +586,7 @@ async def run_transform(state: GraphState, ctx: NodeContext) -> dict[str, Any]: except json.JSONDecodeError as e: raise _json_error(e, str(template or ""), tctx, ctx) from e else: - raise NodeError(ctx.node.id, f"未知的整形模式:{mode}") + raise NodeError(ctx.node.id, f"不支持的整形方式:{mode}") updates: dict[str, Any] = {"nodes": {ctx.node.id: output}} var_name = ctx.cfg("assign_to", "") @@ -608,7 +607,7 @@ _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 过滤器输出" +TEMPLATE_HINT = "请检查模板中的引号和逗号,字符串值需使用 | json 过滤器输出" #: 解析器在这一段的头一个字上要的是这些:前一个值在模板里已经写完了,缺的是模板里的标点 _DELIMITED = ("Expecting ',' delimiter", "Expecting ':' delimiter", "Extra data") @@ -638,9 +637,11 @@ def _json_error(e: json.JSONDecodeError, template: str, tctx: dict[str, Any], ct 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" + fix = ("如需模型输出结构化数据,请为其配置「结构化输出 Schema」;数字需要进入口径卡时," + "请改用 Agent 并开启「按出处核对字段」" if node.type == NodeType.LLM else - "让模型交结构化数据请用 output_schema + cite_fields,别用整形节点解析它写的文字") + "如需模型输出结构化数据,请配置「结构化输出 Schema」并开启「按出处核对字段」," + "不要用「数据整形」节点解析模型写的文字") return NodeError(ctx.node.id, f"上游「{node.title}」输出的不是合法 JSON({where}附近),{reason};{fix}") @@ -675,14 +676,14 @@ def _diagnose(template: str, tctx: dict[str, Any], ctx: NodeContext, 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} }}}} 取出来是空的,这里缺一个值:检查路径写对没有、前面的节点有没有产出" + 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(文字自带引号),外面不要再加引号" + 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: @@ -706,19 +707,19 @@ def _diagnose(template: str, tctx: dict[str, Any], ctx: NodeContext, def _needs_json(expr: str, model: bool) -> str: what = "模型写的文字" if model else "一段文字" - return f"模板里 {{{{ {expr} }}}} 是{what},放进 JSON 要写成 {{{{ {expr} | json }}}}(外面不要再加引号)" + return f"模板里 {{{{ {expr} }}}} 是{what},放入 JSON 时请写成 {{{{ {expr} | json }}}}(外面不要再加引号)" def _why(text: str, at_end: bool) -> str: """上游写的 JSON 为什么解析不了,按看得出来的实情说。""" body = text.lstrip() if body.startswith("```"): - return "它把 JSON 包在了 ``` 代码块里" + return "模型把 JSON 包在了 ``` 代码块中" if at_end and _unclosed(text): - return "它写的 JSON 没有收尾,可能写到一半被截断了" + return "模型输出的 JSON 不完整,可能在中途被截断" if not body.startswith(("{", "[")): - return "它写的是一段文字,不是 JSON" - return "常见原因是字符串里有没转义的英文引号" + return "模型输出的是一段文字,而不是 JSON" + return "常见原因是字符串中有未转义的英文引号" def _writes_json(text: str) -> bool: diff --git a/backend/app/engine/nodes/knowledge.py b/backend/app/engine/nodes/knowledge.py index 8e2c8d8d..501f268c 100644 --- a/backend/app/engine/nodes/knowledge.py +++ b/backend/app/engine/nodes/knowledge.py @@ -37,7 +37,7 @@ async def run_memory(state: GraphState, ctx: NodeContext) -> dict[str, Any]: elif action == "write": content = ctx.render_str(ctx.cfg("content", ""), state) if not content.strip(): - raise NodeError(ctx.node.id, "记忆写入节点没有内容") + raise NodeError(ctx.node.id, "「长期记忆」节点没有填写要记住的内容") item = await store.remember( session, scope=scope, @@ -51,7 +51,7 @@ async def run_memory(state: GraphState, ctx: NodeContext) -> dict[str, Any]: removed = await store.clear_scope(session, scope) result = {"cleared": removed, "scope": scope} else: - raise NodeError(ctx.node.id, f"未知的记忆操作:{action}") + raise NodeError(ctx.node.id, f"不支持的记忆操作:{action}") # 写入必须看得见:这是往长期记忆里存东西,会影响以后每一次对话。 # 以前发的是 info 日志,而解码层丢弃所有 info,等于系统背着用户记了东西 @@ -75,7 +75,7 @@ async def run_retrieve(state: GraphState, ctx: NodeContext) -> dict[str, Any]: """知识库检索节点。输出既有结构化命中列表,也有拼好的上下文文本。""" query = ctx.render_str(ctx.cfg("query", "{{ last_message }}"), state) if not query.strip(): - raise NodeError(ctx.node.id, "检索节点没有查询内容") + raise NodeError(ctx.node.id, "「知识检索」节点没有填写检索问题") collection = ctx.render_str(ctx.cfg("collection", "") or ctx.run.collection, state) limit = int(ctx.cfg("limit", 5) or 5) @@ -117,7 +117,9 @@ async def run_retrieve(state: GraphState, ctx: NodeContext) -> dict[str, Any]: async with SessionLocal() as session: model, _ = await get_chat_model(session, spec) except ProviderNotConfigured as e: - degraded.append(f"重排用不了:{e}") + from app.core.errors import not_configured + + degraded.append(f"重排不可用:{not_configured(e)}") model = None hits = await rerank(model, query, hits, top_n=limit, on_note=degraded.append) else: diff --git a/backend/app/engine/nodes/llm.py b/backend/app/engine/nodes/llm.py index e31bf063..5e1c0aea 100644 --- a/backend/app/engine/nodes/llm.py +++ b/backend/app/engine/nodes/llm.py @@ -12,7 +12,7 @@ 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.errors import describe_exception, not_configured, raw_detail from app.core.events import EventType from app.db.base import SessionLocal from app.db.models import Skill @@ -131,7 +131,10 @@ async def _build_messages(state: GraphState, ctx: NodeContext) -> list[BaseMessa if prompt: messages.append(HumanMessage(content=prompt)) if not messages: - raise NodeError(ctx.node.id, "没有可发送的内容:system 和 prompt 都是空的") + from app.engine.labels import field_label + + raise NodeError(ctx.node.id, f"没有可发送给模型的内容:「{field_label('system', ctx.node.type)}」" + f"和「{field_label('prompt', ctx.node.type)}」都为空") return messages @@ -167,14 +170,14 @@ def explain_model_error(exc: Exception, model_id: str) -> str: text = str(exc) if "invalid_model" in text or "model does not exist" in text.lower(): return ( - f"模型「{model_id}」在这个供应商上不存在,或者当前 key 没有它的权限。" - f"去「设置 → 供应商」把模型列表改成它真正提供的 id," - f"或者在节点上换一个模型。" + f"模型「{model_id}」在当前模型接入中不存在,或当前 API Key 无权使用该模型。" + f"请在「设置 → 模型接入」中把可选模型改为服务实际提供的模型 ID," + f"或在节点上换一个模型。" ) if "insufficient" in text.lower() or "quota" in text.lower(): - return f"模型「{model_id}」的额度用完了:{text[:200]}" + return f"模型「{model_id}」的额度已用完:{text[:200]}" return (f"调用模型「{model_id}」失败:{describe_exception(exc)}。" - "稍后重试;反复失败就去「设置 → 模型接入」测一下这个模型") + "请稍后重试;如持续失败,请到「设置 → 模型接入」测试该模型") async def _invoke_streaming( @@ -205,7 +208,7 @@ async def _invoke_streaming( response = await model.ainvoke(messages) except Exception as e: # noqa: BLE001 ctx.emit(EventType.LOG, level="warn", - message=f"流式失败,回退非流式:{explain_model_error(e, model_id)}", + message=f"流式输出失败,已改用非流式调用:{explain_model_error(e, model_id)}", code="stream_fallback") try: response = await model.ainvoke(messages) @@ -245,7 +248,7 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]: try: model, model_id = await get_chat_model(session, spec) except ProviderNotConfigured as e: - raise NodeError(ctx.node.id, str(e)) from e + raise NodeError(ctx.node.id, not_configured(e)) from e messages = await _build_messages(state, ctx) schema = ctx.cfg("output_schema") @@ -269,8 +272,8 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]: raise NodeError(ctx.node.id, explain_model_error(e, model_id)) from e raise NodeError( ctx.node.id, - f"模型没能按「结构化输出 Schema」给出结果:{describe_exception(e)}。" - "检查 Schema 是否写对,或者换一个支持结构化输出的模型", + f"模型未能按「结构化输出 Schema」给出结果:{describe_exception(e)}。" + "请检查 Schema 是否正确,或换用支持结构化输出的模型", ) from e payload = value if isinstance(value, (dict, list)) else getattr(value, "model_dump", lambda: value)() output = {"data": payload, "text": json.dumps(payload, ensure_ascii=False, indent=2)} @@ -284,7 +287,7 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 模型把工具调用当正文写了出来:这个节点压根没有工具,那段"调用"什么都没查到。 # 带一句纠正再问一次;还这样就判失败,别让一堆标记当答案往下游走 ctx.emit(EventType.LOG, level="warn", code="tool_markup_leak", - message=f"{markup_warning(snippet)},已提醒它重试一次") + message=f"{markup_warning(snippet)},已要求模型重试一次") retried = time.perf_counter() response = await _invoke_streaming( model, [*messages, response, HumanMessage(content=TOOL_MARKUP_NUDGE)], ctx, model_id) @@ -296,7 +299,7 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if not text and reasoning: # 思考型模型把额度全花在推理上了,正文是空的 —— 说清楚而不是抛个空结果给下游 ctx.emit(EventType.LOG, level="warn", - message="模型只输出了思考内容,正文为空。把 max_tokens 调大,或把 thinking 设为 off。", + message="模型只输出了思考内容,正文为空。请调大「最大输出 token」,或关闭「思考模式」。", code="empty_completion") output = {"text": text, "thinking": reasoning} @@ -407,7 +410,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: try: base_model, model_id = await get_chat_model(session, model_spec) except ProviderNotConfigured as e: - raise NodeError(ctx.node.id, str(e)) from e + raise NodeError(ctx.node.id, not_configured(e)) from e tools = await _resolve_tools(ctx, state) tool_map = {t.name: t for t in tools} @@ -545,7 +548,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: 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)}"} + 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", @@ -577,7 +580,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: raise NodeError(ctx.node.id, TOOL_MARKUP_ERROR) nudged = True await once(ctx, EventType.LOG, level="warn", code="tool_markup_leak", - message=f"{markup_warning(snippet)},已提醒它重试一次") + message=f"{markup_warning(snippet)},已要求模型重试一次") messages.append(HumanMessage(content=TOOL_MARKUP_NUDGE)) final_text = "" continue @@ -620,7 +623,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if guard and (again := guard.repeat(name, args)) is not None: # 同样的调用已经成功跑过:不再执行(也就不用再审批),把上次的结果交还给它 await once(ctx, EventType.LOG, level="info", code="tool_repeat", - message=f"{name} 用同样的参数又调了一次,没有再执行,把上次的结果交还给它") + message=f"{name} 被以相同参数重复调用,已跳过执行并返回上次的结果") messages.append(ToolMessage(content=again, tool_call_id=call_id)) transcript.append({"tool": name, "args": args, "repeat": True}) continue @@ -640,7 +643,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: ctx, {"kind": "tool_approval", "node_id": ctx.node.id, "tool": name, "args": args, "title": f"是否允许调用 {name}?", **trustable}, - mode="approve", tool=name, args=args, title=f"Agent 想调用工具 {name}", **trustable, + mode="approve", tool=name, args=args, title=f"Agent 请求调用工具 {name}", **trustable, ) verdict = read_decision(decision) note = verdict.note @@ -652,7 +655,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if not verdict.approved: messages.append( ToolMessage( - content=f"用户拒绝了这次调用。原因:{note or '未说明'}。请换一种方式。", + content=f"用户驳回了这次调用。原因:{note or '未说明'}。请换一种方式。", tool_call_id=call_id, ) ) @@ -687,7 +690,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: squeezed = guard.compress(messages) if squeezed: await once(ctx, EventType.LOG, level="info", code="context_compressed", - message=f"对话用到上下文窗口的 {guard.last_input * 100 // guard.window}%," + message=f"对话已占用上下文窗口的 {guard.last_input * 100 // guard.window}%," f"已压缩 {squeezed} 条早期的工具结果") # 刚压缩过的这一步不按上下文收尾:压缩的效果要到下一次调用才看得出来 if settle_reason := guard.stop_reason(total_usage, context=not squeezed): @@ -719,7 +722,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: settled = message_text(response).strip() except Exception as e: # noqa: BLE001 - 收尾失败不能把已有成果一起赔进去 await once(ctx, EventType.LOG, level="warn", - message=f"收尾轮没跑成:{describe_exception(e)}", code="settle_failed") + message=f"收尾失败:{describe_exception(e)}", code="settle_failed") if snippet := leaked_markup(settled): if not any(isinstance(m, AIMessage) and getattr(m, "tool_calls", None) for m in messages): @@ -729,14 +732,14 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 这不是「节点没绑工具」(前面的步数里工具是真调过的),不能套 TOOL_MARKUP_ERROR # 判失败、把已经查到的一起丢掉——按收尾轮没说出话处理,取它之前说过的话 await once(ctx, EventType.LOG, level="warn", code="tool_markup_leak", - message=f"{markup_warning(snippet)}:步数用完后的收尾轮仍想调用工具," - "没能给出结论") + message=f"{markup_warning(snippet)}:已达步数上限,收尾时仍试图调用工具," + "未能给出结论") settled = "" limited = {"reason": settle_reason} if guard else {} if settled: final_text = settled - hint = f"{to_user}这个结论是基于已经查到的部分给出的。" if guard else legacy_hint(max_steps, True) + hint = f"{to_user}以上结论基于已查到的部分。" if guard else legacy_hint(max_steps, True) # 和 step_limit 分开发:库里那些老事件的含义确实是"硬截断", # 复用同一个 code 会把历史运行重新解释成另一回事 ctx.emit(EventType.LOG, level="warn", message=hint, code="step_limit_settled", **limited) @@ -751,7 +754,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: and not leaked_markup(text)), "", ) - hint = f"{to_user}收尾轮也没有给出结论。" if guard else legacy_hint(max_steps, False) + hint = f"{to_user}收尾时仍未给出结论。" if guard else legacy_hint(max_steps, False) # 一步一工具时步数消耗得比并行快得多,这里不说清楚,用户只会看到 # 一个没头没尾的答案,而不知道是被步数掐断的 final_text = f"{final_text}\n\n({hint})".strip() if final_text else f"({hint})" @@ -762,7 +765,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if schema is not None and (fields := cited_fields(schema)): # 结构化抽取只能追加在循环之后:循环里的 task 按调用位置从 checkpoint 取回,插一个进去, # 停在审批上的运行恢复时位置就错开了 - extracted: dict[str, Any] = {"error": "这个节点没有查成功的库,没有可以核对出处的数据"} + 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"): @@ -790,7 +793,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if entries: updates["evidence"] = entries if ctx.cfg("emit_message", True): - updates["messages"] = [AIMessage(content=final_text or "(空)")] + updates["messages"] = [AIMessage(content=final_text or "(空)")] var_name = ctx.cfg("assign_to", "") if var_name: # 开了 cite_fields 的,变量里是核对过的 data(值以快照为准),下游口径卡按字段取 @@ -1048,13 +1051,13 @@ def verify_cited_fields(extracted: dict[str, Any], fields: list[tuple[str, dict[ if q["artifact"] not in snapshots: try: content = load(q["artifact"]) - snapshots[q["artifact"]] = (content, None if content is not None else "查询快照取不回来") + snapshots[q["artifact"]] = (content, None if content is not None else "查询快照无法读取") except ValueError: - snapshots[q["artifact"]] = (None, "查询快照和哈希对不上,疑似被改过") + snapshots[q["artifact"]] = (None, "查询快照与哈希不一致,可能已被修改") return snapshots[q["artifact"]] parsed = extracted.get("parsed") - failed = extracted.get("error") or (None if isinstance(parsed, dict) else "抽取结果不是一个对象") + failed = extracted.get("error") or (None if isinstance(parsed, dict) else "抽取结果格式有误(不是对象)") data: dict[str, Any] = {} evidence: dict[str, Any] = {} for path, sub in fields: @@ -1064,7 +1067,7 @@ def verify_cited_fields(extracted: dict[str, Any], fields: list[tuple[str, dict[ continue node = _dig(parsed, path) if not isinstance(node, dict) or "from" not in node: - evidence[path] = {"status": "unresolved", "reason": "抽取结果里没有按 {value, from} 写出这个字段"} + evidence[path] = {"status": "unresolved", "reason": "抽取结果中没有写出该字段的值和出处"} continue told, source = node.get("value"), node.get("from") if source is None: @@ -1085,8 +1088,8 @@ def verify_cited_fields(extracted: dict[str, Any], fields: list[tuple[str, dict[ 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 "(没有)")} + "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) @@ -1118,22 +1121,22 @@ def _verify_rows(schema: dict[str, Any], told: Any, source: Any, by_alias: dict[ snapshot_of: Any) -> tuple[Any, dict[str, Any]]: """数组字段:按 from 的行范围和列从快照里取出整组值,以快照为准。返回 (值, 出处)。""" if not isinstance(source, dict): - return None, {"status": "unresolved", "reason": "数组的 from 要写成 {call, rows, column(或 columns)}"} + return None, {"status": "unresolved", "reason": "数组字段的出处格式有误:缺少查询编号、行号范围或列名"} 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:每个字段取自哪一列"} + return None, {"call": call, "status": "unresolved", "reason": "对象数组的出处缺少各字段对应的列"} if fields is None and not isinstance(wanted, str): - return None, {"call": call, "status": "unresolved", "reason": "数组要写 column:这组值取自哪一列"} + return None, {"call": call, "status": "unresolved", "reason": "数组字段的出处缺少列名"} if span is None: - return None, {"call": call, "status": "unresolved", "reason": "rows 要写成 0-4 这样的行号范围(从 0 数)"} + return None, {"call": call, "status": "unresolved", "reason": "行号范围格式有误,应写成 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 "(没有)")) + reason = (f"行号范围需从小到大,当前为「{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) @@ -1177,16 +1180,16 @@ def _field_warnings(data: dict[str, Any], evidence: dict[str, Any], 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))}" + 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])) + 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)" + 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}" + message = f"有 {len(unresolved)} 个字段无法核对出处,记为空值(未以 0 代替):{detail}" out.append(("agent_field_unverified", message, [p for p, _ in unresolved])) return out diff --git a/backend/app/engine/nodes/metrics.py b/backend/app/engine/nodes/metrics.py index 18ccb461..b926b0e7 100644 --- a/backend/app/engine/nodes/metrics.py +++ b/backend/app/engine/nodes/metrics.py @@ -31,6 +31,7 @@ from app.engine.expressions import ( same_value, substitute, ) +from app.engine.labels import field_label from app.engine.state import GraphState, template_context @@ -62,7 +63,7 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 交给出具契约的 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}") + raise NodeError(ctx.node.id, f"「缺输入时」只能是「整个节点失败」或「记为空值」,当前为「{on_missing}」") metrics: list[dict[str, Any]] = [] errors: list[str] = [] @@ -70,16 +71,16 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]: metric_id = str(definition.get("id") or "").strip() expr = str(definition.get("expression") or "").strip() if not metric_id or not expr: - errors.append(f"指标定义不完整:{definition}") + errors.append(f"指标定义不完整(缺少 ID 或计算表达式):{definition}") continue display, problem = _display_of(definition) if problem: - errors.append(f"{metric_id}: {problem}") + errors.append(f"指标「{metric_id}」:{problem}") continue try: tree, _, _ = parse_expression(expr) except ExpressionError as e: - errors.append(f"{metric_id}: 表达式错误({e})") + errors.append(f"指标「{metric_id}」:表达式有误({e})") continue paths = leaf_refs(tree) values = {path: _value_of(path, tctx) for path in paths} @@ -89,28 +90,28 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]: try: value = eval_expression(expr, tctx) except ExpressionError as e: - errors.append(f"{metric_id}: 表达式错误({e})") + errors.append(f"指标「{metric_id}」:表达式有误({e})") continue except ZeroDivisionError: - errors.append(f"{metric_id}: 除以零") + errors.append(f"指标「{metric_id}」:除以零") continue 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)) + errors.append(f"指标「{metric_id}」:" + _missing_reason(missing)) continue value = None elif isinstance(e, TypeError): - errors.append(f"{metric_id}: 输入的类型不对,算不出来——" + _type_hint(paths, values)) + errors.append(f"指标「{metric_id}」:输入的类型不正确,无法计算——" + _type_hint(paths, values)) continue else: - errors.append(f"{metric_id}: 算不出来({describe_exception(e)})") + 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}") + errors.append(f"指标「{metric_id}」:小数位(decimals)需要填写整数,当前为「{definition.get('decimals')}」") continue decimals = display["decimals"] if isinstance(value, float) and decimals is not None: @@ -142,7 +143,7 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # text 是给叙述节点 prompt 用的清单——它是叙述层唯一的数字来源 lines = [ f"- {m['id']}({m['name']})= {m['value']}{m['unit']}" if m["value"] is not None - else f"- {m['id']}({m['name']})= {MISSING}(缺输入,没有值)" + else f"- {m['id']}({m['name']})= {MISSING}(缺少输入,无值)" for m in metrics ] card = { @@ -202,27 +203,27 @@ async def _pinned_caliber(ctx: NodeContext) -> tuple[dict[str, Any], dict[str, A 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}") + raise NodeError(ctx.node.id, f"「{field_label('caliber_from')}」格式有误:需要指定工作流、版本和其中的口径卡," + f"当前为「{ref}」") 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} 不存在(可能已经被删了):" - "在节点里重新选一张口径卡") + raise NodeError(ctx.node.id, f"「{field_label('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} 这个版本:在节点里重新选版本") + raise NodeError(ctx.node.id, f"「{field_label('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}:在节点里重新选一张口径卡") + 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'))}」") + raise NodeError(ctx.node.id, f"「{field_label('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, "", {}): @@ -230,9 +231,9 @@ async def _pinned_caliber(ctx: NodeContext) -> tuple[dict[str, Any], dict[str, A 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}):" - "直接钉住源头那张,升版处置才比得对版本") + if upstream is not None else str(origin)) + 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 @@ -255,15 +256,15 @@ def _display_of(definition: dict[str, Any]) -> tuple[dict[str, Any], str | None] 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}" + return {}, f"显示格式(format)只能是 {' / '.join(FORMATS)},当前为「{fmt}」" 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}") + return {}, (f"小数位(decimals)需要填写 -{_DECIMALS_RANGE} 到 {_DECIMALS_RANGE} 的整数" + f"(负数表示取整到十位、百位),当前为「{raw}」") display["decimals"] = decimals return display, None try: @@ -306,8 +307,8 @@ def _value_of(path: str, tctx: dict[str, Any]) -> Any: def _missing_reason(missing: list[str]) -> str: if not missing: - return "有输入是空值,算不出来(检查上游有没有产出这些字段)" - return f"输入 {'、'.join(missing[:4])} 没有值,算不出来(上游没有产出这个字段,或者路径写错了)" + return "有输入为空值,无法计算(请检查上游是否产出了这些字段)" + return f"输入 {'、'.join(missing[:4])} 没有值,无法计算(上游没有产出该字段,或路径有误)" def _type_hint(paths: list[str], values: dict[str, Any]) -> str: @@ -321,7 +322,7 @@ def _type_hint(paths: list[str], values: dict[str, Any]) -> str: sample = f"「{str(value)[:20]}」" if isinstance(value, str) else "" parts.append(f"{path} 是{label}{sample}") if not parts: - return "参与运算的值不是数" + return "参与运算的值不是数值" return "、".join(parts[:4]) + ",不能参与数值运算" @@ -436,7 +437,7 @@ def _agent_element(evidence: dict[str, Any], key: str) -> dict[str, Any] | None: try: truth, _ = locate_cell(artifact_store.load(artifact), row, column) except (ValueError, CellError, OSError) as e: - out.update(status="unresolved", reason=f"查询快照取不回来或对不上:{e}") + out.update(status="unresolved", reason=f"查询快照无法读取或与哈希不一致:{e}") return out if cited.get("status") == "verified": out["status"] = "verified" @@ -480,7 +481,7 @@ def _cell_input(path: str, value: Any, parts: tuple[str, str, str], state: Graph 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() 要取查询工具交回的结果") + status="unresolved", reason="找不到这份数据对应的查询快照:cell() 需要读取查询工具返回的结果") return entry entry["node_id"] = ledger.get("node_id") artifact = ledger.get("artifact") @@ -495,7 +496,7 @@ def _cell_input(path: str, value: Any, parts: tuple[str, str, str], state: Graph snapshot = artifact_store.load(artifact) truth, _ = locate_cell(snapshot, row, name) except (ValueError, CellError, OSError) as e: - entry.update(status="unresolved", reason=f"查询快照取不回来或对不上:{e}") + entry.update(status="unresolved", reason=f"查询快照无法读取或与哈希不一致:{e}") return entry if cell_value(truth) != cell_value(raw): # 算的时候用的值和快照不一样(上游改写过这份结果):照实记下快照里的值 @@ -563,5 +564,5 @@ async def _store(card: dict[str, Any], caliber: str, version: str, ctx: NodeCont 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)}),报告里没法引用它的指标") + message=f"口径卡的指标保存失败({describe_exception(e)}),报告将无法引用这些指标") return None diff --git a/backend/app/engine/nodes/multi.py b/backend/app/engine/nodes/multi.py index 0389f7b5..37a136cc 100644 --- a/backend/app/engine/nodes/multi.py +++ b/backend/app/engine/nodes/multi.py @@ -42,8 +42,8 @@ _MAX_DEPTH = 3 COORDINATOR = "调度者" #: 成员把工具调用写成文字、纠正之后还是这样时,交给调度者的那句话 -MEMBER_MARKUP_FAILED = ("模型输出了工具调用的原始标记,但没有真正调用工具,这一步什么都没查到" - "(常见原因:这个成员没有绑定工具,或者模型、服务不支持工具调用)") +MEMBER_MARKUP_FAILED = ("模型以文本形式输出了工具调用的原始标记,未实际调用工具,这一步没有查询到任何数据" + "(常见原因:该成员未绑定工具,或模型、服务不支持工具调用)") # -------------------------------------------------------------------------- @@ -60,7 +60,7 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: """ agents = ctx.cfg("agents", []) or [] if not agents: - raise NodeError(ctx.node.id, "supervisor 节点至少要配一个 agent") + raise NodeError(ctx.node.id, "「多 Agent 协作」节点未配置团队成员,至少需要一个") names = [a.get("name") or f"agent{i}" for i, a in enumerate(agents)] agent_map = {n: a for n, a in zip(names, agents)} @@ -235,7 +235,7 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: EventType.LOG, level="info", round=round_no, parallel=len(batch), agents=[n for n, _ in batch], done=False, reason=reason, message=(f"调度 → {who}" + (f"({reason})" if reason else "") - + (f" · {len(batch)} 人同时进行" if len(batch) > 1 else "")), + + (f" · {len(batch)} 名成员同时执行" if len(batch) > 1 else "")), ) return {"decision": value, "usage": spent} @@ -285,7 +285,7 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: text = f"({name} 执行失败:{why})" out = {"text": text, "tool_calls": [], "failed": True, "error": why} ctx.emit(EventType.LOG, level="warn", round=round_no, - message=f"{name} 这一轮失败了:{text}") + message=f"{name} 本轮执行失败:{text}") each_ms = int((time.perf_counter() - t0) * 1000) # failed / error 让矩阵把这一格画成失败,而不是一个"完成"的格子里写着失败原因 failure = {"failed": True, "error": out.get("error") or ""} if out.get("failed") else {} @@ -340,11 +340,11 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 把工具调用写成了文字:这一步什么都没查到。纠正一次,还这样就记为失败, # 原因交给调度者——以前这段标记会被当成这个成员的结论交上去 if nudged: - return {"text": f"({name} 这一步失败:{MEMBER_MARKUP_FAILED})", + return {"text": f"({name} 这一步执行失败:{MEMBER_MARKUP_FAILED})", "tool_calls": calls, "failed": True, "error": MEMBER_MARKUP_FAILED} nudged = True ctx.emit(EventType.LOG, level="warn", code="tool_markup_leak", - message=f"{markup_warning(snippet, name)},已提醒它重试一次") + message=f"{markup_warning(snippet, name)},已要求模型重试一次") messages.append(HumanMessage(content=TOOL_MARKUP_NUDGE)) continue for call in tool_calls: @@ -397,14 +397,14 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # shell_exec / file_write / 可写库上的 DELETE 照跑不误—— # agent 节点守着的那道门,在这里是敞开的。现在是不跑,并说清原因 content = ( - (f"门控模型没有放行({gate_reason})。" if gate_reason else "") - + f"没有执行:{tname} 这次调用需要人工确认,而协作团队里的成员" + (f"门控模型未批准({gate_reason})。" if gate_reason else "") + + f"没有执行:{tname} 这次调用需要人工审批,而协作团队里的成员" "不能停下来等人。换一种不需要它的做法;实在需要,交给团队外" - "的 agent 节点去做(那里可以逐次审批)。" + "的 Agent 节点去做(那里可以逐次审批)。" ) ctx.emit(EventType.LOG, level="warn", code="tool_needs_approval", tool=tname, agent=name, call_id=cid, - message=f"{name} 想调用 {tname},需要人工确认,协作节点里不执行") + message=f"{name} 请求调用 {tname},该调用需要人工审批,协作节点内不执行") else: try: raw = await run_bounded(tool_map[tname].ainvoke(targs), limit, tname) @@ -438,23 +438,23 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: text = message_text(settled).strip() except Exception as e: # noqa: BLE001 - 收尾失败不能把已有的过程一起赔进去 ctx.emit(EventType.LOG, level="warn", code="settle_failed", - message=f"{name} 的收尾轮没跑成:{describe_exception(e)}") + message=f"{name} 收尾失败:{describe_exception(e)}") text = next((t for m in reversed(messages) if isinstance(m, AIMessage) and (t := message_text(m).strip()) and not leaked_markup(t)), "") if snippet := leaked_markup(text): if not calls: - return {"text": f"({name} 这一步失败:{MEMBER_MARKUP_FAILED})", + return {"text": f"({name} 这一步执行失败:{MEMBER_MARKUP_FAILED})", "tool_calls": calls, "failed": True, "error": MEMBER_MARKUP_FAILED} # 真调过工具,只是收尾轮还想接着查:取它之前说过的话,和 agent 节点一样 ctx.emit(EventType.LOG, level="warn", code="tool_markup_leak", - message=f"{markup_warning(snippet, name)}:步数用完后的收尾轮仍想调用工具") + message=f"{markup_warning(snippet, name)}:已达步数上限,收尾时仍试图调用工具") text = next((t for m in reversed(messages) if isinstance(m, AIMessage) and (t := message_text(m).strip()) and not leaked_markup(t)), "") ctx.emit(EventType.LOG, level="warn", code="step_limit_settled", - message=f"{name} 用满了 {max_steps} 步,结论基于已经查到的部分") - return {"text": text or f"({name} 用满了 {max_steps} 步,没有给出结论)", "tool_calls": calls} + message=f"{name} 已用完 {max_steps} 步上限,结论基于已查到的部分") + return {"text": text or f"({name} 已用完 {max_steps} 步上限,未给出结论)", "tool_calls": calls} progress_lines: list[str] = [] final_text = "" @@ -539,34 +539,35 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: late = "、".join(dict.fromkeys(t["agent"] for t in failed if t["round"] == transcript[-1]["round"])) ctx.emit(EventType.LOG, level="warn", code="team_last_failed", - message=f"{late} 最后一轮没有交回结果,团队成果取自{delivered[-1][0]}的产出") + message=f"{late} 最后一轮未交回结果,团队成果取自{delivered[-1][0]}的产出") elif finished and transcript: # 调度者说完成了,派出去的成员却一个都没交回结果,手上只有失败说明。以前最后 # 那段失败说明就被当成团队的结论交出去:一条数据都没查到,运行照样是已完成。 # 不看 on_exhausted:那是「用完轮数时」的收场方式,降档交的是成员原话;这里 # 连原话都没有,交下去的只能是失败说明,界面还会把它说成「用完 N 轮」 why = ";".join(f"{who}:{err[:200]}" for who, err in dict.fromkeys( - (t["agent"], t.get("error") or "没有说明原因") for t in failed)) - summary = (f"协作团队没有交出结论:派出去的成员都没能交回结果,调度者仍判定完成" - f"({last_reason or '没有给出理由'})。{why}") + (t["agent"], t.get("error") or "未说明原因") for t in failed)) + summary = (f"协作团队未交出结论:所有被分派的成员都未能交回结果,调度者仍判定完成" + f"({last_reason or '未给出理由'})。{why}") if never: summary += f"。一次都没被派到的成员:{'、'.join(never)}" - raise NodeError(ctx.node.id, f"{summary}。按各成员的失败原因改好配置,再运行") + raise NodeError(ctx.node.id, f"{summary}。请根据各成员的失败原因修改配置后重新运行") elif not finished: # 轮数用完,调度者一次都没说「完成」。这时手上只有最后一个成员的原话—— # 以前它就被当作团队的结论交了出去:真实运行里是一段没执行的工具调用标记, # 而负责定稿的成员一次都没被派到 summary = (f"协作团队用完 {max_rounds} 轮仍未完成:" - f"{last_reason or '调度者没有给出理由'}") + f"{last_reason or '调度者未给出理由'}") if never: summary += f"。一次都没被派到的成员:{'、'.join(never)}" if on_exhausted == "fail": - raise NodeError(ctx.node.id, f"{summary}。先看成员有没有绑定要用的工具,再调大「最多" - "轮数」;也可以把「用完轮数时」改成降档交付") + # 「。先看成员」是前端切分这句话的锚点(decode.ts exhaustedOf、NodeCard、explain.ts),不要改 + raise NodeError(ctx.node.id, f"{summary}。先看成员是否绑定了所需工具,再调大「最多" + "轮数」;也可将「用完轮数时」改为「降档交付」") exhausted = {"exhausted": True, "exhausted_reason": last_reason, "never_dispatched": never} ctx.emit(EventType.LOG, level="warn", code="team_exhausted", - message=f"{summary}。按降档交付:成果是成员最后的原话,不是调度者认可的结论") + message=f"{summary}。按降档交付:成果取自成员最后的回复,并非调度者认可的结论") usage_total["total_tokens"] = usage_total["input_tokens"] + usage_total["output_tokens"] # 并行省下的时间:各轮"串行本该花的"减去"实际花的"。只有并发过才有差值 @@ -586,7 +587,7 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: "usage": usage_total, } if ctx.cfg("emit_message", True): - updates["messages"] = [AIMessage(content=final_text or "(空)")] + updates["messages"] = [AIMessage(content=final_text or "(空)")] var_name = ctx.cfg("assign_to", "") if var_name: updates["vars"] = {var_name: final_text} @@ -609,11 +610,11 @@ async def run_subgraph(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if ctx.run.depth >= _MAX_DEPTH: raise NodeError(ctx.node.id, f"子工作流嵌套超过 {_MAX_DEPTH} 层,已阻止。" - "多半是几张工作流互相引用了,检查「子工作流」节点选的是哪一张") + "可能是多个工作流相互引用,请检查「子工作流」节点选择的工作流") workflow_id = ctx.cfg("workflow_id") if not workflow_id: - raise NodeError(ctx.node.id, "「子工作流」节点还没选要嵌套的工作流") + raise NodeError(ctx.node.id, "「子工作流」节点尚未选择要嵌套的工作流") # 版本钉死:这就是"方法卡"的机制核心。钉了 workflow_version 就永远 # 执行那个不可变快照,上游改了方法卡也不会让这里的口径悄悄漂移; @@ -622,8 +623,8 @@ async def run_subgraph(state: GraphState, ctx: NodeContext) -> dict[str, Any]: async with SessionLocal() as session: workflow = await session.get(Workflow, workflow_id) if not workflow: - raise NodeError(ctx.node.id, f"「子工作流」引用的工作流({workflow_id})已经不在了," - "可能被删除了。在节点里重新选一张") + raise NodeError(ctx.node.id, f"「子工作流」引用的工作流({workflow_id})已不存在," + "可能已被删除,请在节点中重新选择") if pinned: from sqlalchemy import select @@ -639,7 +640,7 @@ async def run_subgraph(state: GraphState, ctx: NodeContext) -> dict[str, Any]: ).scalar_one_or_none() if not snapshot: raise NodeError( - ctx.node.id, f"工作流「{workflow.name}」没有 v{pinned} 这个版本" + ctx.node.id, f"工作流「{workflow.name}」不存在 v{pinned} 版本" ) sub_graph = snapshot.graph used_version = int(pinned) @@ -693,8 +694,8 @@ async def run_subgraph(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 不接住的话,外层包装成 NodeError 时带的是 LangGraph 的英文原文 raise NodeError( ctx.node.id, - f"子图「{workflow.name}」走满了 {limit} 步还没跑完,已中止。多半是子图里有个环" - "在空转:分支连回了上游、却没有 loop 节点给它定轮数上限", + f"子工作流「{workflow.name}」已执行 {limit} 步仍未结束,已中止。可能存在没有轮数上限的环路," + "请在子工作流中用「循环」节点限制轮数", ) from e output = result_state.get("output") or {} diff --git a/backend/app/engine/nodes/report.py b/backend/app/engine/nodes/report.py index d24b887f..3e72234b 100644 --- a/backend/app/engine/nodes/report.py +++ b/backend/app/engine/nodes/report.py @@ -37,11 +37,12 @@ from typing import Any from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage from langgraph.func import task -from app.core.errors import describe_exception +from app.core.errors import describe_exception, not_configured from app.core.events import EventType from app.db.base import SessionLocal from app.engine import judge as judging from app.engine.context import NodeContext, NodeError +from app.engine.labels import field_label, option_label from app.engine.evidence import ( CELLS_REASON, CLAIMS_RULE, @@ -87,8 +88,9 @@ ROLE = ("你是报告撰写人。报告里的每个数字都由系统从证据 MARKUP_NUDGE = ("你上一条回复把工具调用写成了文字。报告撰写不调用任何工具:能用的数据都在上面的" "证据目录里,直接用引用标记写报告正文。") -MARKUP_ERROR = ("模型输出了工具调用的原始标记,而报告撰写节点不调用工具——数据已经在证据目录里。" - "换一个模型再试") +#: 节点失败原因(给人看)。给模型的那句是上面的 MARKUP_NUDGE,「证据目录」是模型那边的说法 +MARKUP_ERROR = ("模型输出了工具调用的原始标记,而报告撰写节点不调用工具,数据已由系统提供。" + "请换一个模型重试") #: 接着跑时 checkpoint 里缓存的判定最多翻几条去找这一稿的(每条都是先前某一稿的,对不上就往后翻) _STALE_LIMIT = 16 @@ -200,12 +202,12 @@ 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") + return ("报告撰写节点的上游没有可引用的来源(" + "、".join(_CITABLE.values()) + "都没有)," + f"报告中的数字都会被判为没有出处。请在它前面接入取数节点或口径卡,或检查「{field_label('metrics_from')}」") if not cells and not kinds & {"metric", "input"}: # 只有查询和检索:单元格引用不了,检索片段本来就只能当依据,一个数都没处引 - return (f"报告撰写节点的上游只有查询结果、没有口径卡指标,而这次{CELLS_REASON}:单元格引用不了," - "报告里的数字都会被判为没有出处。在出口契约里写 \"cells\": true,或者把要写的数登记进口径卡") + return (f"报告撰写节点的上游只有查询结果,没有口径卡指标,而{CELLS_REASON},当前无法引用单元格," + "报告中的数字都会被判为没有出处。请在出具契约中开启「单元格引用」,或把要写的数字登记到口径卡") return None @@ -262,7 +264,7 @@ async def _default_on_violation(run_id: str) -> str: 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}") + raise NodeError(ctx.node.id, _only("numbers", NUMBERS, numbers)) # 画布校验也拦这两项;执行时再守一道,报的是同一句话,免得写错的值被悄悄当成默认 if problem := claims_problem(ctx.cfg("claims")): raise NodeError(ctx.node.id, problem) @@ -270,17 +272,28 @@ def _options(ctx: NodeContext) -> tuple[str, int]: raise NodeError(ctx.node.id, ";".join(message for _, message in problems)) entities = ctx.cfg("entities", "link") or "link" if entities not in ENTITIES: - raise NodeError(ctx.node.id, f"entities 只能是 {' / '.join(ENTITIES)},写的是 {entities!r}") + raise NodeError(ctx.node.id, _only("entities", ENTITIES, entities)) 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 + raise NodeError(ctx.node.id, _repairs_problem(raw)) 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}") + raise NodeError(ctx.node.id, _repairs_problem(raw)) return numbers, repairs +def _only(key: str, allowed: tuple[str, ...], got: Any) -> str: + """「「表名、字段名」只能是「核对」或「不核对」,当前为「x」」:写界面上的叫法,不写键名和枚举值。""" + names = [f"「{option_label(key, v)}」" for v in allowed] + listed = "或".join(names) if len(names) <= 2 else "、".join(names[:-1]) + "或" + names[-1] + return f"「{field_label(key, 'report')}」只能是{listed},当前为「{got}」" + + +def _repairs_problem(raw: Any) -> str: + return f"「{field_label('max_repairs', 'report')}」需要填写 0 到 {MAX_REPAIRS} 的整数,当前为「{raw}」" + + def _blocking(violations: list[dict[str, Any]], numbers: str) -> list[dict[str, Any]]: """要让写作者改的违规。numbers=off 时裸数字只记录不拦(文档和出口复核照样看得到)。 @@ -356,7 +369,7 @@ async def _store(doc: dict[str, Any], ctx: NodeContext) -> str | None: 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)}),报告里的数字点不开证据") + message=f"报告文档保存失败({describe_exception(e)}),报告中的数字将无法查看证据") return None @@ -364,13 +377,13 @@ 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}") + raise NodeError(ctx.node.id, _only("on_violation", ("flag", "fail"), on_violation)) 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 + raise NodeError(ctx.node.id, not_configured(e)) from e spec = ctx.run.spec catalog = report_catalog(state, spec, ctx.node) @@ -406,11 +419,11 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]: raise NodeError(ctx.node.id, MARKUP_ERROR) nudged = True ctx.emit(EventType.LOG, level="warn", code="tool_markup_leak", - message=f"{markup_warning(snippet)},已提醒它重试一次") + 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。") + message="模型只输出了思考内容,报告正文为空。请调大「最大输出 token」,或关闭「思考模式」。") return response, text entities = report_entities(spec, ctx.node) == "link" @@ -425,8 +438,8 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]: 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} 次)") + message=f"报告有 {len(blocking)} 处未通过核对({_named(blocking)})," + f"已要求模型重写(第 {repairs} 次)") messages = [*messages, response, HumanMessage(content=_repair_request(blocking))] response, raw = await draft(messages) doc = compose(raw) @@ -456,8 +469,9 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]: more = f";…另有 {len(blocking) - 5} 处" if len(blocking) > 5 else "" raise NodeError( ctx.node.id, - f"报告有 {len(blocking)} 处没通过核对(已要求重写 {repairs} 次):{head}{more}。" - "换一个遵从度更高的模型,或者先把 on_violation 设成 flag,把问题标注在报告里再看", + f"报告有 {len(blocking)} 处未通过核对(已要求重写 {repairs} 次):{head}{more}。" + f"请换用指令遵循能力更强的模型,或先将「{field_label('on_violation')}」设为" + f"「{option_label('on_violation', 'flag')}」,查看标注后再调整", ) usage = {key: sum(one[key] for one in spent) for key in spent[0]} @@ -476,7 +490,7 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]: } updates: dict[str, Any] = {"nodes": {ctx.node.id: result}, "usage": usage} if ctx.cfg("emit_message", True): - updates["messages"] = [AIMessage(content=text or "(空)")] + updates["messages"] = [AIMessage(content=text or "(空)")] var_name = ctx.cfg("assign_to", "") if var_name: updates["vars"] = {var_name: text} @@ -545,8 +559,9 @@ async def _judge_inline(ctx: NodeContext, doc: dict[str, Any], catalog: dict[str if first and outcome.get("model") and outcome["model"] == model_id: outcome["same_model"] = True ctx.emit(EventType.LOG, level="warn", code="judge_same_model", - message=f"裁判模型和写作模型都是「{model_id}」:等于自己审自己,模型写错的地方它多半也看不出来。" - "到设置里选一个不同的「证据裁判模型」,或者在节点的 judge.model 里指定") + message=f"裁判模型与写作模型相同(「{model_id}」),难以发现写作模型自身的错误。" + "请在「设置 → 偏好设置 → 证据裁判」中选择另一个模型," + f"或在节点的「{field_label('judge')}」中指定裁判模型") return {**outcome, "key": key} async def judge_round(round_doc: dict[str, Any], limits: judging.Budget, known: dict[str, Any], @@ -573,7 +588,7 @@ async def _judge_inline(ctx: NodeContext, doc: dict[str, Any], catalog: dict[str sentences = [(texts.get(uid, ""), outcome["verdicts"][uid].get("rationale") or "") for uid in bad] ctx.emit(EventType.LOG, level="warn", code="report_rewrite", message=f"裁判认为 {len(bad)} 句结论证据不支持({_named([{'text': t} for t, _ in sentences])})," - "已交回写作者只改这几句") + "已退回写作模型仅修改这几句") again, raw = await draft([*messages, HumanMessage(content=_rewrite_request(sentences))]) rewritten = compose(raw) worse = _blocking(rewritten["violations"], numbers) @@ -581,8 +596,8 @@ async def _judge_inline(ctx: NodeContext, doc: dict[str, Any], catalog: dict[str rewrite = {"units": bad, "sentences": [t for t, _ in sentences], "applied": False, "reason": None, "changed": []} if fresh: - rewrite["reason"] = (f"改写稿冒出 {len(fresh)} 处原稿没有的问题({_named(fresh)}),没有采用," - "保留原稿和原来的判定") + rewrite["reason"] = (f"改写稿新增了 {len(fresh)} 处原稿没有的问题({_named(fresh)}),未予采用," + "已保留原稿及原有判定") ctx.emit(EventType.LOG, level="warn", code="report_rewrite_rejected", message=rewrite["reason"]) else: known = {outcome["keys"][u]: v for u, v in outcome["verdicts"].items() if v["status"] in judging.JUDGED} diff --git a/backend/app/engine/nodes/tools.py b/backend/app/engine/nodes/tools.py index a3948b2f..41a04445 100644 --- a/backend/app/engine/nodes/tools.py +++ b/backend/app/engine/nodes/tools.py @@ -67,11 +67,11 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]: """直接调用一个工具。参数里的 {{ }} 会先用当前状态渲染。""" name = ctx.cfg("tool", "") if not name: - raise NodeError(ctx.node.id, "工具节点没有选择工具") + raise NodeError(ctx.node.id, "「调用工具」节点尚未选择工具") args = ctx.render(ctx.cfg("args", {}) or {}, state) if not isinstance(args, dict): - raise NodeError(ctx.node.id, "工具参数必须是对象") + raise NodeError(ctx.node.id, "工具参数必须是 JSON 对象") # 审批通过后节点会整个重放、再算一遍要不要问人,所以这里只能取决于 name 和 args。 # 节点没配时取全局设置(「危险工具默认需要人工确认」),见 NodeContext.approval_mode @@ -104,7 +104,7 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]: await once(ctx, EventType.HUMAN_RESOLVED, tool=name, approved=decision.approved, note=decision.note, actor=ctx.actor(), **({"always": True} if always else {})) if not decision.approved: - raise NodeError(ctx.node.id, f"用户拒绝执行工具 {name}" + raise NodeError(ctx.node.id, f"工具 {name} 的调用已被驳回" + (f":{decision.note}" if decision.note else "")) limit = limit_of(tool, name, args) @@ -115,7 +115,7 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 替它跑通了这一次,但节点配置里那个错的参数名原封不动,下次还会踩。 # 所以纠正必须留一条看得见的痕迹,而不是安静地把事办了 ctx.emit(EventType.LOG, level="warn", - message=f"工具 {name}:{note}。请到节点里改正。", code="tool_args_fixed") + message=f"工具 {name}:{note}。请在节点中改正。", code="tool_args_fixed") async def _call() -> Any: async with SessionLocal() as session: @@ -128,13 +128,13 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]: elapsed = int((time.perf_counter() - started) * 1000) ctx.emit(EventType.TOOL_ERROR, tool=name, error=str(e), timed_out=True, duration_ms=elapsed) if ctx.cfg("fail_fast", True): - raise NodeError(ctx.node.id, f"{e}。数据量大就在参数里缩小范围;对方偶尔卡住的话," - "稍后「接着跑」即可") from e + raise NodeError(ctx.node.id, f"{e}。数据量较大时请在参数中缩小范围;如为服务暂时无响应," + "可稍后点「继续运行」") from e result = {"error": str(e), "timed_out": True} except KeyError as e: # str(KeyError) 是带引号的 repr,直接拼会多出一对引号 - reason = e.args[0] if e.args else f"找不到工具 {name!r}" - raise NodeError(ctx.node.id, f"{reason}。工具可能被删除或改了名字,在节点里重新选一个") from e + reason = e.args[0] if e.args else f"找不到工具 {name}" + raise NodeError(ctx.node.id, f"{reason}。工具可能已被删除或重命名,请在节点中重新选择") from e except ToolArgsError as e: # 参数对不上且没有唯一候选可纠。报错里已经写清楚该填什么, # 不要再套一层 "执行失败:" 把它推远 @@ -149,8 +149,8 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if ctx.cfg("fail_fast", True): raise NodeError( ctx.node.id, - f"工具 {name} 执行失败:{reason}。检查节点里填的参数;参数没问题的话," - "是这个工具本身出了错,换一个工具或联系管理员", + f"工具 {name} 执行失败:{reason}。请检查节点中填写的参数;如参数无误," + "则是该工具本身出错,请换一个工具或联系管理员", ) from e result = {"error": reason, "detail": raw_detail(e)} @@ -160,7 +160,7 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]: # 没查成:原话就是报错(「查询失败: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 再跑") + raise NodeError(ctx.node.id, f"工具 {name} 查询失败:{result}。请据此修改节点中的 SQL 后重新运行") result = {"error": result} # 取数快照:query(args)和结果集一起进工件库,完整出具时数字回指的就是它 @@ -210,11 +210,11 @@ 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, "代码节点是空的") + 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}") + raise NodeError(ctx.node.id, f"「证据角色」只能是「取数」或「计算」,当前为「{role}」") language = ctx.cfg("language", "python") limits = SandboxLimits( @@ -235,7 +235,7 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]: await once(ctx, EventType.HUMAN_RESOLVED, approved=decision.approved, note=decision.note, actor=ctx.actor()) if not decision.approved: - raise NodeError(ctx.node.id, "用户拒绝执行代码" + raise NodeError(ctx.node.id, "代码执行已被驳回" + (f":{decision.note}" if decision.note else "")) # 隔离档位:strict 要硬件级(microVM),fast 要低延迟(Seatbelt/bwrap), @@ -261,7 +261,7 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if isolation == "strict" and result.backend != "microvm": # 要了硬件隔离却没拿到,必须说出来——否则用户以为自己在 VM 里跑 ctx.emit(EventType.LOG, level="warn", - message=f"节点要求 strict 隔离,但 microVM 未就绪,实际用了 {result.backend}", + message=f"节点要求 strict 隔离,但 microVM 未就绪,实际使用了 {result.backend}", code="isolation_fallback") if result.session_reset: # 会话工作区被清空了。同一会话的下游节点会突然读不到自己写的文件, @@ -283,7 +283,7 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]: if not result.ok and ctx.cfg("fail_fast", True): raise NodeError( ctx.node.id, - f"代码执行失败(exit={result.exit_code}):{result.error or result.stderr[:500]}", + f"代码执行失败(退出码 {result.exit_code}):{result.error or result.stderr[:500]}", ) payload = result.model_dump() diff --git a/backend/app/engine/review.py b/backend/app/engine/review.py index 2615766c..1f671611 100644 --- a/backend/app/engine/review.py +++ b/backend/app/engine/review.py @@ -161,9 +161,13 @@ def scan(events: Iterable[Any], output: Mapping[str, Any] | None = None) -> list # 不区分的话,参数自动纠正这条路每修一次就报一次「答案不可信」。 recovered: set[str] = set() failed_at: dict[str, int] = {} + #: 节点名:node.started 带着画布上的名字,报失败时写名字,不写节点 id + titles: dict[str, str] = {} for i, e in enumerate(rows): etype = str(_event_field(e, "type", "")) data = _event_field(e, "data") or {} + if etype == EventType.NODE_STARTED and data.get("label"): + titles.setdefault(str(_event_field(e, "node_id") or ""), str(data["label"])) tool = str(data.get("tool") or "") if etype == EventType.TOOL_ERROR and tool: failed_at.setdefault(tool, i) @@ -185,7 +189,7 @@ def scan(events: Iterable[Any], output: Mapping[str, Any] | None = None) -> list elif etype == EventType.NODE_FAILED: err = str(data.get("error") or "").strip()[:200] - add("node_failed", f"节点 {node_id} 执行失败:{err}", BROKEN) + add("node_failed", f"节点「{titles.get(node_id) or node_id}」执行失败:{err}", BROKEN) elif etype == EventType.RUN_FAILED: err = str(data.get("error") or "").strip()[:200] @@ -196,7 +200,7 @@ def scan(events: Iterable[Any], output: Mapping[str, Any] | None = None) -> list # knowledge.py 在这条事件**之前**已经把每条具体原因发成了 warn #("重排结果解析不出来"、"多少条向量对不上")。两边都收就是同一件事 # 报两遍,一条含糊一条具体——这里只兜没有 warn 的情形 - add("retrieve_degraded", "知识库检索能力降级,可能漏掉换了说法的内容", DEGRADED) + add("retrieve_degraded", "知识库检索能力降级,可能遗漏表述不同的内容", DEGRADED) if not data.get("count"): q = str(data.get("query") or "").strip()[:60] add("retrieve_empty", f"知识库里没有检索到与「{q}」相关的内容", BROKEN) @@ -213,10 +217,10 @@ def scan(events: Iterable[Any], output: Mapping[str, Any] | None = None) -> list if not text: add("empty_output", "这次运行没有产出任何成果内容", BROKEN) elif any(mark in text for mark in _PLACEHOLDER_MARKS): - add("placeholder_output", "交出来的是一句内部流程说明,不是对问题的回答", BROKEN) + add("placeholder_output", "交付的是一句内部流程说明,而不是对问题的回答", BROKEN) elif leaked_markup(text): # 老运行、或者绕过了节点检查的路径:成果本身就是一段没执行的工具调用标记 - add("markup_output", "交出来的是一段没有执行的工具调用标记,不是对问题的回答", BROKEN) + add("markup_output", "交付的是一段未执行的工具调用标记,而不是对问题的回答", BROKEN) return signals diff --git a/backend/app/engine/runner.py b/backend/app/engine/runner.py index a6b2ad53..1392b0fc 100644 --- a/backend/app/engine/runner.py +++ b/backend/app/engine/runner.py @@ -66,12 +66,12 @@ class RunManager: await session.execute( update(Run) .where(Run.status == "running") - .values(status="interrupted", error="服务重启,运行已挂起,可从断点恢复") + .values(status="interrupted", error="服务重启,运行已挂起,可从断点继续运行") ) await session.execute( update(Run) .where(Run.status == "queued") - .values(status="failed", error="服务重启时这次运行还在排队,没有可恢复的进度,请重新发起") + .values(status="failed", error="服务重启时这次运行仍在排队,没有可恢复的进度,请重新发起运行") ) await session.commit() # 进程被强杀时连 server_shutdown 日志都来不及发,事件流停在半路。补上这一条, @@ -80,7 +80,7 @@ class RunManager: bus.set_seq(run_id, last_seq or 0) await self._emit(run_id, EventType.LOG, data={ "level": "warn", "code": "server_shutdown", - "message": "服务上次没有正常关停,这次运行停在了半路;可以从断点接着跑", + "message": "服务上次未正常关闭,这次运行已中断;可从断点继续运行", }) async def shutdown(self) -> None: @@ -181,7 +181,7 @@ class RunManager: report = validate_graph(spec) if not report.ok: raise ValueError( - "工作流没有通过校验,先在画布上修好标红的节点再运行:" + "工作流未通过校验,请先在画布上修正标红的节点再运行:" + ";".join(i.message for i in report.issues if i.level == "error") ) if approval_default is None: @@ -248,7 +248,7 @@ class RunManager: async with SessionLocal() as session: run = await session.get(Run, run_id) if not run: - raise KeyError(f"找不到运行 {run_id}") + raise KeyError("运行记录不存在") if run.status not in ("interrupted",): raise ValueError(_cannot_resume(run.status)) spec = GraphSpec.model_validate(run.graph) @@ -265,13 +265,12 @@ class RunManager: if not waiting and not getattr(snapshot, "next", None): # 没有断点可续。多半是重启时被标成 interrupted 的 queued 运行。 raise ValueError( - "这次运行没有可恢复的断点(很可能重启前还没真正开始跑)。" - "请重新发起一次运行,而不是恢复——继续下去只会用默认值跑出一份假结果。" + "这次运行没有可恢复的断点,可能在服务重启前尚未开始执行。请重新发起运行。" ) if stale := await _stale_replay(run_id, spec, snapshot): raise ValueError( - f"这次运行是升级前停在「{stale}」上的,引擎记录断点的方式已经变了:现在恢复," - f"「{stale}」里已经执行过的工具会再执行一次。请放弃这次运行,重新发起" + f"这次运行停在「{stale}」时系统已升级,断点格式不再兼容,继续会让「{stale}」中" + f"已执行的工具重复执行。请放弃这次运行并重新发起" ) answers: dict[str, Any] = {} @@ -289,13 +288,13 @@ class RunManager: if approval_id: target = next((a for a in pending if a.id == approval_id), None) if target is None: - raise ValueError("这条审批已经处理过了,或者不属于这次运行。刷新看看最新状态") + raise ValueError("这条审批已处理过,或不属于这次运行。请刷新页面查看最新状态") elif len(pending) == 1: target = pending[0] elif len(pending) > 1: raise ValueError( f"这次运行有 {len(pending)} 条待处理的审批," - "得说明回复的是哪一条(approval_id),请在对应的审批卡上操作" + "无法确定本次回复对应哪一条,请在对应的审批卡上操作" ) now = datetime.now(timezone.utc) @@ -314,7 +313,7 @@ class RunManager: ) if marked.rowcount != 1: await session.rollback() - raise ValueError("这条审批已经处理过了,或者这次运行已经放弃了。刷新看看最新状态") + raise ValueError("这条审批已处理过,或这次运行已被放弃。请刷新页面查看最新状态") await session.commit() # 审批卡上点的是「始终允许」:这个工具以后改由门控把关。只有带 trust_key 的 # 审批才有这个按钮(MCP / 自定义工具、探索运行),别的审批带了 always 也不理。 @@ -390,7 +389,7 @@ class RunManager: else: command = Command(resume=answers) await self._emit(run_id, EventType.RUN_RESUMED, data=( - {"message": "服务重启时中断的运行,从断点接着跑", "actor": actor} if command is None + {"message": "服务重启时中断的运行,从断点继续运行", "actor": actor} if command is None else {"response": _safe(response), "actor": actor} )) self._tasks[run_id] = asyncio.create_task( @@ -420,7 +419,7 @@ class RunManager: async with SessionLocal() as session: run = await session.get(Run, run_id) if not run: - raise KeyError(f"找不到运行 {run_id}") + raise KeyError("运行记录不存在") has_pending = run.status == "interrupted" and (await session.execute( select(Approval.id).where( Approval.run_id == run_id, Approval.status.in_(["pending", "answered"]) @@ -437,14 +436,13 @@ class RunManager: revised = GraphSpec.model_validate(graph) if topology_of(revised) != topology_of(spec): raise ValueError( - "接着跑只能改节点配置,不能增删节点或改连线——" - "断点是按节点名存的,结构变了就对不上了。" - "要改结构请重新发起一次运行。" + "继续运行时只能修改节点配置,不能增删节点或修改连线。" + "如需修改结构,请重新发起运行。" ) report = validate_graph(revised) if not report.ok: first = next((i.message for i in report.issues if i.level == "error"), "") - raise ValueError(f"改过的图没有通过校验:{first}") + raise ValueError(f"修改后的工作流未通过校验:{first}") spec = revised # 先问引擎到底停在哪。没有待跑的节点就不是"能接着跑"的情形—— @@ -456,13 +454,12 @@ class RunManager: pending = [str(n) for n in (getattr(snapshot, "next", None) or [])] if not pending: raise ValueError( - "这次运行没有留下可以接着跑的断点(多半是还没跑到第一个节点就挂了)。" - "请重新发起一次运行——继续下去只会从头跑一遍,还看不出来。" + "这次运行没有可继续的断点,可能在执行第一个节点前就已中断。请重新发起运行。" ) if stale := await _stale_replay(run_id, spec, snapshot): raise ValueError( - f"这次运行是升级前停在「{stale}」上的,引擎记录断点的方式已经变了:现在接着跑," - f"「{stale}」里已经执行过的工具会再执行一次。请重新发起一次运行" + f"这次运行停在「{stale}」时系统已升级,断点格式不再兼容,继续运行会让「{stale}」中" + f"已执行的工具重复执行。请重新发起运行" ) done = [n for n in (snapshot.values or {}).get("nodes", {}) if n not in pending] @@ -485,8 +482,8 @@ class RunManager: "from": pending, # 说清楚"哪些没重来"——否则用户看到时间线又动起来, # 分不清这次是接着跑还是整张图又跑了一遍 - "message": f"从「{labels.get(pending[0], pending[0])}」接着跑" - + (f",前面 {len(done)} 个节点的结果保留" if done else ""), + "message": f"从「{labels.get(pending[0], pending[0])}」继续运行" + + (f",保留前面 {len(done)} 个节点的结果" if done else ""), "actor": actor, }, ) @@ -534,7 +531,7 @@ class RunManager: run = await session.get(Run, run_id) timing = await _timing(session, run, 0, now) run.usage = {**(run.usage or {}), "duration_ms": timing["active_ms"], **timing} - run.error = "用户取消:在等审批时放弃了这次运行" if closed else "用户取消:挂起期间放弃了这次运行" + run.error = "用户取消:等待审批时放弃了这次运行" if closed else "用户取消:挂起期间放弃了这次运行" bus.set_seq(run_id, run.last_seq or 0) # 和状态同一个事务提交,理由同 _finalize event = self._event(run_id, EventType.RUN_CANCELLED, data={ @@ -678,10 +675,10 @@ class RunManager: # checkpoint 完好,记成中断、重启后从断点接着跑——和强杀后启动 # 扫描的处理一致。以前一律记"用户取消",resume 和 continue 都拒绝它 status = "interrupted" - error = "服务重启,运行已挂起,可从断点恢复" + error = "服务重启,运行已挂起,可从断点继续运行" await self._emit(run_id, EventType.LOG, data={ "level": "warn", "code": "server_shutdown", - "message": "服务关停时这次运行还在跑,已挂起;重启后可以从断点接着跑", + "message": "服务关闭时这次运行仍在进行,已挂起;重启后可从断点继续运行", }) else: status = "cancelled" @@ -692,8 +689,9 @@ class RunManager: status = "failed" if deadline is not None and deadline.expired(): error = ( - f"这次执行超过了 {settings.max_run_seconds} 秒的上限,已中止。" - "跑得慢的多半是模型或工具没有响应;确实需要更久,调大 AGENTLAB_MAX_RUN_SECONDS" + f"本次运行超过 {settings.max_run_seconds} 秒的时长上限,已中止。" + "通常是模型或工具长时间未响应;如确需更长时间,请联系管理员调大时长上限" + "(AGENTLAB_MAX_RUN_SECONDS)" ) terminal = (EventType.RUN_FAILED, {"error": error}) else: # 别处抛的超时,不是这道上限——按普通失败说 @@ -704,11 +702,12 @@ class RunManager: # LangGraph 的原文是英文,还叫人去调 recursion_limit——用户碰不到那个键。 # 循环的轮数已经另算了预算,走到这里的多半是不归 loop 节点管的环 error = ( - f"走满了 {settings.max_graph_steps + extra_steps} 步还没跑完,已中止" - f"(图最大步数 {settings.max_graph_steps}" - + (f",另按循环轮数预留了 {extra_steps} 步" if extra_steps else "") + ")。" - "多半是有个环在空转:分支连回了上游、却没有 loop 节点给它定轮数上限。" - "用 loop 节点包住它;确实需要这么多步,调大 AGENTLAB_MAX_GRAPH_STEPS" + f"运行已执行 {settings.max_graph_steps + extra_steps} 步仍未结束,已中止" + f"(工作流步数上限为 {settings.max_graph_steps}" + + (f",另为循环预留 {extra_steps} 步" if extra_steps else "") + ")。" + "可能存在没有轮数上限的环路:某个分支连回了上游,但没有用「循环」节点限制轮数。" + "请用「循环」节点包住这段环路;如确需更多步数,请联系管理员调大步数上限" + "(AGENTLAB_MAX_GRAPH_STEPS)" ) terminal = (EventType.RUN_FAILED, {"error": error}) except Exception as e: # noqa: BLE001 @@ -781,7 +780,7 @@ class RunManager: node_id=str(payload.get("node_id") or ""), interrupt_id=interrupt_id, mode=str(payload.get("mode") or "approve"), - title=str(payload.get("title") or "需要你确认"), + title=str(payload.get("title") or "待审批"), payload=payload, schema_=payload.get("schema") or {}, ) @@ -909,10 +908,10 @@ async def verify_manifest(run_id: str) -> dict[str, Any]: async with SessionLocal() as session: run = await session.get(Run, run_id) if run is None: - raise KeyError(f"找不到运行 {run_id}") + raise KeyError("运行记录不存在") if not run.manifest_hash: return {"sealed": False, "ok": None, - "message": "这次运行还没有封存(没跑完,或者停在人工审批)"} + "message": "这次运行尚未封存(尚未结束,或正停在人工审批)"} rows = [tuple(r) for r in await session.execute( select(RunEvent.seq, RunEvent.type, RunEvent.node_id, RunEvent.data) .where(RunEvent.run_id == run_id) @@ -933,7 +932,7 @@ async def verify_manifest(run_id: str) -> dict[str, Any]: ok = _manifest(covered) == expected return { "sealed": True, "ok": ok, "events": len(covered), "sealed_at": sealed_at, "legacy": legacy, - "message": "事件流与封存时一致" if ok else "事件流和封存时对不上:封存之后有事件被改过、删过或插过", + "message": "事件记录与封存时一致" if ok else "事件记录与封存时不一致:封存后有事件被修改、删除或插入", } @@ -962,20 +961,20 @@ def _clip(value: Any, limit: int = 4000) -> tuple[Any, bool]: _STATUS_TEXT = { - "queued": "还在排队", "running": "正在运行", "interrupted": "停在断点上", - "succeeded": "已完成", "failed": "失败了", "cancelled": "已取消", + "queued": "仍在排队", "running": "正在运行", "interrupted": "停在断点上", + "succeeded": "已完成", "failed": "已失败", "cancelled": "已取消", } def _cannot_resume(status: str) -> str: hint = { - "running": "它还在跑,不需要恢复。", - "queued": "它还没开始跑。", - "succeeded": "要再跑一次,请重新发起运行。", - "failed": "失败的运行用「接着跑」从出错的节点继续。", + "running": "运行仍在进行,无需恢复。", + "queued": "运行尚未开始。", + "succeeded": "如需再次运行,请重新发起。", + "failed": "失败的运行可点「继续运行」从出错的节点继续。", "cancelled": "已取消的运行请重新发起。", }.get(status, "") - return f"这次运行{_STATUS_TEXT.get(status, status)},没有在等审批,不能恢复。{hint}" + return f"这次运行{_STATUS_TEXT.get(status, status)},没有待处理的审批,无法恢复。{hint}" def _cannot_continue(status: str, has_pending: bool) -> str: @@ -985,15 +984,15 @@ def _cannot_continue(status: str, has_pending: bool) -> str: 在等审批,还让人去一张不存在的审批卡上处理;已取消的只说不行,不说该怎么办。 """ if status == "interrupted" and has_pending: - return "这次运行在等审批,不是失败了,不用接着跑。在审批卡上放行或驳回,它会自己往下走。" + return "这次运行正在等待审批,无需继续运行。在审批卡上批准或驳回后,运行会自动继续。" return { - "cancelled": "这次运行已取消,不能接着跑。要继续,请重新发起一次运行。", - "succeeded": "这次运行已完成,没有要接着跑的——只有失败的运行或被服务重启打断的运行" - "能接着跑。要再跑一次,请重新发起运行。", - "running": "这次运行正在运行,不需要接着跑。", - "queued": "这次运行还在排队,还没开始跑,不需要接着跑。", + "cancelled": "这次运行已取消,无法继续运行。如需继续,请重新发起运行。", + "succeeded": "这次运行已完成,无需继续运行:只有失败的运行或被服务重启打断的运行" + "可以继续运行。如需再次运行,请重新发起。", + "running": "这次运行正在进行,无需继续运行。", + "queued": "这次运行仍在排队,尚未开始,无需继续运行。", }.get(status, f"这次运行{_STATUS_TEXT.get(status, status)}," - "只有失败的运行或被服务重启打断的运行能接着跑。") + "只有失败的运行或被服务重启打断的运行可以继续运行。") def _carried(run: Run) -> dict[str, Any]: @@ -1031,8 +1030,8 @@ def _failure(exc: BaseException, spec: GraphSpec) -> tuple[str, tuple[EventType, detail = raw_detail(exc.__cause__) if exc.__cause__ is not None else None node_id: str | None = exc.node_id else: - message = (f"运行出错:{describe_exception(exc)}。技术细节已记在服务日志里;" - "可以点「接着跑」重试,仍然失败请把运行编号反馈给维护者") + message = (f"运行出错:{describe_exception(exc)}。技术细节已记录在服务日志中;" + "可点「继续运行」重试,如仍失败,请将运行编号反馈给维护者") detail = raw_detail(exc) node_id = None data: dict[str, Any] = {"error": message} diff --git a/backend/app/engine/schema.py b/backend/app/engine/schema.py index b6be8b01..5ed99873 100644 --- a/backend/app/engine/schema.py +++ b/backend/app/engine/schema.py @@ -8,6 +8,8 @@ from typing import Any, Iterable, Literal from pydantic import BaseModel, Field, field_validator, model_validator +from app.engine.labels import TYPE_LABEL, field_label, judge_label, option_label, q, type_label # noqa: F401 + class NodeType(StrEnum): """画布上可用的节点类型。新增类型 = 加一个枚举值 + 一个执行器 + 一个前端渲染。""" @@ -36,19 +38,8 @@ class NodeType(StrEnum): REPORT = "report" # 报告撰写:模型只写引用标记,数字由系统从口径卡取出来渲染 -# 节点类型在画布上的叫法。报错和门禁文案用它,而不是枚举值——用户在界面上从没 -# 见过 supervisor、llm 这些词。和前端 decode.ts / nodeDefs.ts 的叫法保持一致 -TYPE_LABEL: dict[str, str] = { - "input": "输入", "output": "成果 / 出具", "llm": "模型调用", "agent": "Agent", - "supervisor": "多 Agent 协作", "tool": "调用工具", "code": "沙箱代码", - "branch": "条件分支", "loop": "循环", "subgraph": "子工作流", - "memory": "长期记忆", "retrieve": "知识检索", "transform": "数据整形", - "human": "人工审批", "validate": "结构校验", "metrics": "口径卡", "report": "报告撰写", -} - - -def type_label(node_type: Any) -> str: - return TYPE_LABEL.get(str(node_type), str(node_type)) +# 节点类型在画布上的叫法(TYPE_LABEL / type_label)从 labels.py 导入:报错和门禁文案用它, +# 而不是枚举值——用户在界面上从没见过 supervisor、llm 这些词 class Position(BaseModel): @@ -75,10 +66,10 @@ class GraphNode(BaseModel): @classmethod def _valid_id(cls, v: str) -> str: if not v or not v.replace("_", "").replace("-", "").isalnum(): - raise ValueError(f"节点 id 只能包含字母数字、下划线和连字符:{v!r}") + raise ValueError(f"节点 ID 只能包含字母、数字、下划线和连字符,当前为「{v}」") # LangGraph 保留了这两个名字 if v in ("__start__", "__end__"): - raise ValueError(f"{v!r} 是保留节点名") + raise ValueError(f"「{v}」是保留的节点 ID,请换一个") return v @property @@ -361,18 +352,18 @@ def _check_case_keys(node: GraphNode, cases: list[Any], result: ValidationResult name = case.get("label") or key or f"第 {i} 个" field = f"cases[{i - 1}].key" if not key: - result.add(f"「条件分支」的分支「{name}」没有标识(key),连不出边、也走不到它", + result.add(f"「条件分支」的分支「{name}」没有标识,无法连线,也不会被选中", node_id=node.id, field=field) continue if key == "default": result.add( - f"分支「{name}」的标识用了 default:这是「其他」兜底出口的保留名,两者会合并成" - "同一个出口,跑完分不清走的是哪条。换一个标识,比如 team", + f"分支「{name}」的标识用了「default」:这是「其他」出口的保留名,两者会合并成" + "同一个出口,运行后无法区分走的是哪一条。请换一个标识,例如 team", level="warning", node_id=node.id, field=field, ) elif key in seen: - result.add(f"「条件分支」里有两个分支的标识都是 {key!r}:路由只认标识," - "后一个永远轮不到。给它换一个不重复的标识", node_id=node.id, field=field) + result.add(f"「条件分支」中有两个分支的标识都是「{key}」:路由只按标识区分," + "后一个分支不会被选中。请换一个不重复的标识", node_id=node.id, field=field) seen.add(key) @@ -405,7 +396,7 @@ def _check_report_sources(node: GraphNode, spec: GraphSpec, result: ValidationRe sources = [sources] code = "report.metrics_from_invalid" 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, + result.add("「报告撰写」的「指标来自」需要选择口径卡节点", node_id=node.id, field="metrics_from", code=code) return nodes = spec.node_map() @@ -413,15 +404,15 @@ def _check_report_sources(node: GraphNode, spec: GraphSpec, result: ValidationRe for src in sources: target = nodes.get(src) if target is None: - result.add(f"「报告撰写」的 metrics_from 指向 {src!r},但工作流里不存在这个节点", + result.add(f"「报告撰写」的「指标来自」选择了「{src}」,但工作流中不存在这个节点", node_id=node.id, field="metrics_from", code=code) elif target.type != NodeType.METRICS: - result.add(f"「报告撰写」的 metrics_from 指向「{target.title}」({src}),它不是「口径卡」" - f"节点,而是「{type_label(target.type)}」:报告里的指标只能从口径卡来", + result.add(f"「报告撰写」的「指标来自」选择了「{target.title}」,它是「{type_label(target.type)}」" + "节点,不是口径卡;报告中的指标只能来自口径卡", node_id=node.id, field="metrics_from", code=code) elif src not in upstream: - result.add(f"「报告撰写」的 metrics_from 指向的口径卡「{target.title}」不在它的上游:报告跑的" - "时候那张卡还没算,目录里不会有它的指标。把口径卡连到报告前面", + result.add(f"「报告撰写」的「指标来自」选择的口径卡「{target.title}」不在它的上游:撰写报告时" + "该口径卡尚未计算,报告无法引用它的指标。请把口径卡连到报告撰写节点之前", node_id=node.id, field="metrics_from", code=code) @@ -442,7 +433,8 @@ def claims_problem(value: Any) -> str | None: """claims 的取值有什么问题,没问题返回 None。校验和报告撰写节点执行时报的是同一句话。""" if value in (None, "") or (isinstance(value, str) and value in CLAIMS_VALUES): return None - return f"claims 只能是 {' / '.join(CLAIMS_VALUES)},写的是 {value!r}" + allowed = [f"「{option_label('claims', v)}」" for v in CLAIMS_VALUES] + return (f"「{field_label('claims')}」只能选{'、'.join(allowed[:-1])}或{allowed[-1]},当前为「{value}」") def _positive(value: Any, *, integer: bool = False) -> bool: @@ -460,28 +452,32 @@ def judge_problems(value: Any) -> list[tuple[str, str]]: if value in (None, ""): return [] if not isinstance(value, dict): - return [("judge", f'judge 要写成一个对象,比如 {{"max_cost_usd": 0.05, "max_claims": 40}},写的是 {value!r}')] + return [("judge", f"「{field_label('judge')}」设置格式有误,需要是一个对象" + f'(例如 {{"max_cost_usd": 0.05, "max_claims": 40}}),当前为「{value}」')] out: list[tuple[str, str]] = [] for key, item in value.items(): field = f"judge.{key}" if key not in JUDGE_KEYS: - out.append((field, f"judge 里不认识「{key}」:能写的是 {'、'.join(JUDGE_KEYS)}")) + known = "、".join(f"「{judge_label(k)}」" for k in JUDGE_KEYS) + out.append((field, f"「{field_label('judge')}」中无法识别「{key}」,可设置的项为:{known}")) elif key in ("provider", "model") and item is not None and not isinstance(item, str): - what = "模型接入的名字" if key == "provider" else "模型 id" - out.append((field, f"judge.{key} 要写{what}(字符串),不写或写 null 就用设置里的「证据裁判模型」," - f"写的是 {item!r}")) + what = "模型接入的名称" if key == "provider" else "模型 ID" + out.append((field, f"「{judge_label(key)}」需要填写{what},留空则使用设置中的「证据裁判」模型," + f"当前为「{item}」")) elif key == "max_claims" and item is not None and not _positive(item, integer=True): - out.append((field, f"judge.max_claims 要写正整数(每份报告最多判几句),写 null 表示不限,写的是 {item!r}")) + out.append((field, f"「{judge_label(key)}」需要填写正整数(每份报告最多裁判的句数),或选择不限," + f"当前为「{item}」")) elif key == "max_cost_usd" and item is not None and not _positive(item): - out.append((field, "judge.max_cost_usd 要写大于 0 的金额(美元,每份报告的裁判花费上限)," - f"写 null 表示不限,写的是 {item!r}")) + out.append((field, f"「{judge_label(key)}」需要填写大于 0 的金额(每份报告的裁判费用上限),或选择不限," + f"当前为「{item}」")) elif key == "timeout_s" and item is not None and not _positive(item): - out.append((field, f"judge.timeout_s 要写大于 0 的秒数(每份报告的裁判时长上限),写 null 表示不限," - f"写的是 {item!r}")) + out.append((field, f"「{judge_label(key)}」需要填写大于 0 的秒数(每份报告的裁判时长上限),或选择不限," + f"当前为「{item}」")) elif key == "rewrite_once" and not isinstance(item, bool): - out.append((field, f"judge.rewrite_once 只能是 true 或 false,写的是 {item!r}")) + out.append((field, f"「{judge_label(key)}」只能是开启或关闭,当前为「{item}」")) elif key == "on_unsupported" and item not in JUDGE_ON_UNSUPPORTED: - out.append((field, f"judge.on_unsupported 只能是 {' / '.join(JUDGE_ON_UNSUPPORTED)},写的是 {item!r}")) + allowed = "或".join(f"「{option_label(key, v)}」" for v in JUDGE_ON_UNSUPPORTED) + out.append((field, f"「{judge_label(key)}」只能选{allowed},当前为「{item}」")) return out @@ -506,8 +502,8 @@ def _check_report_claims(node: GraphNode, spec: GraphSpec, result: ValidationRes result.add(message, node_id=node.id, field=field, code="report.judge_invalid") judge_model = judge.get("model") if isinstance(judge, dict) else None if isinstance(judge_model, str) and judge_model and judge_model == effective("model"): - result.add(f"裁判模型和写作模型都是「{judge_model}」:等于自己审自己,模型写错的地方它多半也看不出来。" - "给 judge.model 换一个不同的模型", level="warning", node_id=node.id, field="judge.model", + result.add(f"裁判模型与写作模型相同(「{judge_model}」),难以发现写作模型自身的错误。" + f"请在「{field_label('judge')}」中选择另一个模型", level="warning", node_id=node.id, field="judge.model", code="report.judge_same_model") @@ -528,19 +524,19 @@ def _check_report_from(node: GraphNode, report_from: Any, spec: GraphSpec, """引用模式的契约:report_from 必须是出口上游的报告撰写节点。""" field, code = "contract.report_from", "contract.report_from_invalid" if not isinstance(report_from, str): - result.add("出具契约的 report_from 要写「报告撰写」节点的 id", node_id=node.id, field=field, code=code) + result.add("出具契约的「报告来自」需要选择一个「报告撰写」节点", node_id=node.id, field=field, code=code) return target = spec.node_map().get(report_from) if target is None: - result.add(f"出具契约的 report_from 指向 {report_from!r},但工作流里不存在这个节点", + result.add(f"出具契约的「报告来自」选择了「{report_from}」,但工作流中不存在这个节点", node_id=node.id, field=field, code=code) elif target.type != NodeType.REPORT: - result.add(f"出具契约的 report_from 指向「{target.title}」({report_from}),它不是「报告撰写」" - f"节点,而是「{type_label(target.type)}」:引用模式只核对报告撰写节点产出的文档", + result.add(f"出具契约的「报告来自」选择了「{target.title}」,它是「{type_label(target.type)}」节点," + "不是「报告撰写」节点:出具契约只核对报告撰写节点产出的文档", node_id=node.id, field=field, code=code) elif report_from not in _ancestors(spec, node.id): - result.add(f"出具契约的 report_from 指向的「{target.title}」不在这个出口的上游:出口核对的时候" - "那份报告还没写出来。把报告撰写节点连到出口前面", + result.add(f"出具契约的「报告来自」选择的「{target.title}」不在该成果节点的上游:核对时这份报告还没有写出。" + "请把报告撰写节点连到成果节点之前", node_id=node.id, field=field, code=code) @@ -550,18 +546,18 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: nodes = spec.node_map() if not spec.nodes: - result.add("图是空的,先拖一个节点进来") + result.add("画布上还没有节点,请先从节点库拖入一个节点") return result # 引用完整性 for edge in spec.edges: if edge.source not in nodes: - result.add(f"边指向了不存在的源节点 {edge.source!r}", edge_id=edge.id) + result.add(f"连线的起点节点「{edge.source}」不存在", edge_id=edge.id) if edge.target not in nodes: - result.add(f"边指向了不存在的目标节点 {edge.target!r}", edge_id=edge.id) + result.add(f"连线的终点节点「{edge.target}」不存在", edge_id=edge.id) if not spec.entry_nodes(): - result.add("找不到入口:每个节点都有入边,工作流里有环且没有起点") + result.add("找不到起始节点:每个节点都有上游连线,工作流中存在环路且没有起点") # 节点级必填项 for node in spec.nodes: @@ -569,29 +565,29 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: if node.type == NodeType.BRANCH: cases = cfg.get("cases") or [] if not cases: - result.add("「条件分支」至少要配一个分支条件", node_id=node.id, field="cases") + result.add("「条件分支」至少需要配置一个分支条件", node_id=node.id, field="cases") handles = {e.sourceHandle for e in spec.outgoing(node.id)} _check_case_keys(node, cases, result) for i, case in enumerate(cases): key = str((case or {}).get("key") or "").strip() if key and key != "default" and key not in handles: result.add( - f"分支 {key!r} 没有连出去的边", level="warning", node_id=node.id, + f"分支「{key}」还没有连线", level="warning", node_id=node.id, field=f"cases[{i}].key", ) if "default" not in handles: result.add( - "建议给「条件分支」的「其他」出口连一条边,兜住所有条件都不满足的情况", + "建议为「条件分支」的「其他」出口添加连线,处理所有条件都不满足的情况", level="warning", node_id=node.id, field="cases", ) elif node.type == NodeType.TOOL: if not cfg.get("tool"): - result.add("「调用工具」节点还没选工具", node_id=node.id, field="tool") + result.add("「调用工具」节点还没有选择工具", node_id=node.id, field="tool") elif node.type == NodeType.SUBGRAPH: if not cfg.get("workflow_id"): - result.add("「子工作流」节点还没选要嵌套的工作流", node_id=node.id, + result.add("「子工作流」节点还没有选择要嵌套的工作流", node_id=node.id, field="workflow_id") elif node.type == NodeType.VALIDATE: if not cfg.get("schema"): @@ -603,7 +599,7 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: result.add("口径卡还没有定义指标", node_id=node.id, field="metrics") for i, d in enumerate(defs): if not d.get("id") or not d.get("expression"): - result.add(f"指标定义缺 id 或 expression:{d.get('id') or '(空)'}", + result.add(f"指标定义缺少 ID 或表达式:{d.get('id') or '(空)'}", node_id=node.id, field=f"metrics[{i}]") elif node.type == NodeType.REPORT: _check_report_sources(node, spec, result) @@ -616,7 +612,7 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: result.add("出具契约必须是一个 JSON 对象", node_id=node.id, field="contract", code="contract.not_object") elif contract and not contract.get("metrics_from") and contract_needs_metrics(contract): - result.add("出具契约缺 metrics_from(指标来自哪个「口径卡」节点)", + result.add("出具契约缺少「指标来自」(提供指标的口径卡)", node_id=node.id, field="contract.metrics_from", code="contract.metrics_from_missing") if isinstance(contract, dict) and contract.get("report_from") not in (None, ""): _check_report_from(node, contract["report_from"], spec, result) @@ -627,7 +623,7 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: if node.type in (NodeType.LLM, NodeType.AGENT, NodeType.SUPERVISOR, NodeType.REPORT): if not (cfg.get("model") or spec.defaults.get("model")): result.add( - "没有指定模型,将回退到默认 provider", + "没有指定模型,将使用默认模型", level="warning", node_id=node.id, field="model", @@ -643,28 +639,28 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: try: _, unwrapped, unknown = parse_expression(text) except ExpressionError as e: - result.add(f"{label}写错了:{e}(原文:{text})", node_id=node.id, field=field) + result.add(f"{label}有误:{e}(原文:{text})", node_id=node.id, field=field) continue if unwrapped: result.add( - f"{label}里的 {{{{ }}}} 是多余的——这里是表达式、不是模板," + f"{label}中的 {{{{ }}}} 是多余的:这里是表达式,不是模板," f"已按 {'、'.join(unwrapped)} 理解", level="warning", node_id=node.id, field=field, ) if unknown: result.add( - f"{label}里的 {'、'.join(unknown)} 不是能用的名字,运行时会取到空值" - "(变量要写全:vars.x、input.x、nodes.某节点.text)", + f"{label}中的 {'、'.join(unknown)} 不是可用的名称,运行时会取到空值" + "(变量需写完整路径,例如 vars.x、input.x、nodes.某节点.text)", level="warning", node_id=node.id, field=field, ) cfg = node.config if node.type == NodeType.LOOP and cfg.get("mode", "foreach") == "while" \ and not str(cfg.get("condition") or "").strip(): - result.add("while 循环没有写条件,循环体一次都不会跑", level="warning", node_id=node.id, + result.add("条件循环没有设置「继续条件」,循环体不会执行", level="warning", node_id=node.id, field="condition") if node.type == NodeType.TRANSFORM and cfg.get("mode", "expression") == "expression" \ and not str(cfg.get("expression") or "").strip(): - result.add("整形节点没有填表达式", node_id=node.id, field="expression") + result.add("「数据整形」节点还没有填写表达式", node_id=node.id, field="expression") # assign_to 拿到的是 stdout。脚本最后一行写个裸表达式不会输出(那是 notebook # 的行为)——变量是空的,下游的循环条件一上来就不成立、成果也是空的,而整次 # 运行照样"成功"。开发库里的「测试 1」就是这样:修好条件之后跑通了,结果为空 @@ -676,9 +672,9 @@ def validate_graph(spec: GraphSpec) -> ValidationResult: if not _MAY_WRITE_STDOUT.search(source): var = cfg["assign_to"] result.add( - f"代码把输出交给 vars.{var},可代码里没有 print:Python 脚本最后一行的表达式" - f"不会自动输出,vars.{var} 会是空的。把结果 print 出来;要交给下游一个对象," - "就 print(json.dumps(结果))", node_id=node.id, field="code", + f"代码把输出交给 vars.{var},但代码中没有 print:Python 脚本最后一行的表达式" + f"不会自动输出,vars.{var} 将为空。请用 print 输出结果;如需向下游传递对象," + "请使用 print(json.dumps(结果))", node_id=node.id, field="code", ) _check_named_tools(spec, result) @@ -869,17 +865,18 @@ def _check_named_tools(spec: GraphSpec, result: ValidationResult) -> None: if explicit: message = (f"{who}的提示词要求用「{tool}」,但没有给这个成员绑定它" if who else f"提示词要求用「{tool}」,但节点没有绑定它") - result.add(f"{message}:运行时模型拿不到这个工具,只能编一个结果出来。" - "把它加进工具里,或者改掉提示词里的要求", + where = "该成员的工具" if who else f"「{field_label('tools')}」" + result.add(f"{message}:运行时模型无法调用该工具,可能会编造结果。" + f"请把它加入{where},或删除提示词中的这项要求", node_id=node.id, field=field) else: result.add(f"{who + '的' if who else ''}提示词提到了「{tool}」,但{'这个成员' if who else '节点'}没有" - "绑定它:如果是要模型调用它,运行时拿不到。需要就把它加进工具里", + "绑定它:如果需要模型调用它,运行时将无法调用。如有需要,请把它加入工具", level="warning", node_id=node.id, field=field) # 已经点名报过了,那句笼统的就不再重复 if vague_at is not None and not reported: result.add(f"{who or '提示词'}要求调用工具,但{'这个成员' if who else '这个节点'}没有绑定任何" - "工具:模型拿不到工具,只能假设一个结果。绑定要用的工具,或者改掉这句要求", + "工具:模型无法调用工具,只能假设调用结果。请绑定要用的工具,或删除这项要求", level="warning", node_id=node.id, field=vague_at) for node in agents: @@ -902,12 +899,12 @@ def _check_named_tools(spec: GraphSpec, result: ValidationResult) -> None: if _covers(team_tools, tool): continue if explicit: - result.add(f"协作目标要求用「{tool}」,但没有哪个成员绑定了它:调度者派出去的人" - "谁都调不了它。给负责的成员加上这个工具,或者改掉目标里的要求", + result.add(f"团队目标要求用「{tool}」,但没有任何成员绑定该工具:调度者分派的成员" + "都无法调用它。请为负责的成员添加该工具,或删除目标中的这项要求", node_id=node.id, field="goal") else: - result.add(f"协作目标提到了「{tool}」,但没有哪个成员绑定了它:如果是要成员" - "调用它,谁都拿不到。需要就给负责的成员加上", + result.add(f"团队目标提到了「{tool}」,但没有任何成员绑定该工具:如果需要成员" + "调用它,目前都无法调用。如有需要,请为负责的成员添加", level="warning", node_id=node.id, field="goal") @@ -998,11 +995,12 @@ def _feeds_caliber(node: GraphNode, spec: GraphSpec) -> bool: def _structured_fix(source: GraphNode) -> str: if source.type == NodeType.AGENT: var = str(source.config.get("assign_to") or "").strip() or "变量名" - return (f"给「{source.title}」配 output_schema 并开 cite_fields,口径卡直接读 vars.{var}.字段" - "(每个字段都核对到查询结果里的那一格)") + return (f"为「{source.title}」配置「结构化输出 Schema」并开启「按出处核对字段」,口径卡直接读取 " + f"vars.{var}.字段(每个字段都核对到查询结果中的对应单元格)") if source.type == NodeType.LLM: - return f"给「{source.title}」配 output_schema;数要进口径卡的,改用 agent 的 output_schema + cite_fields" - return "数要进口径卡的,改用 agent 的 output_schema + cite_fields" + return (f"为「{source.title}」配置「结构化输出 Schema」;数字需要进入口径卡时,请改用 Agent 并开启" + "「按出处核对字段」") + return "数字需要进入口径卡时,请改用 Agent,配置「结构化输出 Schema」并开启「按出处核对字段」" def _json_spans(template: str) -> list[tuple[str, bool]]: @@ -1040,14 +1038,14 @@ def text_parse_issues(spec: GraphSpec) -> list[ValidationIssue]: if spans and all(quoted for _, quoted in spans): # 模型的文字放在模板的引号里:不是在解析它,是在拼字符串,少的是 | json expr = spans[0][0] - message = (f"模板里 {{{{ {expr} }}}} 放在 JSON 的引号里:{who}写的文字只要带英文引号、换行,JSON 就被" - f"撑破,整个节点失败。写成 {{{{ {expr} | json }}}}(外面不要再加引号)") + message = (f"模板中的 {{{{ {expr} }}}} 位于 JSON 引号内:{who}写的文字只要包含英文引号或换行,JSON 就会" + f"格式错误,导致整个节点失败。请改写为 {{{{ {expr} | json }}}}(外面不要再加引号)") elif mode == "json": - message = (f"整形节点按 JSON 解析{who}写的文字:模型写的 JSON 常夹着没转义的英文引号,解析一失败" - f"整个节点就失败。改成让它直接交结构化数据:{_structured_fix(sources[0])}") + message = (f"「数据整形」节点按 JSON 解析{who}写的文字:模型写的 JSON 常含有未转义的英文引号,一旦解析失败," + f"整个节点就会失败。请改为让它直接输出结构化数据:{_structured_fix(sources[0])}") elif _feeds_caliber(node, spec): - message = (f"口径卡的数要经这个整形节点从{who}写的文字里取:文字不是结构化数据,取不准,也核对不了出处。" - f"{_structured_fix(sources[0])}") + message = (f"口径卡的数字需要经过这个「数据整形」节点,从{who}写的文字中提取:文字不是结构化数据,提取不可靠," + f"也无法追溯出处。{_structured_fix(sources[0])}") else: continue out.append(ValidationIssue(level="warning", node_id=node.id, field=field, message=message)) @@ -1098,13 +1096,14 @@ def evidence_issues(spec: GraphSpec) -> list[ValidationIssue]: for node in spec.nodes: cfg = node.config if node.type == NodeType.AGENT and cfg.get("output_schema") and cfg.get("cite_fields") is not True: - add("output_schema 要开 cite_fields 才生效,会多一次抽取调用:开了之后循环结束再按 Schema " - "抽一次字段,每个字段都核对到查询结果里的那一格;不开的话 assign_to 拿到的仍是自由文字", + add("「结构化输出 Schema」需要同时开启「按出处核对字段」才会生效(会多一次抽取调用):开启后,Agent 执行" + "结束时按 Schema 抽取字段,每个字段都核对到查询结果中的对应单元格;不开启时,「结果存为变量」得到的" + "仍是自由文本", node, "output_schema", code="evidence.cite_fields_off") elif node.type == NodeType.CODE: role = cfg.get("evidence_role") if role not in (None, "") and role not in EVIDENCE_ROLES: - add(f"evidence_role 只能是 source(取数)或 compute(计算),写的是 {role!r}", node, + add(f"「证据角色」只能是「取数」或「计算」,当前为「{role}」", node, "evidence_role", level="error") elif node.type == NodeType.METRICS: if cfg.get("caliber_from") not in (None, "", {}): @@ -1115,9 +1114,9 @@ def evidence_issues(spec: GraphSpec) -> list[ValidationIssue]: if producer.type != NodeType.CODE or role == "source" or producer.id in warned: continue warned.add(producer.id) - add(f"口径卡的输入来自沙箱代码「{producer.title}」,它的角色是计算(evidence_role 不是 source):" - "沙箱里算出来的数核对不了出处。负责取数的代码节点把 evidence_role 标成 source;" - "业务计算挪进口径卡的表达式", node, f"metrics[{i}].expression", + add(f"口径卡的输入来自沙箱代码「{producer.title}」,它的「证据角色」是「计算」:沙箱中计算出的数字" + "无法追溯出处。负责取数的代码节点请将「证据角色」设为「取数」;业务计算请移到口径卡的表达式中", + node, f"metrics[{i}].expression", code="evidence.caliber_compute_input") return out @@ -1133,18 +1132,19 @@ def _caliber_from_issues(node: GraphNode, policies: set[str], labels: dict[str, if not isinstance(ref, dict) or not str(ref.get("workflow_id") or "").strip() \ or not str(ref.get("node_id") or "").strip(): - add("caliber_from 要写 {workflow_id, workflow_version, node_id}:钉住哪个工作流的哪一版里的哪张口径卡", - "caliber_from") + add(f"「{field_label('caliber_from')}」需要选定工作流、版本和其中的口径卡", "caliber_from") return out version = ref.get("workflow_version") if isinstance(version, bool) or not (isinstance(version, int) or (isinstance(version, str) and version.isdigit())) \ or int(version) < 1: - add(f"caliber_from 的 workflow_version 要写具体的版本号(1、2…),写的是 {version!r}:不钉版本,口径会跟着" - "上游漂移", "caliber_from.workflow_version") + add(f"「{field_label('caliber_from')}」需要选择具体的版本号(1、2…),当前为「{version}」:不固定版本," + "口径会随上游变化", "caliber_from.workflow_version") if cfg.get("metrics"): - add("写了 caliber_from 就按钉住的那张卡算,这里自己写的 metrics 不会生效", "metrics", level="warning") + add(f"已设置「{field_label('caliber_from')}」,将按所引用的口径卡计算,此处填写的「{field_label('metrics')}」" + "不会生效", "metrics", level="warning") policy = cfg.get("upgrade_policy") if policy not in (None, "") and policy not in policies: - add("upgrade_policy 只能是 " + " / ".join(f"{k}({v})" for k, v in labels.items()) - + f",写的是 {policy!r}", "upgrade_policy") + allowed = [f"「{v}」" for v in labels.values()] + add(f"「{field_label('upgrade_policy')}」只能选{'、'.join(allowed[:-1])}或{allowed[-1]},当前为「{policy}」", + "upgrade_policy") return out diff --git a/backend/app/engine/toolcalls.py b/backend/app/engine/toolcalls.py index 52c096c5..5cb6b26c 100644 --- a/backend/app/engine/toolcalls.py +++ b/backend/app/engine/toolcalls.py @@ -92,10 +92,10 @@ class ToolTimeout(TimeoutError): self.limit = limit seconds = _seconds(limit.seconds) if limit.kind == "query": - text = (f"查询超过 {seconds}s 没有返回,已放弃等待(数据库那边可能还在跑,连接会在后台" - "收回)。加上 WHERE 条件或 LIMIT 缩小范围再查") + text = (f"查询超过 {seconds} 秒没有返回,已停止等待(数据库可能仍在执行,连接会在后台" + "回收)。请添加 WHERE 条件或 LIMIT 缩小范围后重试") else: - text = f"工具 {name} 超过 {seconds}s 没有返回,已放弃等待" + text = f"工具 {name} 超过 {seconds} 秒没有返回,已停止等待" super().__init__(text) @@ -148,9 +148,9 @@ _SQL_KEY = re.compile(r'"sql"\s*:') _PRETEND = re.compile(r"假设(?:调用|使用|执行)了?(?:工具|查询)|假装调用|模拟调用(?:了)?工具") TOOL_MARKUP_ERROR = ( - "模型输出了工具调用的原始标记,但没有真正调用工具,这一步一次都没查到数据。" - "常见原因:节点没有绑定工具,或者模型、服务不支持工具调用。" - "到画布里给这个节点绑定要用的工具;绑定了还这样,就换一个支持工具调用的模型" + "模型以文本形式输出了工具调用的原始标记,未实际调用工具,这一步没有查询到任何数据。" + "常见原因:节点未绑定工具,或模型、服务不支持工具调用。" + "请在画布中为该节点绑定所需工具;如已绑定仍出现此问题,请换用支持工具调用的模型" ) TOOL_MARKUP_NUDGE = ( @@ -172,4 +172,4 @@ def leaked_markup(text: str | None) -> str | None: def markup_warning(snippet: str, who: str = "模型") -> str: - return f"{who}把工具调用写成了文字({snippet[:40]}…),没有真正调用工具" + return f"{who}以文本形式输出了工具调用({snippet[:40]}…),未实际调用工具" diff --git a/backend/app/engine/upgrade.py b/backend/app/engine/upgrade.py index 630d9b22..022e39a5 100644 --- a/backend/app/engine/upgrade.py +++ b/backend/app/engine/upgrade.py @@ -36,6 +36,7 @@ from app.engine.governance import ( _refs, publish_issues, ) +from app.engine.labels import field_label, option_label from app.engine.schema import GraphNode, GraphSpec, NodeType, _ancestors, _feeds_caliber, innermost_loops #: 会改图的规则,按这个顺序应用:先换写字的节点,再插报告,最后开 cite_fields(R3 要先把出口从 agent 的 @@ -149,12 +150,12 @@ def _llm_blocked(spec: GraphSpec, node: GraphNode, loops: dict[str, str]) -> str """这个模型调用节点能不能原样换成报告撰写;不能的说清为什么。""" who = f"「{node.title}」(模型调用)" if node.config.get("output_schema"): - return f"{who}配了 output_schema,交的是结构化数据、不是给人看的文字,没有换成报告撰写" + return f"{who}配置了「结构化输出 Schema」,输出的是结构化数据而不是给人看的文字,因此没有换成报告撰写" if node.id in loops: - return f"{who}在循环体里,换成报告撰写就是每一轮写一份报告:循环怎么改要你来定,升级没有动它" + return f"{who}位于循环体中,换成报告撰写会导致每一轮都写一份报告:循环结构需要由你调整,升级未作修改" if _feeds_caliber(node, spec): - return (f"{who}写的数还喂给了口径卡:换成报告撰写,口径卡就读不到它了。先把取数改由 Agent(配 output_schema、" - "开 cite_fields)或「调用工具」节点来做,再升级") + return (f"{who}写的数字还提供给了口径卡:换成报告撰写后,口径卡将无法读取这些数字。请先改由 Agent(配置" + "「结构化输出 Schema」、开启「按出处核对字段」)或「调用工具」节点取数,再升级") return None @@ -191,14 +192,14 @@ def upgrade_candidates(spec: GraphSpec) -> list[Match]: if len(writers) > 1: # 叙述拼了几个节点写的文字:换哪一个都会让其余的文字悄悄离开契约的核对。拼进来的每个模型调用都不换, # 哪怕它另有一个只读它的出口——不然结果要看两个出口在画布上谁排前面 - why = (f"「{exit_node.title}」的出具契约 narrative 拼了{_names(writers)}几个节点写的文字,该换哪一个说不准," - "没有升级:让一个节点写完整篇(其余的内容交给它当素材),再升级") + why = (f"「{exit_node.title}」的出具契约「叙述」拼接了{_names(writers)}等多个节点的文字,无法确定应替换" + "哪一个,因此没有升级。请由一个节点撰写全文(其余内容作为它的素材),再升级") for llm in llms: _add(found, Match("R1", llm.id, blocked=why)) elif llms: llm = llms[0] _add(found, Match("R1", llm.id, (exit_node.id,), - f"「{llm.title}」(模型调用)写的叙述换成报告撰写,出具契约改为核对它的文档", + f"把「{llm.title}」(模型调用)写的叙述换成报告撰写,出具契约改为核对它的文档", _llm_blocked(spec, llm, loops))) r1 = {m.node_id for m in found.values()} @@ -209,7 +210,7 @@ def upgrade_candidates(spec: GraphSpec) -> list[Match]: if llm.id in r1 or not any(_fetches(nodes[a]) for a in _ancestors(spec, llm.id) if a in nodes): continue _add(found, Match("R2", llm.id, (exit_node.id,), - f"「{llm.title}」(模型调用)写的文字直接进了出口,换成报告撰写", + f"「{llm.title}」(模型调用)写的文字直接进入了成果节点,换成报告撰写", _llm_blocked(spec, llm, loops))) for exit_node in outputs: @@ -229,15 +230,15 @@ def upgrade_candidates(spec: GraphSpec) -> list[Match]: # 说不准的只跳过这个出口:同一个 agent 直连的出口照样插报告撰写,结果不看出口在画布上的顺序 if agent.id in loops: _add(found, Match("R3", agent.id, blocked=( - f"「{agent.title}」在循环体里,升级不替你改循环结构,没有插入报告撰写"))) + f"「{agent.title}」位于循环体中,升级不会修改循环结构,因此没有插入报告撰写"))) elif not any(e.source == agent.id and e.target == exit_node.id for e in spec.edges): _add(found, Match("R3", agent.id, skipped=( - f"「{agent.title}」的原话要经过别的节点才到「{exit_node.title}」,升级不替你改接中间的连线:在它后面" - f"接一个报告撰写,「{exit_node.title}」改取报告的正文",))) + f"「{agent.title}」的原话要经过其他节点才到达「{exit_node.title}」,升级不会改接中间的连线:请在它" + f"后面接一个报告撰写节点,「{exit_node.title}」改为取报告的正文",))) elif agent.id in {n.id for n in narrated} and len(narrated) > 1: _add(found, Match("R3", agent.id, skipped=( - f"「{exit_node.title}」的出具契约 narrative 拼了{_names(narrated)}几个节点写的文字,改成核对报告撰写的" - "文档,其余的文字就悄悄离开了核对:这个出口升级没有动。让一个节点写完整篇,再升级",))) + f"「{exit_node.title}」的出具契约「叙述」拼接了{_names(narrated)}等多个节点的文字,改为核对报告撰写" + "的文档后,其余文字将不再受核对,因此没有升级这个成果节点。请由一个节点撰写全文后再升级",))) else: _add(found, Match("R3", agent.id, (exit_node.id,))) @@ -247,13 +248,13 @@ def upgrade_candidates(spec: GraphSpec) -> list[Match]: agent = nodes[m.node_id] if m.exits: found[key] = replace(m, summary=f"在「{agent.title}」和{_names([nodes[x] for x in m.exits])}之间插入报告撰写," - "答案里的数逐个点得开出处") + "答案中的数字均可查看出处") elif not m.blocked: found[key] = replace(m, blocked=";".join(m.skipped), skipped=()) for n in spec.nodes: if n.type == NodeType.AGENT and n.config.get("output_schema") and n.config.get("cite_fields") is not True: - _add(found, Match("R4", n.id, (), f"打开「{n.title}」的 cite_fields,output_schema 才生效")) + _add(found, Match("R4", n.id, (), f"开启「{n.title}」的「按出处核对字段」,「结构化输出 Schema」才会生效")) return sorted(found.values(), key=lambda m: (RULES.index(m.rule), order.get(m.node_id, len(order)))) @@ -267,7 +268,7 @@ def upgrade_hint(spec: GraphSpec) -> str | None: if not ready: return None parts = [m.summary for m in ready[:3]] + ([f"另有 {len(ready) - 3} 处"] if len(ready) > 3 else []) - return f"{HINT}:{';'.join(parts)}。先预览改动,确认了才保存" + return f"{HINT}:{';'.join(parts)}。请先预览改动,确认后再保存" # -------------------------------------------------------------------------- @@ -352,8 +353,8 @@ def _retype(graph: dict[str, Any], spec: GraphSpec, match: Match, level: str) -> raw["type"] = NodeType.REPORT.value raw["data"]["config"] = after title = node.title - step = _Step(label=(f"把「{title}」换成报告撰写,出具契约改为核对它的文档" if match.rule == "R1" - else f"把「{title}」换成报告撰写"), + step = _Step(label=(f"将「{title}」换成报告撰写,出具契约改为核对它的文档" if match.rule == "R1" + else f"将「{title}」换成报告撰写"), retyped={(node.id, NodeType.LLM.value, NodeType.REPORT.value)}, created=True) step.changes = [_change(node.id, title, "type", NodeType.LLM.value, NodeType.REPORT.value), *_config_changes(node.id, title, before, after)] @@ -363,15 +364,17 @@ def _retype(graph: dict[str, Any], spec: GraphSpec, match: Match, level: str) -> dropped = [k for k in _LLM_ONLY if k not in ("prompt", "system") and before.get(k) not in (None, "", [], {})] if before.get("skills"): skills = before["skills"] if isinstance(before["skills"], list) else [before["skills"]] - step.notes.append(_note(f"「{title}」挂的技能 {'、'.join(f'「{s}」' for s in skills)} 不会再加载:报告撰写不挂技能," - "其中的写作要求要保留的话,写进 instructions", match.rule, node.id, "warning")) + step.notes.append(_note(f"「{title}」挂载的 Skill {'、'.join(f'「{s}」' for s in skills)} 将不再加载:报告撰写节点" + f"不挂载 Skill,其中的写作要求如需保留,请写入「{field_label('instructions')}」", + match.rule, node.id, "warning")) if other := [k for k in dropped if k != "skills"]: - step.notes.append(_note(f"「{title}」的 {'、'.join(other)} 报告撰写用不上,已去掉", match.rule, node.id)) + named = "、".join(f"「{field_label(k, NodeType.LLM.value)}」" for k in other) + step.notes.append(_note(f"「{title}」的{named}在报告撰写节点中不适用,已去掉", match.rule, node.id)) if echoed := _echoed_evidence(_Graph(spec), node.id, text): step.notes.append(_note( - f"「{title}」的 instructions 里照搬了 {'、'.join(echoed)}:报告撰写会自己收集上游的口径卡指标和查询结果,数字由" - "系统渲染;直接塞进指令的这段文字里的数,模型容易照抄成不带出处的裸数字(会被打回重写)。确认用不上就删掉," - "升级没有替你删", match.rule, node.id)) + f"「{title}」的「{field_label('instructions')}」中照搬了 {'、'.join(echoed)}:报告撰写节点会自行收集上游的" + "口径卡指标和查询结果,数字由系统填入;直接写在要求中的数字,模型容易照抄成不带出处的数字(会被要求重写)。" + "如确认不需要,请删除;升级未作删除", match.rule, node.id)) if match.rule == "R1": for exit_id in match.exits: exit_raw = _raw(graph, exit_id) @@ -444,7 +447,7 @@ def _insert(graph: dict[str, Any], spec: GraphSpec, match: Match, level: str) -> "data": {"label": "报告撰写", "config": config}} graph["nodes"].insert(graph["nodes"].index(raw_agent) + 1, new) exits = [nodes[x] for x in match.exits] - step = _Step(label=f"在「{agent.title}」和{_names(exits)}之间插入报告撰写,出口改取报告的正文", + step = _Step(label=f"在「{agent.title}」和{_names(exits)}之间插入报告撰写,成果节点改为取报告的正文", rewired={(agent.id, x.id) for x in exits}, created=True) step.changes.append(_change(rid, "报告撰写", "node", None, {"id": rid, "type": NodeType.REPORT.value, "label": "报告撰写", "config": config})) @@ -481,8 +484,8 @@ def _insert(graph: dict[str, Any], spec: GraphSpec, match: Match, level: str) -> if isinstance(f, dict) and f != old and f.get("value", "").strip() != exact] if mixed: step.notes.append(_note( - f"「{x.title}」的成果字段{'、'.join(f'「{n}」' for n in mixed)}在报告正文前后还拼了别的内容:这样没法" - f"逐段对应证据。要每个数都点得开,字段里只放 {exact}", "R3", x.id)) + f"「{x.title}」的成果字段{'、'.join(f'「{n}」' for n in mixed)}在报告正文前后还拼接了其他内容," + f"无法逐段对应证据。如需每个数字都可查看出处,字段中只放 {exact}", "R3", x.id)) contract = cfg.get("contract") narrative = contract.get("narrative") if isinstance(contract, dict) else None if isinstance(narrative, str) and agent.id in { @@ -507,16 +510,18 @@ def _cells_note(spec: GraphSpec, exits: list[GraphNode], converted: list[dict[st if converted and all(c.get("cells") is True for c in converted): return None where = _names(exits) - choose = (f"二选一:在{where}的出具契约里写 cells: true;或者改走口径卡,把要写的数登记成指标,报告只引用 " - "[[m:指标id]]。选哪条要你拿主意,升级没有替你写") + choose = (f"二选一:在{where}的出具契约中开启「单元格引用」;或改用口径卡,把要写的数字登记为指标,报告只引用" + "指标。选择哪一种需要由你决定,升级未作修改") cards = any(n.type == NodeType.METRICS for n in spec.nodes) if level == "governed" or (converted and not cards): - lead = "按受管级别" if level == "governed" else "现在(已发布级别)照常;以后按受管级别发布的话" - return (f"报告会直接引用查询单元格([[v:Q1.r0.列]]),{lead},正式运行只在出口的出具契约写了 cells: true 时才认单元格" - "引用:不写的话报告里的数一个都引用不了,报告节点(numbers: strict、on_violation: fail)每次正式运行都会失败。" + lead = "按受管级别" if level == "governed" else "当前(已发布级别)不受影响;今后按受管级别发布时" + numbers = f"「{field_label('numbers')}」为「{option_label('numbers', 'strict')}」" + violation = f"「{field_label('on_violation')}」为「{option_label('on_violation', 'fail')}」" + return (f"报告会直接引用查询单元格,{lead},正式运行只在成果节点的出具契约开启「单元格引用」时才接受单元格引用:" + f"未开启时报告中的数字都无法引用,报告撰写节点({numbers}、{violation})每次正式运行都会失败。" + choose, "warning") - return ("报告会直接引用查询单元格([[v:Q1.r0.列]])。探索运行和已发布级别照常;要按受管级别正式出具,得在出口的出具契约里写 " - "cells: true,或者改走口径卡:把要写的数登记成指标,报告只引用 [[m:指标id]]。选哪条要你拿主意,升级没有替你加契约", + return ("报告会直接引用查询单元格。探索运行和已发布级别不受影响;如需按受管级别正式出具,请在成果节点的出具契约中开启" + "「单元格引用」,或改用口径卡:把要写的数字登记为指标,报告只引用指标。选择哪一种需要由你决定,升级未添加出具契约", "info") @@ -549,14 +554,14 @@ def _cite(graph: dict[str, Any], spec: GraphSpec, match: Match, level: str) -> _ cfg = _config(_raw(graph, agent.id)) before = cfg.get("cite_fields") cfg["cite_fields"] = True - step = _Step(label=f"打开「{agent.title}」的 cite_fields:每个字段都核对到查询结果里的那一格") + step = _Step(label=f"开启「{agent.title}」的「按出处核对字段」:每个字段都核对到查询结果中的对应单元格") step.changes = [_change(agent.id, agent.title, "cite_fields", before, True)] step.ops = [{"op": "update_node", "id": agent.id, "config": {"cite_fields": True}}] var = str(agent.config.get("assign_to") or "").strip() for reader, span in _whole_var_readers(spec, var) if var else []: step.notes.append(_note( - f"「{agent.title}」开了 cite_fields 以后,vars.{var} 拿到的是核对过的对象,不再是文字:「{reader.title}」里的 " - f"{span} 会显示成对象。要原话就改成 {{{{ nodes.{agent.id}.text }}}}", "R4", reader.id, "warning")) + f"「{agent.title}」开启「按出处核对字段」后,vars.{var} 得到的是核对过的对象,而不再是文字:「{reader.title}」中的 " + f"{span} 会显示为对象。如需原话,请改为 {{{{ nodes.{agent.id}.text }}}}", "R4", reader.id, "warning")) return step @@ -593,9 +598,9 @@ def metric_feeders(spec: GraphSpec, card: GraphNode) -> list[tuple[int, GraphNod def _r5_notes(spec: GraphSpec) -> list[dict[str, Any]]: return [_note( - f"「{code.title}」(沙箱代码)的产出喂给了口径卡{_names(cards)}:它如果是在取数(查库、调接口、读文件),把 " - "evidence_role 标成 source,口径卡读它时记得下出处;如果是在做计算,把计算挪进口径卡的表达式(交给 Copilot " - "可以请它把纯算术的代码改写成口径卡表达式)。它在取数还是在算只有你知道,升级没有替你改", "R5", code.id) + f"「{code.title}」(沙箱代码)的产出提供给了口径卡{_names(cards)}:若它负责取数(查库、调用接口、读文件)," + "请把「证据角色」设为「取数」,口径卡读取时会记录出处;若负责计算,请把计算移到口径卡的表达式中(可交给助手" + "把纯算术的代码改写为口径卡表达式)。它负责取数还是计算需要由你确认,升级未作修改", "R5", code.id) for code, cards in compute_feeders(spec)] @@ -625,7 +630,7 @@ def upgrade_for_evidence(graph: dict[str, Any] | GraphSpec, *, level: str = "pub - applied:采用的 "R1:<节点 id>"…;rejected:[{fix_id, reason}],碰了禁止规则或者会冒出新 error 的 """ if level not in LEVELS: - raise ValueError(f"level 只能是 {' / '.join(LEVELS)},写的是 {level!r}") + raise ValueError(f"发布级别只能是「已发布」或「受管」,当前为「{level}」") raw = graph.model_dump(mode="json") if isinstance(graph, GraphSpec) else graph current = copy.deepcopy(raw) spec = GraphSpec.model_validate(current) @@ -656,14 +661,14 @@ def upgrade_for_evidence(graph: dict[str, Any] | GraphSpec, *, level: str = "pub try: trial_spec = GraphSpec.model_validate(trial) except Exception: # noqa: BLE001 - 规则把图改坏了:丢弃,不交给人一张存不回去的图 - rejected.append({"fix_id": fix_id, "reason": "改完的图结构读不懂,这一步没有采用"}) + rejected.append({"fix_id": fix_id, "reason": "修改后的工作流结构无法解析,这一步未采用"}) continue trial_issues = publish_issues(trial_spec, level=level) why = ";".join(forbidden(current, trial, retyped=step.retyped, rewired=step.rewired)) \ or worse(issues, trial_issues) if why: rejected.append({"fix_id": fix_id, "reason": why}) - notes.append(_note(f"{step.label}:没有采用,{why}", rule, match.node_id, "warning")) + notes.append(_note(f"{step.label}:未采用,{why}", rule, match.node_id, "warning")) continue current, spec, issues = trial, trial_spec, trial_issues applied.append(fix_id) @@ -674,6 +679,7 @@ def upgrade_for_evidence(graph: dict[str, Any] | GraphSpec, *, level: str = "pub notes += _r5_notes(spec) if created and level != "governed": notes.append(_note( - "报告撰写重写之后仍有没出处的数字时:探索运行照常产出、把问题标在报告里;正式运行里 on_violation 缺省是 fail,节点" - "会失败。想先标注着看,把 on_violation 设成 flag", created, None)) + f"报告撰写节点重写后仍有无出处的数字时:探索运行正常产出,并在报告中标注;正式运行中「{field_label('on_violation')}」" + f"默认为「{option_label('on_violation', 'fail')}」,节点会失败。如需先查看标注,请将「{field_label('on_violation')}」" + f"设为「{option_label('on_violation', 'flag')}」", created, None)) return {"graph": current, "changes": changes, "ops": ops, "notes": notes, "applied": applied, "rejected": rejected} diff --git a/backend/app/engine/variables.py b/backend/app/engine/variables.py index 92e1ce6c..f023f4d3 100644 --- a/backend/app/engine/variables.py +++ b/backend/app/engine/variables.py @@ -29,7 +29,7 @@ _TEMPLATE_RE = re.compile(r"\{\{(.*?)\}\}", re.DOTALL) _BUILTIN_ROOTS = { "input": "工作流的入口输入", "nodes": "各节点的输出", - "vars": "节点用 assign_to 写入的变量", + "vars": "节点通过「结果存为变量」写入的变量", "output": "已收集的成果", "loops": "循环的当前项和轮次", "usage": "token 与成本累计", @@ -364,7 +364,7 @@ def analyze(spec: GraphSpec) -> VariableReport: level="warning", node_id=node.id, path=path, field=field, message=f"{{{{ {path} }}}} 是「{target.produced_by_label}」" f"每轮的循环变量,只在循环体内部有值;" - f"这一步不在循环体里,取到的会是空值", + f"这一步不在循环体内,取到的将是空值", )) continue @@ -377,7 +377,7 @@ def analyze(spec: GraphSpec) -> VariableReport: report.issues.append(VarIssue( level="warning", node_id=node.id, path=path, field=field, message=f"{{{{ {path} }}}} 由「{target.produced_by_label}」产出," - f"但那一步在这之后才跑,这里取到的会是空值", + f"但那一步在这之后才执行,这里取到的将是空值", )) continue @@ -397,10 +397,10 @@ def analyze(spec: GraphSpec) -> VariableReport: node_id=node.id, path=path, field=field, message=( f"{{{{ {path} }}}} 没有任何节点产出," - f"是不是想写 {{{{ {hint} }}}}?取不到值会渲染成空字符串,不报错" + f"是否应为 {{{{ {hint} }}}}?无法取值时会渲染为空字符串,不会报错" if hint else f"{{{{ {path} }}}} 没有任何节点产出。" - f"取不到值会渲染成空字符串,不报错" + f"无法取值时会渲染为空字符串,不会报错" ), )) @@ -420,7 +420,7 @@ def analyze(spec: GraphSpec) -> VariableReport: if not var.refs and var.produced_by and not auto_provided: report.issues.append(VarIssue( level="info", node_id=var.produced_by, path=var.path, - message=f"{{{{ {var.path} }}}} 产出了但没有任何地方引用", + message=f"{{{{ {var.path} }}}} 已产出,但没有任何地方引用", )) report.variables = sorted( diff --git a/backend/app/memory/embeddings.py b/backend/app/memory/embeddings.py index 35988208..bc0655c5 100644 --- a/backend/app/memory/embeddings.py +++ b/backend/app/memory/embeddings.py @@ -124,9 +124,9 @@ def _make(kind: str, model: str, base_url: str = "", *, # 而实际拿到的是哈希词袋——搜不出同义表达时完全无从怀疑到这里 where = base_url or "api.openai.com" raise EmbedderUnavailable( - f"用不了 {where} 上的 embedding 模型 " + f"无法使用 {where} 上的向量模型 " f"{model or 'text-embedding-3-small'}:{_why(e)}。" - f"检查服务在不在、模型名对不对;走官方接口还要看 OPENAI_API_KEY。" + f"请检查服务是否可用、模型名是否正确;使用官方接口时还需检查 OPENAI_API_KEY。" ) from e return _local diff --git a/backend/app/memory/kb.py b/backend/app/memory/kb.py index 36855b18..a324d973 100644 --- a/backend/app/memory/kb.py +++ b/backend/app/memory/kb.py @@ -291,7 +291,7 @@ async def search( total_stale = await stale_count(session, collection) on_degrade( f"{collection or '全部集合'}里有 {total_stale} 条向量由" - f"「{'、'.join(names)}」建立,和当前的「{embedder_id()}」对不上," + f"「{'、'.join(names)}」建立,与当前的「{embedder_id()}」不一致," f"本次已退回纯关键词检索。重建索引后恢复。" ) alpha = 0.0 # 纯关键词 diff --git a/backend/app/memory/parsing.py b/backend/app/memory/parsing.py index 4fbbc9c8..bb05e3b7 100644 --- a/backend/app/memory/parsing.py +++ b/backend/app/memory/parsing.py @@ -55,7 +55,7 @@ def supported_formats() -> dict[str, list[str]]: def _why(e: BaseException) -> str: """解析库的原话,去掉类名。它们常常是英文,但比"读不开"多一点线索。""" text = str(e).strip() - return (text.splitlines()[0][:120] if text else "") or "没有更多说明" + return (text.splitlines()[0][:120] if text else "") or "无更多说明" def _ext(filename: str) -> str: @@ -68,14 +68,14 @@ def _from_pdf(raw: bytes) -> str: from pypdf import PdfReader except ImportError as e: raise UnsupportedDocument( - "要读 PDF 得先装解析库:pip install 'agentlab-backend[docs]'" + "解析 PDF 需要安装解析库:pip install 'agentlab-backend[docs]'" ) from e try: reader = PdfReader(io.BytesIO(raw)) except Exception as e: # noqa: BLE001 raise UnsupportedDocument( - f"这个 PDF 读不开:文件可能损坏、加了密码,或者其实不是 PDF({_why(e)})。" - "用原软件打开另存一份再传" + f"无法打开该 PDF:文件可能已损坏、设置了密码或并非 PDF({_why(e)})。" + "请用原软件另存后重新上传" ) from e # 按页拼,页与页之间留空行——切块是按段落切的,页边界正好是天然的段落边界 @@ -95,8 +95,8 @@ def _from_pdf(raw: bytes) -> str: text = "\n\n".join(cleaned) if not text.strip(): raise UnsupportedDocument( - "这个 PDF 里没有可提取的文字——多半是扫描件。" - "扫描件要先过 OCR,这里不做图像识别。" + "该 PDF 中没有可提取的文字,可能是扫描件。" + "扫描件需要先进行 OCR 识别,这里不做图像识别。" ) return text @@ -106,14 +106,14 @@ def _from_docx(raw: bytes) -> str: import docx except ImportError as e: raise UnsupportedDocument( - "要读 Word 得先装解析库:pip install 'agentlab-backend[docs]'" + "解析 Word 需要安装解析库:pip install 'agentlab-backend[docs]'" ) from e try: doc = docx.Document(io.BytesIO(raw)) except Exception as e: # noqa: BLE001 raise UnsupportedDocument( - f"这个 Word 文档读不开:文件可能损坏、加了密码,或者其实不是 Word({_why(e)})。" - "用原软件打开另存一份再传" + f"无法打开该 Word 文档:文件可能已损坏、设置了密码或并非 Word({_why(e)})。" + "请用原软件另存后重新上传" ) from e parts = [p.text.strip() for p in doc.paragraphs if p.text.strip()] @@ -126,7 +126,7 @@ def _from_docx(raw: bytes) -> str: parts.append(" | ".join(cells)) text = "\n\n".join(parts) if not text.strip(): - raise UnsupportedDocument("这个 Word 文档里没有文字内容") + raise UnsupportedDocument("该 Word 文档中没有文字内容") return text @@ -135,14 +135,14 @@ def _from_pptx(raw: bytes) -> str: from pptx import Presentation except ImportError as e: raise UnsupportedDocument( - "要读 PowerPoint 得先装解析库:pip install 'agentlab-backend[docs]'" + "解析 PowerPoint 需要安装解析库:pip install 'agentlab-backend[docs]'" ) from e try: deck = Presentation(io.BytesIO(raw)) except Exception as e: # noqa: BLE001 raise UnsupportedDocument( - f"这个 PowerPoint 读不开:文件可能损坏、加了密码,或者其实不是 PowerPoint({_why(e)})。" - "用原软件打开另存一份再传" + f"无法打开该 PowerPoint:文件可能已损坏、设置了密码或并非 PowerPoint({_why(e)})。" + "请用原软件另存后重新上传" ) from e slides: list[str] = [] @@ -168,8 +168,8 @@ def _from_pptx(raw: bytes) -> str: text = "\n\n".join(slides) if not text.strip(): raise UnsupportedDocument( - "这个 PowerPoint 里没有可提取的文字——多半整页都是图片。" - "图里的字要先过 OCR,这里不做图像识别。" + "该 PowerPoint 中没有可提取的文字,可能整页都是图片。" + "图片中的文字需要先进行 OCR 识别,这里不做图像识别。" ) return text @@ -198,21 +198,21 @@ def extract(raw: bytes, filename: str, mime: str = "") -> str: return _from_html(raw) if ext in _TABULAR: raise UnsupportedDocument( - f"「{filename}」是表格,知识库不收表格。请到「数据源」点「传表格」导入:" - "它会变成一张能用 SQL 查的表,数字是算出来的、查得到出自哪条查询。" - "放进知识库只能按文字检索,数字靠模型去读,容易读错,也追不到来源。" + f"「{filename}」是表格,知识库不接收表格。请到「数据」页的「表格」中点击「上传表格」导入:" + "导入后会成为可用 SQL 查询的表,数字由查询计算得出,可追溯到具体查询。" + "放进知识库只能按文字检索,数字要由模型读取,容易读错,也无法追溯来源。" ) if ext in _LEGACY_OFFICE: # 认出来再拒,而不是让它掉进下面那个"不是 UTF-8"的兜底—— # 后者对着一个 .ppt 说"不是文本",用户根本不知道该怎么办 raise UnsupportedDocument( - f"读不了 {filename}:{_LEGACY_OFFICE[ext]} 的老二进制格式({ext})需要" - f"外部转换器才能解析。请在 Office 里另存为 {ext}x 再传。" + f"无法读取 {filename}:{_LEGACY_OFFICE[ext]} 的旧版二进制格式({ext})需要" + f"外部转换器才能解析。请在 Office 中另存为 {ext}x 后重新上传。" ) try: return raw.decode("utf-8") except UnicodeDecodeError as e: raise UnsupportedDocument( - f"读不了 {filename or '这个文件'}:它不是 UTF-8 文本," - f"也不是认得出的 PDF / Word / PowerPoint / HTML。" + f"无法读取 {filename or '该文件'}:它不是 UTF-8 文本," + f"也不是可识别的 PDF / Word / PowerPoint / HTML。" ) from e diff --git a/backend/app/memory/rerank.py b/backend/app/memory/rerank.py index ea06252e..71a97658 100644 --- a/backend/app/memory/rerank.py +++ b/backend/app/memory/rerank.py @@ -42,22 +42,22 @@ def _parse_scores(text: str, n: int) -> list[float]: # 实测 deepseek-v4-pro:失败那次 out_tokens 正好等于 max_tokens, # 输出预算被耗光后正文什么都不剩。报"解析不出来"会把人引去查 JSON 格式, # 而该调的是 max_tokens——llm.py 里对同一个现象也是这么说的 - raise Unusable("模型没有输出正文,多半是输出 token 预算用完了。把节点上的最大输出 token 调大") + raise Unusable("模型没有输出正文,可能是输出 token 预算已用完。请调大节点的「最大输出 token」") match = re.search(r"\{[^{}]*\"scores\"\s*:\s*\[[^\]]*\][^{}]*\}", text, re.S) if not match: - raise Unusable(f"模型回复里找不到 scores:{text.strip()[:80]}") + raise Unusable(f"模型回复中找不到 scores:{text.strip()[:80]}") try: scores = json.loads(match.group(0)).get("scores") except json.JSONDecodeError as e: raise Unusable(f"scores 不是合法 JSON:{e}") from e if not isinstance(scores, list) or len(scores) != n: # 个数对不上就没法一一对应,硬凑只会把顺序搅乱 - raise Unusable(f"给了 {len(scores) if isinstance(scores, list) else '?'} 个分数," - f"候选有 {n} 个,对不上") + raise Unusable(f"模型给出 {len(scores) if isinstance(scores, list) else '?'} 个分数," + f"候选有 {n} 个,数量不一致") out: list[float] = [] for s in scores: if not isinstance(s, (int, float)): - raise Unusable(f"分数里混了非数字:{s!r}") + raise Unusable(f"分数中含有非数字:「{s}」") out.append(float(s)) return out @@ -92,13 +92,13 @@ async def rerank( scores = _parse_scores(str(text), len(hits)) except Unusable as e: if on_note: - on_note(f"重排没用上,按初筛顺序返回:{e}") + on_note(f"重排不可用,已按初筛顺序返回:{e}") return hits[:top_n] except Exception as e: # noqa: BLE001 if on_note: from app.core.errors import explain - on_note(f"重排失败,按初筛顺序返回:{explain(e)[0]}") + on_note(f"重排失败,已按初筛顺序返回:{explain(e)[0]}") return hits[:top_n] ranked = sorted(zip(hits, scores), key=lambda t: t[1], reverse=True) diff --git a/backend/app/memory/store.py b/backend/app/memory/store.py index 5d150666..44524cd3 100644 --- a/backend/app/memory/store.py +++ b/backend/app/memory/store.py @@ -116,7 +116,7 @@ async def recall( names = sorted({r.embed_model or "未知模型" for r in stale}) on_degrade( f"记忆域「{scope}」里有 {len(stale)}/{len(rows)} 条向量由" - f"「{'、'.join(names)}」建立,和当前的「{embedder_id()}」对不上," + f"「{'、'.join(names)}」建立,与当前的「{embedder_id()}」不一致," f"本次已退回纯关键词召回。重建索引后恢复。" ) vectors: list[Any] = [None] * len(rows) diff --git a/backend/app/providers/catalog.py b/backend/app/providers/catalog.py index bc418ca0..116850ab 100644 --- a/backend/app/providers/catalog.py +++ b/backend/app/providers/catalog.py @@ -99,16 +99,16 @@ COMPATIBLE_PRESETS: list[dict[str, Any]] = [ "base_url": "http://localhost:11434/v1", "api_key_optional": True, "models": [ - {"id": "qwen3:8b", "label": "Qwen3 8B (本地)", "context": 32_000, + {"id": "qwen3:8b", "label": "Qwen3 8B(本地)", "context": 32_000, "pricing": {"input": 0.0, "output": 0.0}}, - {"id": "llama3.2", "label": "Llama 3.2 (本地)", "context": 128_000, + {"id": "llama3.2", "label": "Llama 3.2(本地)", "context": 128_000, "pricing": {"input": 0.0, "output": 0.0}}, ], }, ] MOCK_MODELS: list[dict[str, Any]] = [ - {"id": "mock-fast", "label": "Mock(不花钱,用来试编排)", "context": 128_000, + {"id": "mock-fast", "label": "演示模型(无需 API Key)", "context": 128_000, "pricing": {"input": 0.0, "output": 0.0}}, ] @@ -116,14 +116,14 @@ PROVIDER_KINDS = [ { "kind": "anthropic", "label": "Anthropic", - "base_url_hint": "留空走官方;填了就是自定义网关(读 ANTHROPIC_BASE_URL)", + "base_url_hint": "留空使用官方地址;填写后使用自定义网关(默认读取 ANTHROPIC_BASE_URL)", "models": ANTHROPIC_MODELS, "default_model": "claude-opus-5", }, { "kind": "openai", "label": "OpenAI", - "base_url_hint": "留空走官方", + "base_url_hint": "留空使用官方地址", "models": OPENAI_MODELS, "default_model": "gpt-5.2", }, @@ -137,7 +137,7 @@ PROVIDER_KINDS = [ }, { "kind": "mock", - "label": "Mock(无需 API Key)", + "label": "演示模型(无需 API Key)", "base_url_hint": "", "models": MOCK_MODELS, "default_model": "mock-fast", diff --git a/backend/app/providers/factory.py b/backend/app/providers/factory.py index c3a3c168..6a7c3870 100644 --- a/backend/app/providers/factory.py +++ b/backend/app/providers/factory.py @@ -29,7 +29,15 @@ class ModelSpec(BaseModel): class ProviderNotConfigured(RuntimeError): - pass + """模型接入没配好。reason 说缺了什么,hint 说去哪里补;str(e) 是两句连起来的整句, + 运行失败原因直接用它。设置页的测试弹窗本来就在接入的编辑框里,只取 reason、另给自己的 hint。 + code 给调用方按类别分支:disabled / no_model / missing_key / missing_base_url。""" + + def __init__(self, reason: str, hint: str = "", code: str = "") -> None: + super().__init__(f"{reason}。{hint}" if hint else reason) + self.reason = reason + self.hint = hint + self.code = code async def list_providers(session: AsyncSession) -> list[Provider]: @@ -70,8 +78,8 @@ async def resolve_provider( or p.default_model == model ): raise ProviderNotConfigured( - f"模型 {model!r} 属于 provider {p.name!r},但它已被停用。" - f"请在设置里启用它,或给节点换一个模型。" + f"模型「{model}」所属的模型接入「{p.name}」已停用", + "请在「设置 → 模型接入」中启用它,或为节点换一个模型", code="disabled", ) # 认不出来的模型名就放行:用户可能手填了一个目录里还没有的新模型 @@ -102,7 +110,8 @@ def build_chat_model(provider: Provider, spec: ModelSpec) -> BaseChatModel: """ model = spec.model or provider.default_model or "" if not model: - raise ProviderNotConfigured(f"provider {provider.name!r} 没有可用的模型") + raise ProviderNotConfigured(f"模型接入「{provider.name}」没有可用的模型", + "请在「设置 → 模型接入」中添加可选模型,或设置默认模型", code="no_model") kwargs: dict[str, Any] = {"model": model} if spec.max_tokens: @@ -127,7 +136,8 @@ def build_chat_model(provider: Provider, spec: ModelSpec) -> BaseChatModel: base_url = base_url or os.environ.get("ANTHROPIC_BASE_URL") or None if not api_key: - raise ProviderNotConfigured(f"provider {provider.name!r} 缺少 API Key") + raise ProviderNotConfigured(f"模型接入「{provider.name}」缺少 API Key", + "请在「设置 → 模型接入」中填写", code="missing_key") bearer = extra.get("auth_style") == "bearer" kwargs["api_key"] = "placeholder-replaced-below" if bearer else api_key @@ -203,7 +213,8 @@ def build_chat_model(provider: Provider, spec: ModelSpec) -> BaseChatModel: # openai 与 openai 兼容走同一个类,区别只在 base_url if provider.kind == "openai_compatible" and not base_url: - raise ProviderNotConfigured(f"provider {provider.name!r} 需要填 base_url") + raise ProviderNotConfigured(f"模型接入「{provider.name}」需要填写 Base URL", + "请在「设置 → 模型接入」中填写", code="missing_base_url") # 很多本地服务(Ollama、vLLM)不校验 key,但 SDK 要求非空 kwargs["api_key"] = api_key or "not-needed" if base_url: diff --git a/backend/app/providers/mock_model.py b/backend/app/providers/mock_model.py index 442db7e8..bb924911 100644 --- a/backend/app/providers/mock_model.py +++ b/backend/app/providers/mock_model.py @@ -121,7 +121,7 @@ class MockChatModel(BaseChatModel): if not isinstance(args, dict): args = {} return AIMessage( - content=f"我需要先调用 `{tool['name']}` 来获取信息。", + content=f"需要先调用 `{tool['name']}` 获取信息。", tool_calls=[ {"name": tool["name"], "args": args, "id": f"call_{rng.randrange(1 << 30):08x}"} ], @@ -132,10 +132,10 @@ class MockChatModel(BaseChatModel): ) topic = re.sub(r"\s+", " ", last_user).strip()[:60] or "这个问题" body = ( - f"(Mock 回复)关于「{topic}」,我的结论分三点:\n\n" - f"1. 这是一个由 mock provider 生成的假响应,用来验证编排链路。\n" - f"2. 当前节点接收到 {len(messages)} 条消息,工具 {len(self.tools)} 个。\n" - f"3. 在设置页配一个真实 provider,把节点的模型换掉就能拿到真实结果。" + f"(演示模型的回复)关于「{topic}」,示例内容分三点:\n\n" + f"1. 这是演示模型生成的示例内容,用于验证工作流能否正常运行。\n" + f"2. 当前节点收到 {len(messages)} 条消息、{len(self.tools)} 个工具。\n" + f"3. 如需真实结果,请在「设置 → 模型接入」中添加模型接入,并为节点换用对应模型。" ) return AIMessage(content=body) diff --git a/backend/app/sandbox/base.py b/backend/app/sandbox/base.py index 92741271..6440874e 100644 --- a/backend/app/sandbox/base.py +++ b/backend/app/sandbox/base.py @@ -51,10 +51,10 @@ class ExecResult(BaseModel): def summary(self) -> str: if self.timed_out: - return f"执行超时(>{'?'}s)" + return "执行超时" if self.error: return self.error - return self.stdout or self.stderr or "(无输出)" + return self.stdout or self.stderr or "(无输出)" class Sandbox(abc.ABC): diff --git a/backend/app/sandbox/bubblewrap_sandbox.py b/backend/app/sandbox/bubblewrap_sandbox.py index c2341443..ad64e574 100644 --- a/backend/app/sandbox/bubblewrap_sandbox.py +++ b/backend/app/sandbox/bubblewrap_sandbox.py @@ -157,7 +157,7 @@ class BubblewrapSandbox(Sandbox): return ExecResult( ok=False, backend=self.name, timed_out=True, exit_code=124, duration_ms=int((time.perf_counter() - started) * 1000), - error=f"执行超过 {limits.timeout}s 被终止", + error=f"执行超过 {limits.timeout} 秒,已终止", ) except Exception as e: # noqa: BLE001 # 起进程和收输出在同一个 try 里。首行只说原因,类名和 errno 这些留给日志 diff --git a/backend/app/sandbox/interpreter.py b/backend/app/sandbox/interpreter.py index 60fcfa31..c0377925 100644 --- a/backend/app/sandbox/interpreter.py +++ b/backend/app/sandbox/interpreter.py @@ -99,8 +99,8 @@ def describe() -> dict[str, object]: "python": exe, "clean": clean, "note": ( - "解释器本身看不到后端依赖" + "解释器无法访问服务端的依赖包" if clean else - "没找到干净的解释器,改用 -S 关掉 site-packages(标准库仍可用,第三方包不可见)" + "未找到独立的解释器,已改用 -S 关闭 site-packages(标准库仍可用,第三方包不可见)" ), } diff --git a/backend/app/sandbox/local_sandbox.py b/backend/app/sandbox/local_sandbox.py index ea98f911..2215fa03 100644 --- a/backend/app/sandbox/local_sandbox.py +++ b/backend/app/sandbox/local_sandbox.py @@ -46,7 +46,7 @@ class LocalSandbox(Sandbox): "backend": self.name, "available": True, "isolated": False, - "warning": "裸子进程执行,无访问控制,不要跑不信任的代码", + "warning": "以本地子进程执行,无访问控制,请勿运行不可信的代码", "enforced": {"timeout": True, "cpu": True, "memory": not sys.platform == "darwin", "network": False, "fsize": True}, "root": str(self._root), @@ -103,7 +103,7 @@ class LocalSandbox(Sandbox): argv = [*cmd, entry] if shutil.which(argv[0]) is None and argv[0] != sys.executable: return ExecResult( - ok=False, backend=self.name, error=f"宿主机上找不到 {argv[0]}" + ok=False, backend=self.name, error=f"本机找不到 {argv[0]}" ) workdir = self._session_dir(session_id or f"tmp-{int(time.time()*1000)}") @@ -137,7 +137,7 @@ class LocalSandbox(Sandbox): except Exception as e: # noqa: BLE001 # 首行只说原因,类名和 errno 这些留给日志 logger.warning("%s 沙箱起进程失败:%s", self.name, raw(e)) - return ExecResult(ok=False, backend=self.name, error=f"没能启动进程:{describe_exception(e)}") + return ExecResult(ok=False, backend=self.name, error=f"无法启动进程:{describe_exception(e)}") try: out, err = await asyncio.wait_for(proc.communicate(), timeout=limits.timeout) @@ -153,7 +153,7 @@ class LocalSandbox(Sandbox): timed_out=True, exit_code=124, duration_ms=int((time.perf_counter() - started) * 1000), - error=f"执行超过 {limits.timeout}s 被终止", + error=f"执行超过 {limits.timeout} 秒,已终止", ) stdout, t1 = truncate(out.decode(errors="replace"), limits.max_output) diff --git a/backend/app/sandbox/manager.py b/backend/app/sandbox/manager.py index 268c28e9..4daf3c05 100644 --- a/backend/app/sandbox/manager.py +++ b/backend/app/sandbox/manager.py @@ -125,12 +125,12 @@ class SandboxManager: # auto 模式额外要求"开箱即用":microVM 镜像没拉过就先跳过 warm = getattr(impl, "image_ready", None) if warm is not None and not warm(): - self._resolved_from = f"{name} 可用但镜像未缓存,auto 先跳过" + self._resolved_from = f"{name} 可用但镜像未缓存,自动选择时暂不使用" continue self._resolved_from = f"自动选择 {name}({_why(name)})" return impl() - self._resolved_from = "没有可用的隔离后端,降级到本地子进程" + self._resolved_from = "没有可用的隔离方式,已降级为本地子进程" return LocalSandbox() async def run( diff --git a/backend/app/sandbox/microvm_sandbox.py b/backend/app/sandbox/microvm_sandbox.py index f66d71ef..5c48d483 100644 --- a/backend/app/sandbox/microvm_sandbox.py +++ b/backend/app/sandbox/microvm_sandbox.py @@ -141,15 +141,15 @@ class MicroVMSandbox(Sandbox): "network": "partial", }, "limits_note": ( - "内存/CPU/进程表由内核边界强制执行(超限进程被 OOM killer 杀掉,VM 存活)。" - "网络只能算部分生效:HTTP/HTTPS 与域名解析可断,但 UDP/53 拦不住," - "DNS 隧道外泄通道仍然开着。" + "内存、CPU、进程表由内核边界强制限制(超限进程会被 OOM killer 终止,VM 保持运行)。" + "网络隔离仅部分生效:可切断 HTTP/HTTPS 与域名解析,但无法拦截 UDP/53," + "存在经 DNS 隧道外泄数据的风险。" ), "image": self._image, "image_cached": cached, "live_vms": len(self._leases), - **({} if installed else {"error": "运行时未就绪(await microsandbox.install(),约 50MB)"}), - **({} if cached else {"first_run_cost": "镜像未缓存,首次启动需拉取(本机实测约 55s)"}), + **({} if installed else {"error": "运行时未就绪(await microsandbox.install(),约 50 MB)"}), + **({} if cached else {"first_run_cost": "镜像未缓存,首次启动需要拉取镜像(约 55 秒)"}), } # ---------------- 会话(长驻 VM)---------------- @@ -279,8 +279,8 @@ class MicroVMSandbox(Sandbox): return ExecResult( ok=False, backend=self.name, timed_out=True, duration_ms=int((time.perf_counter() - started) * 1000), - error=f"microVM 启动超过 {settings.microvm_boot_timeout}s" - + ("" if self.image_ready() else "(镜像未缓存,首次需拉取约 55s)"), + error=f"microVM 启动超过 {settings.microvm_boot_timeout} 秒" + + ("" if self.image_ready() else "(镜像未缓存,首次启动需要拉取镜像,约 55 秒)"), ) except Exception as e: # noqa: BLE001 logger.warning("microVM 启动失败:%s", raw(e)) @@ -299,7 +299,7 @@ class MicroVMSandbox(Sandbox): return ExecResult(ok=False, backend=self.name, error=f"非法文件路径:{rel}") data = content.encode() if len(data) > _MAX_FILE_BYTES: - return ExecResult(ok=False, backend=self.name, error=f"{rel} 超过 8MB 上限") + return ExecResult(ok=False, backend=self.name, error=f"{rel} 超过 8 MB 上限") target = f"{_WORKDIR}/{rel}" if "/" in rel: try: @@ -328,7 +328,7 @@ class MicroVMSandbox(Sandbox): ok=False, backend=self.name, timed_out=True, exit_code=124, duration_ms=int((time.perf_counter() - started) * 1000), session_reset=not killed, - error=f"执行超过 {limits.timeout}s 被终止" + error=f"执行超过 {limits.timeout} 秒,已终止" + ("" if killed else ";VM 已重置,该会话之前写的文件已丢失"), ) except Exception as e: # noqa: BLE001 @@ -336,7 +336,7 @@ class MicroVMSandbox(Sandbox): return ExecResult( ok=False, backend=self.name, duration_ms=int((time.perf_counter() - started) * 1000), - error=f"microVM 里的执行中断了:{describe_exception(e)}", + error=f"microVM 中的执行意外中断:{describe_exception(e)}", ) finally: if ephemeral: @@ -359,7 +359,7 @@ class MicroVMSandbox(Sandbox): error = None if exit_code < 0 and not stderr.strip(): error = (f"进程被内核终止(退出码 {exit_code})," - f"最常见的原因是超过了 {limits.memory_mb}MB 内存上限") + f"最常见的原因是超过了 {limits.memory_mb} MB 内存上限") written: list[str] = [] if not ephemeral: diff --git a/backend/app/sandbox/seatbelt_sandbox.py b/backend/app/sandbox/seatbelt_sandbox.py index 1c1de97b..3dcb1c26 100644 --- a/backend/app/sandbox/seatbelt_sandbox.py +++ b/backend/app/sandbox/seatbelt_sandbox.py @@ -246,7 +246,7 @@ class SeatbeltSandbox(Sandbox): timed_out=True, exit_code=124, duration_ms=int((time.perf_counter() - started) * 1000), - error=f"执行超过 {limits.timeout}s 被终止", + error=f"执行超过 {limits.timeout} 秒,已终止", ) stdout, t1 = truncate(out.decode(errors="replace"), limits.max_output) diff --git a/backend/app/seed.py b/backend/app/seed.py index 0583ed1a..6328a67d 100644 --- a/backend/app/seed.py +++ b/backend/app/seed.py @@ -38,7 +38,7 @@ def _e(source: str, target: str, handle: str | None = None) -> dict[str, Any]: TEMPLATES: list[dict[str, Any]] = [ { "name": "① 最小问答", - "description": "一个模型节点跑通全流程。先从这个开始改。", + "description": "用一个「模型调用」节点完成从输入到成果的完整流程,适合作为起点。", "tags": ["入门"], "nodes": [ _n("start", "input", "提问", fields=[{"name": "question", "required": True, @@ -51,8 +51,8 @@ TEMPLATES: list[dict[str, Any]] = [ }, { "name": "② 研究助手(Agent + 工具)", - "description": "Agent 自主决定搜什么、抓哪篇,再汇总成带出处的简报。", - "tags": ["agent", "工具"], + "description": "Agent 自主决定搜索和抓取哪些网页,再汇总成带出处的简报。", + "tags": ["Agent", "工具"], "nodes": [ _n("start", "input", "研究主题", fields=[{"name": "topic", "required": True}]), _n("research", "agent", "调研 Agent", @@ -73,15 +73,15 @@ TEMPLATES: list[dict[str, Any]] = [ }, { "name": "③ 带人工审批的发布流", - "description": "起草 → 人工把关 → 通过就发布、驳回就改写。演示中断与断点恢复。", + "description": "起草 → 人工审批 → 批准即发布、驳回则改写。演示运行中断与断点恢复。", "tags": ["人工审批", "分支"], "nodes": [ _n("start", "input", "主题", fields=[{"name": "topic", "required": True}]), _n("draft", "llm", "起草", system="你是品牌文案。", prompt="为「{{ input.topic }}」写一条 100 字以内的对外公告。", assign_to="draft"), - _n("review", "human", "人工把关", mode="approve", - title="这条公告可以发吗?", + _n("review", "human", "人工审批", mode="approve", + title="是否批准发布这条公告?", message="草稿:\n\n{{ vars.draft }}"), _n("publish", "transform", "标记发布", mode="template", template="✅ 已批准发布\n\n{{ vars.draft }}", assign_to="final"), @@ -100,14 +100,14 @@ TEMPLATES: list[dict[str, Any]] = [ }, { "name": "④ 知识库问答(RAG)", - "description": "先检索再回答,检索不到就明说。需要先在知识库页上传文档。", + "description": "先检索再回答,检索不到时明确告知。使用前请在知识库页上传文档。", "tags": ["RAG", "知识库"], "nodes": [ _n("start", "input", "提问", fields=[{"name": "question", "required": True}, {"name": "collection", "default": "default"}]), _n("search", "retrieve", "检索知识库", query="{{ input.question }}", collection="{{ input.collection }}", limit=5, alpha=0.5, assign_to="context"), - _n("gate", "branch", "检索到东西了吗", mode="expression", + _n("gate", "branch", "是否检索到内容", mode="expression", cases=[{"key": "hit", "condition": "nodes.search.count > 0", "label": "有命中"}]), _n("answer", "llm", "基于资料回答", system="只根据提供的资料回答,每句话后面用 [编号] 标注依据。资料不足就直接说不确定。", @@ -127,8 +127,8 @@ TEMPLATES: list[dict[str, Any]] = [ ], }, { - "name": "⑤ 写代码跑数据(沙箱 + 校验)", - "description": "模型写 Python,沙箱里真跑,输出还要过 JSON Schema 校验,不合格自动返工。", + "name": "⑤ 代码数据处理(沙箱 + 校验)", + "description": "模型编写 Python 代码并在沙箱中执行,输出经 JSON Schema 校验,不合格时自动重试。", "tags": ["沙箱", "结构化"], "nodes": [ _n("start", "input", "分析需求", fields=[ @@ -152,7 +152,7 @@ TEMPLATES: list[dict[str, Any]] = [ { "name": "⑥ 多 Agent 协作", "description": "调度者按进展分派任务给研究员、批评家和写手,直到目标达成。", - "tags": ["多agent"], + "tags": ["多 Agent"], "nodes": [ _n("start", "input", "目标", fields=[{"name": "goal", "required": True}]), _n("team", "supervisor", "协作团队", goal="{{ input.goal }}", max_rounds=6, @@ -175,8 +175,8 @@ TEMPLATES: list[dict[str, Any]] = [ }, { "name": "⑧ 周报(口径卡 + 三档出具)", - "description": "模板定骨架、agent 填关节的完整示范:取数固定、口径卡算数、" - "叙述只许引用清单里的数、出具时逐数回指——现编的数字会被点名并降档。", + "description": "用口径卡计算指标、按出具契约三档出具的示例:取数固定,报告只能引用指标清单中的数字," + "出具时逐一核对,无法核对的数字会被标出并降档出具。", "tags": ["出具", "口径卡", "周报"], "nodes": [ _n("start", "input", "周期", fields=[ @@ -230,12 +230,9 @@ TEMPLATES: list[dict[str, Any]] = [ }, { "name": "⑨ 可追溯周报", - "description": "报告里的每个数都点得开出处:tool 节点查库、口径卡登记指标、报告撰写节点只写引用" - "标记,数字由系统从口径卡取出来渲染,出口按引用逐段核对后三档出具。取数节点查的是示例数据源 " - "shop 的 orders 表(week、amount、refunded 三列):先接入你的库(或者上传一张表格、命名为 " - "shop),再把 SQL 换成你的口径。报告撰写节点按受管要求写明了 on_violation: fail 和 claims: " - "require_citation:探索运行里修不掉的数字违规也会让报告节点失败,而不只是标出来;正式运行里没挂引用" - "的结论句计入缺口、按档降级。", + "description": "报告中的每个数字都可追溯出处:「调用工具」节点查询数据,口径卡登记指标,报告撰写节点只写" + "引用标记,数字由系统填入,成果节点按引用逐段核对后三档出具。使用前请接入名为 shop 的数据源(含 orders " + "表的 week、amount、refunded 列),或上传同名表格,再按你的口径修改 SQL。报告撰写节点已按受管级别设置核对规则。", "tags": ["出具", "口径卡", "周报", "证据"], "nodes": [ _n("start", "input", "周期", fields=[ @@ -290,7 +287,7 @@ TEMPLATES: list[dict[str, Any]] = [ }, { "name": "⑦ 批量处理(循环)", - "description": "对列表逐项处理再汇总。演示 loop 节点的 body / done 两个出口怎么接。", + "description": "对列表逐项处理后汇总,演示「循环」节点「循环体」和「结束」两个出口的连法。", "tags": ["循环"], "nodes": [ _n("start", "input", "条目列表", fields=[ @@ -333,7 +330,7 @@ SKILLS: list[dict[str, Any]] = [ }, { "name": "批判性审阅", - "description": "挑毛病而不是夸奖", + "description": "只指出问题,不复述优点", "instructions": ( "审阅内容时:\n" "1. 只指出问题,不要复述优点\n" @@ -345,7 +342,7 @@ SKILLS: list[dict[str, Any]] = [ }, { "name": "中文写作", - "description": "干净、不翻译腔的中文", + "description": "简洁自然、避免翻译腔的中文", "instructions": ( "写中文时:\n" "1. 不用「进行」「作出」这类空动词,直接用实义动词\n" @@ -369,7 +366,7 @@ async def seed_defaults() -> None: if count == 0: session.add( Provider( - name="Mock(无需 Key)", + name="演示模型(无需 API Key)", kind="mock", models=catalog.MOCK_MODELS, default_model="mock-fast", diff --git a/backend/app/tools/builtin/data.py b/backend/app/tools/builtin/data.py index 1472fc70..bd670a73 100644 --- a/backend/app/tools/builtin/data.py +++ b/backend/app/tools/builtin/data.py @@ -39,7 +39,7 @@ class CurrentTimeArgs(BaseModel): @register( name="current_time", category="数据", - description="获取当前日期时间。模型不知道此刻是什么时候,需要时间信息时用这个。", + description="获取当前日期和时间。需要时间信息时使用。", args_schema=CurrentTimeArgs, ) async def current_time(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: @@ -66,7 +66,7 @@ class JsonQueryArgs(BaseModel): @register( name="json_query", category="数据", - description="从 JSON 里按路径取值,避免让模型自己在长 JSON 里数括号。", + description="按路径从 JSON 中取值,适合处理较长的 JSON。", args_schema=JsonQueryArgs, ) async def json_query(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: diff --git a/backend/app/tools/builtin/files.py b/backend/app/tools/builtin/files.py index aec0d529..0a7ab4f0 100644 --- a/backend/app/tools/builtin/files.py +++ b/backend/app/tools/builtin/files.py @@ -45,7 +45,7 @@ async def file_read(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: if not target.exists(): return {"error": f"文件不存在:{args.path}"} if target.is_dir(): - return {"error": f"{args.path} 是目录,用 file_list"} + return {"error": f"{args.path} 是目录,请使用 file_list"} data = target.read_bytes()[:_MAX_READ] return { "path": args.path, diff --git a/backend/app/tools/builtin/web.py b/backend/app/tools/builtin/web.py index 6f9d4aec..3f37e897 100644 --- a/backend/app/tools/builtin/web.py +++ b/backend/app/tools/builtin/web.py @@ -161,7 +161,7 @@ async def _duckduckgo(query: str, n: int) -> list[dict[str, str]]: @register( name="web_search", category="网络", - description="搜索互联网。配了 TAVILY_API_KEY 就走 Tavily,否则退回 DuckDuckGo。", + description="搜索互联网。已配置 TAVILY_API_KEY 时使用 Tavily,否则使用 DuckDuckGo。", args_schema=WebSearchArgs, ) async def web_search(ctx: ToolContext, **kwargs: Any) -> dict[str, Any]: diff --git a/backend/app/tools/custom.py b/backend/app/tools/custom.py index 997f7f33..5245cc56 100644 --- a/backend/app/tools/custom.py +++ b/backend/app/tools/custom.py @@ -66,38 +66,38 @@ def schema_problem(schema: Any) -> str | None: 字符串——前者会被说成「后端内部出错了」,后者试跑通过、到了模型那边类型不对。 """ if not isinstance(schema, dict): - return "参数定义要是一个 JSON 对象" + return "参数定义必须是一个 JSON 对象" props = schema.get("properties") if props is not None and not isinstance(props, dict): - return '参数定义格式不对:properties 要是一个对象,每个参数一项,比如 {"n": {"type": "integer"}}' + return '参数定义格式有误:properties 必须是一个对象,每个参数一项,例如 {"n": {"type": "integer"}}' for key, spec in (props or {}).items(): if not str(key).strip(): - return "参数定义格式不对:有一个参数名是空的,给它起个名字" + return "参数定义格式有误:存在空的参数名,请为其命名" if str(key).startswith("_"): - return (f"参数定义格式不对:参数名 {key} 不能以下划线开头," - f"换成 {str(key).lstrip('_') or 'value'} 这样的名字") + return (f"参数定义格式有误:参数名 {key} 不能以下划线开头," + f"请改为 {str(key).lstrip('_') or 'value'} 这样的名称") if str(key).startswith("model_") and hasattr(BaseModel, str(key)): - return f"参数定义格式不对:参数名 {key} 和内部保留的名字冲突,换一个名字" + return f"参数定义格式有误:参数名 {key} 与内部保留的名称冲突,请换一个名称" if not isinstance(spec, dict): # 示例照着他写的那个类型给,照抄就能改好:写了 "string" 却让人改成 integer 只会添乱 shown = json.dumps(spec, ensure_ascii=False) meant = _type_guess(spec) or "string" - return (f'参数定义格式不对:参数 {key} 要写成 {{"type": "{meant}"}} 这样的对象,' + return (f'参数定义格式有误:参数 {key} 应写成 {{"type": "{meant}"}} 这样的对象,' f"不能直接写 {shown}") kind = spec.get("type", "string") if not isinstance(kind, str) or kind not in _TYPES: shown = kind if isinstance(kind, str) else json.dumps(kind, ensure_ascii=False) meant = _type_guess(kind) - guess = f",是不是想写 {meant}" if meant else "" - return (f"参数定义格式不对:参数 {key} 的类型「{shown}」认不出来{guess};" - f"只能是 {'、'.join(_TYPES)} 里的一个") + guess = f",是否应为 {meant}" if meant else "" + return (f"参数定义格式有误:无法识别参数 {key} 的类型「{shown}」{guess};" + f"只能是 {'、'.join(_TYPES)} 中的一个") if not isinstance(spec.get("description", ""), str): - return f"参数定义格式不对:参数 {key} 的 description 要是一段文字" + return f"参数定义格式有误:参数 {key} 的 description 必须是文字" required = schema.get("required") if required is not None and ( not isinstance(required, list) or not all(isinstance(k, str) for k in required) ): - return '参数定义格式不对:required 要是参数名的列表,比如 ["n"]' + return '参数定义格式有误:required 必须是参数名的列表,例如 ["n"]' # 上面没认出来的写法,最后按运行时同一个转换真建一次:放行的一定建得出来 import warnings @@ -106,13 +106,13 @@ def schema_problem(schema: Any) -> str | None: warnings.simplefilter("ignore") # 和 BaseModel 同名的参数(json、copy)只是警告,照样能用 schema_to_model("probe", schema) except Exception: # noqa: BLE001 - return "参数定义格式不对:按它建不出工具的参数表,检查参数名和每个参数的 type" + return "参数定义格式有误:无法据此生成工具的参数表,请检查参数名和每个参数的 type" return None def broken_tool_message(name: str, problem: str) -> str: """库里存着的坏工具被节点绑上时的报错:哪个工具、坏在哪、去哪里改。""" - return f"自定义工具「{name}」的{problem}。到「工具」页把它的参数定义改好再运行" + return f"自定义工具「{name}」的{problem}。到「工具」页修改参数定义后再运行" class ToolFailure(dict): diff --git a/backend/app/tools/mcp_manager.py b/backend/app/tools/mcp_manager.py index b607ae3a..9daaa37d 100644 --- a/backend/app/tools/mcp_manager.py +++ b/backend/app/tools/mcp_manager.py @@ -198,9 +198,9 @@ def _reason(e: BaseException, command: str | None = None) -> str: if isinstance(e, FileNotFoundError): # stdio 客户端抛的这个异常常常不带文件名,只剩「找不到命令 」半句:补上配置的命令 missing = e.filename or command or "" - return f"启动不了:找不到命令 {missing}。确认它已安装、并且在后端的 PATH 里" + return f"无法启动:找不到命令 {missing}。请确认已安装,且位于服务端的 PATH 中" if isinstance(e, asyncio.TimeoutError): - return "连上了但 30 秒内没有应答:确认这个命令启动的是 MCP 服务,参数有没有写错" + return "已连接,但 30 秒内没有响应:请确认该命令启动的是 MCP 服务,并检查参数" reason, hint = explain(e) return f"{reason}。{hint}" if hint else reason diff --git a/backend/app/tools/net.py b/backend/app/tools/net.py index f4bb729e..c32bf035 100644 --- a/backend/app/tools/net.py +++ b/backend/app/tools/net.py @@ -91,8 +91,8 @@ async def _real_ips(host: str) -> tuple[str, ...]: if nxdomain: break if nxdomain: - raise UnsafeUrlError(f"{host} 在公共 DNS 里查不到(本机只解析到代理的 fake-ip 假地址),已拦截") - raise UnsafeUrlError(f"{host} 解析到代理的 fake-ip 假地址,而且没能向公共 DNS 核实真实地址,已拦截") + raise UnsafeUrlError(f"{host} 在公共 DNS 中无法解析(本机只解析到代理分配的虚拟地址),已拦截") + raise UnsafeUrlError(f"{host} 解析到代理分配的虚拟地址,且未能向公共 DNS 核实真实地址,已拦截") async def assert_safe_url(url: str) -> str: @@ -108,17 +108,17 @@ async def assert_safe_url(url: str) -> str: """ parsed = urlparse(url) if parsed.scheme not in ("http", "https"): - raise UnsafeUrlError(f"只支持 http/https,收到 {parsed.scheme!r}") + raise UnsafeUrlError(f"只支持 http/https,当前为「{parsed.scheme}」") host = parsed.hostname if not host: - raise UnsafeUrlError("URL 里没有主机名") + raise UnsafeUrlError("URL 中没有主机名") if parsed.port in _BLOCKED_PORTS: raise UnsafeUrlError(f"端口 {parsed.port} 不允许访问") allowlist = settings.http_tool_allowlist if allowlist: if not any(host == d or host.endswith("." + d) for d in allowlist): - raise UnsafeUrlError(f"{host} 不在白名单里(AGENTLAB_HTTP_TOOL_ALLOWLIST)") + raise UnsafeUrlError(f"{host} 不在允许访问的域名列表中(AGENTLAB_HTTP_TOOL_ALLOWLIST)") # 逐个解析结果都要查:一个域名可能同时解析到公网和内网地址 try: @@ -142,9 +142,9 @@ async def assert_safe_url(url: str) -> str: if _is_private(ip): hint = "" if not fake and _in(ip, [_COMMON_FAKE_IP]): - hint = ("。198.18.x.x 通常是本机代理 fake-ip 模式给的假地址:可以设置 " - "AGENTLAB_HTTP_TOOL_FAKE_IP_RANGES=198.18.0.0/15 让它向公共 DNS 核实真实地址," - "或者把代理的 DNS 改成 redir-host、把这个域名加进 fake-ip-filter") + hint = ("。198.18.x.x 通常是本机代理 fake-ip 模式分配的虚拟地址:可设置 " + "AGENTLAB_HTTP_TOOL_FAKE_IP_RANGES=198.18.0.0/15,改为向公共 DNS 核实真实地址;" + "或将代理的 DNS 改为 redir-host,并把该域名加入 fake-ip-filter") raise UnsafeUrlError(f"{host} 解析到内网地址 {ip},已拦截{hint}") if needs_check: diff --git a/backend/app/tools/registry.py b/backend/app/tools/registry.py index d4cd7a99..5f8db0f0 100644 --- a/backend/app/tools/registry.py +++ b/backend/app/tools/registry.py @@ -220,7 +220,7 @@ def describe_args( 字段说明取 Field(description=...),各工具定义里本来就写了,这里只是搬到报错里 ——模型拿到这句话就能在下一步自己改对,不用人工介入。 - 返回的永远是一句完整的话("参数不对:…。它接受:…"),调用方直接拼在 + 返回的永远是一句完整的话("参数有误:…。可用参数:…"),调用方直接拼在 工具名后面即可,不用猜这次会不会缺个主语。 """ js = schema.model_json_schema() @@ -232,14 +232,14 @@ def describe_args( tag = "必填" if key in required else "可选" desc = str(prop.get("description") or "").strip() fields.append(f"{key}({tag},{_type_label(prop)})" + (f" — {desc}" if desc else "")) - tail = "它接受:" + ";".join(fields) if fields else "它不接受任何参数。" + tail = "可用参数:" + ";".join(fields) if fields else "该工具不接受任何参数。" got = dict(got or {}) unknown = [k for k in got if k not in props] missing = [k for k in required if k not in got] problems: list[str] = [] if unknown: - problems.append(f"{'、'.join(unknown)} 不是它的参数") + problems.append(f"{'、'.join(unknown)} 不是该工具的参数") if missing: problems.append(f"缺少必填参数 {'、'.join(missing)}") for err in error.errors() if error else (): @@ -253,7 +253,7 @@ def describe_args( else f"{loc} 的值不合法({err.get('msg', '')})" ) - head = "参数不对:" + ";".join(problems) + "。" if problems else "参数不对。" + head = "参数有误:" + ";".join(problems) + "。" if problems else "参数有误。" return f"{head}{tail}" @@ -331,7 +331,7 @@ async def call_tool( tools = await build_tools([name], ctx, session=session) if not tools: - raise KeyError(f"找不到工具 {name!r}") + raise KeyError(f"找不到工具 {name}") tool = tools[0] model = args_model_of(tool) diff --git a/backend/app/tools/trust.py b/backend/app/tools/trust.py index 8372282b..f4223a6f 100644 --- a/backend/app/tools/trust.py +++ b/backend/app/tools/trust.py @@ -92,7 +92,7 @@ async def set_trust(session: AsyncSession, key: str, level: str) -> None: from app.db.models import Setting if level not in TRUST_LEVELS: - raise ValueError(f"信任档位只能是 {'、'.join(TRUST_LEVELS)},收到的是 {level!r}") + raise ValueError(f"信任档位只能是 {'、'.join(TRUST_LEVELS)},当前为「{level}」") row = await session.get(Setting, SETTING_KEY) tools = dict(((row.value if row else None) or {}).get("tools") or {}) if level == "ask": @@ -165,7 +165,7 @@ def parse_verdict(text: str) -> tuple[bool, str] | None: if not isinstance(data, dict) or data.get("verdict") not in ("allow", "escalate"): return None reason = str(data.get("reason") or "").strip()[:300] - return data["verdict"] == "allow", reason or "(门控没写理由)" + return data["verdict"] == "allow", reason or "(门控未说明理由)" async def ask_gate(*, tool: BaseTool, args: dict[str, Any], node_title: str, task: str) -> GateVerdict: @@ -197,9 +197,9 @@ async def ask_gate(*, tool: BaseTool, args: dict[str, Any], node_title: str, tas HumanMessage(content=gate_prompt(tool=tool, args=args, node_title=node_title, task=task)), ]), timeout=GATE_TIMEOUT_S) except asyncio.TimeoutError: - return done(False, f"门控模型没答上来:{GATE_TIMEOUT_S} 秒内没有回复") + return done(False, f"门控模型未给出判断:{GATE_TIMEOUT_S} 秒内没有回复") except Exception as e: # noqa: BLE001 - 门控出任何错都不能变成放行 - return done(False, f"门控模型没答上来:{describe_exception(e)}") + return done(False, f"门控模型未给出判断:{describe_exception(e)}") from app.providers import catalog @@ -210,7 +210,7 @@ async def ask_gate(*, tool: BaseTool, args: dict[str, Any], node_title: str, tas content = reply.content if isinstance(reply.content, str) else json.dumps(reply.content, ensure_ascii=False) parsed = parse_verdict(content) if parsed is None: - return done(False, "门控模型没答上来:回复不是约定的 JSON 格式") + return done(False, "门控模型未给出判断:回复不是约定的 JSON 格式") return done(*parsed) diff --git a/backend/tests/test_agent_cited_fields.py b/backend/tests/test_agent_cited_fields.py index e22cfb41..a27cd0b5 100644 --- a/backend/tests/test_agent_cited_fields.py +++ b/backend/tests/test_agent_cited_fields.py @@ -195,7 +195,7 @@ async def test_fields_are_checked_against_the_snapshot(monkeypatch): evts = await events(row.id) [mismatch] = logs(evts, "agent_field_mismatch") assert mismatch["level"] == "warn" and mismatch["fields"] == ["orders"] - assert "模型报 30" in mismatch["message"] and "快照是 3" in mismatch["message"] + assert "模型给出 30" in mismatch["message"] and "快照为 3" in mismatch["message"] [unverified] = logs(evts, "agent_field_unverified") assert unverified["level"] == "warn" and unverified["fields"] == ["region"] diff --git a/backend/tests/test_agent_guards.py b/backend/tests/test_agent_guards.py index 07048ed9..7a04f69e 100644 --- a/backend/tests/test_agent_guards.py +++ b/backend/tests/test_agent_guards.py @@ -305,7 +305,7 @@ async def test_reminder_before_the_budget_runs_out(lookup, monkeypatch): seen = script(monkeypatch, lambda i, _: f"店{i}" if i < 5 else None, usage=per_call(1000)) row, _ = await run(graph(budget_tokens=5000)) notes = [m.content for call in seen for m in call if isinstance(m, HumanMessage) and "系统提醒" in m.content] - assert notes and "令牌预算已用 80%" in notes[0] + assert notes and "token 预算已用 80%" in notes[0] assert len(set(notes)) == 1, "同一种提醒只该说一次" @@ -361,7 +361,7 @@ async def test_validation_failure_names_the_agent_that_was_cut_short(lookup, mon g["edges"][1] = {"source": "work", "target": "check"} row, _ = await run(g) assert row.status == "failed" - assert "上游「查数」用满了步数" in (row.error or ""), row.error + assert "上游「查数」因步数用完" in (row.error or ""), row.error async def test_runs_from_before_the_upgrade_keep_the_old_rules(lookup, monkeypatch): @@ -377,7 +377,7 @@ async def test_runs_from_before_the_upgrade_keep_the_old_rules(lookup, monkeypat assert row.status == "succeeded", row.error assert len(calls) == 12 [settled] = logs(events, "step_limit_settled") - assert "reason" not in settled and "用满了 12 步" in settled["message"] + assert "reason" not in settled and "已用完 12 步" in settled["message"] assert not logs(events, "tool_repeat") diff --git a/backend/tests/test_agent_steps.py b/backend/tests/test_agent_steps.py index da832eb2..690fb628 100644 --- a/backend/tests/test_agent_steps.py +++ b/backend/tests/test_agent_steps.py @@ -175,7 +175,7 @@ async def test_a_failed_settle_round_falls_back_and_keeps_what_was_found( assert "step_limit" in codes(events) assert "step_limit_settled" not in codes(events) # 已有成果还在,末尾挂着说明 - assert MIDWAY in text and "用满了" in text, text + assert MIDWAY in text and "已用完" in text, text def test_max_steps_is_clamped_by_the_hard_cap() -> None: diff --git a/backend/tests/test_api_messages.py b/backend/tests/test_api_messages.py index b2295684..e0fccec9 100644 --- a/backend/tests/test_api_messages.py +++ b/backend/tests/test_api_messages.py @@ -41,11 +41,11 @@ def test_common_failures_are_put_in_plain_words(): from app.core.errors import explain, graph_error, raw reason, hint = explain(httpx.ConnectError("[Errno 61] Connection refused")) - assert "连不上" in reason and hint + assert "无法连接服务" in reason and hint req = httpx.Request("GET", "https://x/v1/models") denied = httpx.HTTPStatusError("401", request=req, response=httpx.Response(401, request=req)) - assert "密钥" in explain(denied)[0] + assert "API Key" in explain(denied)[0] reason, hint = explain(TypeError("_run() got an unexpected keyword argument 'query'")) _clean(reason) @@ -61,6 +61,29 @@ def test_common_failures_are_put_in_plain_words(): assert "第 1 个节点" in text and "nope" in text +def test_errors_carry_a_category_for_scene_specific_hints(): + """要按场景换说法的调用方(测数据库连接)按类别判断,不比较 explain 的文字。""" + import asyncio + + import httpx + + from app.core import errors + + req = httpx.Request("GET", "https://x/v1/models") + cases = [ + (httpx.ConnectError("[Errno 61] Connection refused"), errors.NETWORK), + (ConnectionRefusedError(61, "Connection refused"), errors.NETWORK), + (asyncio.TimeoutError(), errors.TIMEOUT), + (httpx.HTTPStatusError("401", request=req, response=httpx.Response(401, request=req)), errors.AUTH), + (httpx.HTTPStatusError("429", request=req, response=httpx.Response(429, request=req)), errors.RATE_LIMIT), + (httpx.HTTPStatusError("502", request=req, response=httpx.Response(502, request=req)), errors.SERVER), + (TypeError("x() got an unexpected keyword argument 'q'"), errors.BUG), + (RuntimeError("upstream closed"), None), + ] + for exc, want in cases: + assert errors.classify(exc) == want, (exc, errors.classify(exc)) + + # -------------------------------------------------------------------------- # 各接口 # -------------------------------------------------------------------------- @@ -79,7 +102,7 @@ async def test_a_failing_provider_test_explains_itself(client, monkeypatch): body = (await client.post("/api/providers/test", json={"kind": "mock", "default_model": "m"})).json() assert body["ok"] is False _clean(body["error"]) - assert "连不上" in body["error"] and body["hint"] + assert "无法连接服务" in body["error"] and body["hint"] assert "ConnectError" in body["detail"], "技术细节里要留着原始异常" @@ -129,7 +152,7 @@ async def test_graph_validation_points_at_the_node(client): json={"graph": {"nodes": [{"id": "a", "type": "nope"}]}})).json() message = body["issues"][0]["message"] _clean(message) - assert "第 1 个节点的类型「nope」不认识" in message + assert "第 1 个节点的类型「nope」无法识别" in message async def test_publish_level_uses_ui_words(client): @@ -235,7 +258,7 @@ async def test_an_unconfigured_copilot_model_uses_settings_words(client, monkeyp async def test_a_missing_item_says_it_may_have_been_deleted(client): """404 多半是别的标签页里删掉了,或者链接过期了。只说「不存在」,人会以为 - 是自己输错了什么;统一说一句「可能已经被删了」,下一步就清楚了。""" + 是自己输错了什么;统一说一句「可能已被删除」,下一步就清楚了。""" gone = "no-such-id" calls = [ ("get", f"/api/workflows/{gone}", None), @@ -261,5 +284,65 @@ async def test_a_missing_item_says_it_may_have_been_deleted(client): r = await client.request(method.upper(), url, **kwargs) assert r.status_code == 404, (method, url, r.status_code, r.text) detail = r.json()["detail"] - assert "可能已经被删了" in detail, (method, url, detail) + assert "可能已被删除" in detail, (method, url, detail) assert gone not in detail, f"把 id 原样念给用户听没用:{detail}" + + +async def test_an_unconfigured_provider_on_the_run_path_uses_settings_words(monkeypatch): + """运行路径上的「缺少 API Key」「接入已停用」和助手、设置页一样经过统一的翻译:写「模型接入」、 + 写去「设置 → 模型接入」哪里补,不露 provider、base_url 和英文单引号。以前运行失败原因里原样是 + 「provider 'x' 缺少 API Key」。""" + import asyncio + + from app.core.crypto import encrypt + from app.db.base import SessionLocal + from app.db.models import Provider, Run + from app.engine.runner import run_manager + + for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"): + monkeypatch.delenv(name, raising=False) + + def graph(model: str) -> dict: + nodes = [ + {"id": "start", "type": "input", "data": {"config": {"fields": [{"name": "q"}]}}}, + {"id": "ask", "type": "llm", "data": {"label": "提问", "config": {"model": model, "prompt": "hi"}}}, + {"id": "out", "type": "output", "data": {"config": {"fields": [{"name": "结果", "value": "{{ last_message }}"}]}}}, + ] + return {"nodes": nodes, "edges": [{"source": "start", "target": "ask"}, {"source": "ask", "target": "out"}]} + + async def error_of(model: str) -> str: + run = await run_manager.start(graph=graph(model), input_payload={"q": "x"}) + for _ in range(400): + async with SessionLocal() as session: + row = await session.get(Run, run.id) + if row and row.status in ("failed", "succeeded", "cancelled"): + assert row.status == "failed", row.status + return row.error or "" + await asyncio.sleep(0.05) + raise AssertionError("运行没有按时结束") + + async with SessionLocal() as session: + keyless = Provider(name="无钥接入", kind="anthropic", api_key=None, models=[{"id": "claude-nokey"}], + default_model="claude-nokey", enabled=True, extra={}) + disabled = Provider(name="停用接入", kind="openai", api_key=encrypt("k"), models=[{"id": "gpt-off"}], + default_model="gpt-off", enabled=False, extra={}) + session.add_all([keyless, disabled]) + await session.commit() + ids = [keyless.id, disabled.id] + await run_manager.setup() + try: + error = await error_of("claude-nokey") + assert "模型接入「无钥接入」缺少 API Key" in error and "「设置 → 模型接入」" in error, error + error = await error_of("gpt-off") + assert "模型「gpt-off」所属的模型接入「停用接入」已停用" in error, error + assert "「设置 → 模型接入」中启用" in error, error + for text in (error,): + assert "provider" not in text and "'" not in text, text + finally: + await run_manager.shutdown() + async with SessionLocal() as session: + for pid in ids: + row = await session.get(Provider, pid) + if row is not None: + await session.delete(row) + await session.commit() diff --git a/backend/tests/test_approval.py b/backend/tests/test_approval.py index f018703d..f3d005a6 100644 --- a/backend/tests/test_approval.py +++ b/backend/tests/test_approval.py @@ -140,7 +140,7 @@ async def test_tool_node_takes_a_refusal_as_a_refusal(): await run_manager.resume(run_id, "拒绝") run = await _wait(run_id, ("failed", "succeeded")) - assert run.status == "failed" and "拒绝" in (run.error or "") + assert run.status == "failed" and "驳回" in (run.error or "") assert not [e for e in await _events(run_id) if e.type == "tool.start"], "被拒绝的工具执行了" diff --git a/backend/tests/test_autofix_assist.py b/backend/tests/test_autofix_assist.py index 9708eb1d..4f57c9a6 100644 --- a/backend/tests/test_autofix_assist.py +++ b/backend/tests/test_autofix_assist.py @@ -115,7 +115,7 @@ async def test_a_sound_fix_is_adopted_as_a_preview(client, monkeypatch): assert await rows(wf) == before # 只是预览 # 交给模型的请求里有剩下的问题和不许降低要求、不许替人选的约定 human = next(text for role, text in model.calls[0] if role == "human") - assert "受管模板至少要有一个「成果 / 出具」节点声明出具契约" in human + assert "受管级别要求至少一个「成果」节点声明出具契约" in human assert "不许降低要求" in human and "不替人选" in human and "question" in human @@ -141,7 +141,7 @@ async def test_a_fix_that_makes_errors_grow_is_refused(client, monkeypatch): out = await assist(client, wf) assert out["assist"]["ok"] is False [rejected] = [r for r in out["rejected"] if r["fix_id"] == "assist"] - assert "新的问题" in rejected["reason"] and "expression" in rejected["reason"] + assert "新的问题" in rejected["reason"] and "表达式" in rejected["reason"] assert out["graph"] == two_exits() @@ -182,7 +182,7 @@ async def test_deterministic_fixes_run_first_and_copilot_sees_what_is_left(clien out = await assist(client, wf, apply=["governed.agent_approval_never:ask"]) assert out["applied"] == ["governed.agent_approval_never:ask", "assist"] and out["ok"] is True human = next(text for role, text in model.calls[0] if role == "human") - assert "的审批策略是「全部自动放行」" not in human and '"approval": "dangerous"' in human + assert "的审批策略是「全部无需审批」" not in human and '"approval": "dangerous"' in human async def test_nothing_left_means_no_model_call(client, monkeypatch): diff --git a/backend/tests/test_autofix_governance.py b/backend/tests/test_autofix_governance.py index a6ff682d..83f4c0f7 100644 --- a/backend/tests/test_autofix_governance.py +++ b/backend/tests/test_autofix_governance.py @@ -166,7 +166,7 @@ def test_a_missing_schema_is_not_invented(): graph = feeding_agent() fid = "governed.caliber_agent_schema:ask" fix = plan(graph)[fid] - assert fix["kind"] == "assist" and "output_schema" in fix["label"] + assert fix["kind"] == "assist" and "「结构化输出 Schema」" in fix["label"] out = apply_fixes(graph, [fid], level="governed") assert out["applied"] == [] and out["rejected"][0]["fix_id"] == fid assert "output_schema" not in config(out["graph"], "ask") and out["graph"] == graph @@ -225,7 +225,7 @@ def test_copilot_may_not_mark_a_code_node_as_source_on_its_own(): after = copy.deepcopy(before) config(after, "calc")["evidence_role"] = "source" [reason] = forbidden_changes(before, after) - assert "「计算」" in reason and "source" in reason + assert "「计算」" in reason and "「取数」" in reason # 新加的沙箱代码直接标成取数也一样 after = copy.deepcopy(before) after["nodes"].append(node("raw", "code", "取原始数据", code="print(2)", evidence_role="source")) @@ -378,8 +378,10 @@ def test_loosening_the_report_policy_is_refused(key, before, after): config(new, "write").pop(key) else: config(new, "write")[key] = after + from app.engine.labels import field_label + [reason] = forbidden_changes(old, new) - assert "「报告撰写」" in reason and key in reason + assert "「报告撰写」" in reason and f"「{field_label(key)}」" in reason def test_turning_cite_fields_off_is_refused(): @@ -387,7 +389,7 @@ def test_turning_cite_fields_off_is_refused(): new = copy.deepcopy(old) config(new, "ask")["cite_fields"] = False [reason] = forbidden_changes(old, new) - assert "「查数员」" in reason and "cite_fields" in reason + assert "「查数员」" in reason and "「按出处核对字段」" in reason def test_tightening_is_not_refused(): @@ -479,9 +481,9 @@ async def test_choosing_copilot_in_the_choice_runs_the_assist(client, monkeypatc @pytest.mark.parametrize("ops, word", [ - ([{"op": "update_node", "id": "calc", "config": {"evidence_role": "source"}}], "evidence_role"), + ([{"op": "update_node", "id": "calc", "config": {"evidence_role": "source"}}], "「证据角色」"), ([{"op": "update_node", "id": "write", "config": {"numbers": "off"}}, - {"op": "update_node", "id": "calc", "config": {"evidence_role": "source"}}], "numbers"), + {"op": "update_node", "id": "calc", "config": {"evidence_role": "source"}}], "「未引用的数字」"), ]) async def test_copilot_cannot_decide_for_the_author_or_loosen_the_report(client, monkeypatch, ops, word): script(monkeypatch, ops) diff --git a/backend/tests/test_autofix_graph_defaults.py b/backend/tests/test_autofix_graph_defaults.py index ad2863ee..d9265c2c 100644 --- a/backend/tests/test_autofix_graph_defaults.py +++ b/backend/tests/test_autofix_graph_defaults.py @@ -75,7 +75,7 @@ def test_an_agent_following_a_never_default_is_blocked_on_the_governed_level(): assert len(found) == 1 issue = found[0] assert issue.level == "error" and issue.node_id == "ask" and issue.field == "approval" - assert "跟随全图默认" in issue.message and "全部自动放行" in issue.message and "「查数员」" in issue.message + assert "跟随工作流默认设置" in issue.message and "全部无需审批" in issue.message and "「查数员」" in issue.message # 已发布档照旧只给警告 assert [i.level for i in issues_of(weekly(), level="published")] == ["warning"] @@ -123,7 +123,7 @@ def test_one_graph_level_auto_fix_serves_every_follower(): fix = fixes[FIX] assert fix["kind"] == "auto" and fix["node_id"] is None and fix["code"] == CODE assert fix["preview"] == {"field": "defaults.approval", "before": "never", "after": "dangerous"} - assert "全图默认" in fix["label"] and "「查数员」" in fix["label"] and "「复核员」" in fix["label"] + assert "工作流默认设置" in fix["label"] and "「查数员」" in fix["label"] and "「复核员」" in fix["label"] # 两条问题都挂上同一个修复 id(问题在节点上,修复不在) out = check(spec, level="governed") assert {i["node_id"]: i["fix"] for i in out["issues"] if i["code"] == CODE} == {"ask": FIX, "ask2": FIX} @@ -178,14 +178,14 @@ def test_a_rule_that_does_not_really_fix_it_is_rejected(monkeypatch): monkeypatch.setitem(autofix._EDITORS, CODE, lambda graph, fix, value: []) out = apply_fixes(weekly(), [FIX], level="governed") assert out["applied"] == [] and out["rejected"][0]["fix_id"] == FIX - assert "还在" in out["rejected"][0]["reason"] + assert "仍然存在" in out["rejected"][0]["reason"] @pytest.mark.parametrize("prev, now, word", [ - ("dangerous", "never", "全部自动放行"), - ("always", "never", "全部自动放行"), + ("dangerous", "never", "全部无需审批"), + ("always", "never", "全部无需审批"), ("always", "dangerous", "放宽"), - ("dangerous", None, "全图默认"), + ("dangerous", None, "工作流默认设置"), ]) def test_loosening_the_graph_default_is_still_forbidden(prev, now, word): before = weekly(default=prev) diff --git a/backend/tests/test_autofix_rules.py b/backend/tests/test_autofix_rules.py index a6276e82..581a28c1 100644 --- a/backend/tests/test_autofix_rules.py +++ b/backend/tests/test_autofix_rules.py @@ -291,7 +291,7 @@ def test_structural_problems_go_to_copilot(): graph["nodes"].insert(1, node("team", "supervisor", "协作团队", goal="查数", agents=[{"name": "a"}])) graph["edges"] += [{"source": "start", "target": "team"}, {"source": "team", "target": "fetch"}] fix = plan(graph)["governed.supervisor:team"] - assert fix["kind"] == "assist" and "固定编排" in fix["label"] and fix["node_id"] == "team" + assert fix["kind"] == "assist" and "配置固定" in fix["label"] and fix["node_id"] == "team" out = apply_fixes(graph, ["governed.supervisor:team"], level="governed") assert out["applied"] == [] and out["rejected"][0]["fix_id"] == "governed.supervisor:team" @@ -388,23 +388,23 @@ def raised(default: str = "dangerous") -> dict: (lambda g: g["edges"].pop(0), "连线"), (lambda g: config(g, "done").pop("contract"), "契约"), (lambda g: config(g, "done").update(contract={}), "契约"), - (lambda g: config(g, "done")["contract"].update(strict=False), "strict"), - (lambda g: config(g, "done")["contract"].update(required=[]), "required"), - (lambda g: config(g, "write").update(approval="never"), "全部自动放行"), - (lambda g: g.setdefault("defaults", {}).update(approval="never"), "全部自动放行"), + (lambda g: config(g, "done")["contract"].update(strict=False), "严格模式"), + (lambda g: config(g, "done")["contract"].update(required=[]), "必需指标"), + (lambda g: config(g, "write").update(approval="never"), "全部无需审批"), + (lambda g: g.setdefault("defaults", {}).update(approval="never"), "全部无需审批"), # 审批按「每次调用都审批 > 仅危险工具需要审批 > 全部自动放行」排,往宽里改、删掉都算降低要求 (lambda g: config(g, "fetch").update(approval="dangerous"), "放宽"), - (lambda g: config(g, "fetch").update(approval="Always"), "不认识"), + (lambda g: config(g, "fetch").update(approval="Always"), "无法识别"), # 删掉写明的审批,运行时退回全图默认(这里是仅危险工具需要审批),比原来的每次调用都审批宽 - (lambda g: config(g, "fetch").pop("approval"), "去掉了"), - (lambda g: config(g, "fetch").update(approval=None), "去掉了"), - (lambda g: config(g, "fetch").update(approval=""), "去掉了"), + (lambda g: config(g, "fetch").pop("approval"), "删除了"), + (lambda g: config(g, "fetch").update(approval=None), "删除了"), + (lambda g: config(g, "fetch").update(approval=""), "删除了"), # 全图默认删掉,退回全局设置:可能是全部自动放行 - (lambda g: g["defaults"].pop("approval"), "全图默认"), + (lambda g: g["defaults"].pop("approval"), "工作流默认设置"), # 白名单里的数字不用引用也能过;cells 要作者显式声明,不由模型替人打开 - (lambda g: config(g, "done")["contract"]["allow_numbers"].append("120"), "allow_numbers"), - (lambda g: config(g, "done")["contract"].update(allow_numbers=["7", "37"]), "allow_numbers"), - (lambda g: config(g, "done")["contract"].update(cells=True), "cells"), + (lambda g: config(g, "done")["contract"]["allow_numbers"].append("120"), "允许无出处的数字"), + (lambda g: config(g, "done")["contract"].update(allow_numbers=["7", "37"]), "允许无出处的数字"), + (lambda g: config(g, "done")["contract"].update(cells=True), "单元格引用"), # 同一个 id 换了类型:等于删了重建 (lambda g: find(g, "write").update(type="llm"), "换成"), ]) @@ -432,8 +432,8 @@ def test_forbidden_ops_are_named(op): @pytest.mark.parametrize("mutate, word", [ - (lambda g: config(g, "card").update(approval="dangerous"), "跟随全图默认"), # 原来跟全图默认:每次调用都审批 - (lambda g: g["defaults"].update(approval="dangerous"), "全图默认"), + (lambda g: config(g, "card").update(approval="dangerous"), "跟随工作流默认设置"), # 原来跟全图默认:每次调用都审批 + (lambda g: g["defaults"].update(approval="dangerous"), "工作流默认设置"), (lambda g: (g["defaults"].pop("approval"), config(g, "card").update(approval="dangerous")), "放宽"), ]) def test_lowering_a_strict_graph_default_is_forbidden(mutate, word): @@ -462,10 +462,10 @@ def test_a_new_contract_cannot_open_cells_or_whitelist_numbers(): assert forbidden_changes(before, after) == [] config(after, "done")["contract"].update(cells=True, allow_numbers=["2026"]) reasons = forbidden_changes(before, after) - assert any("cells" in r for r in reasons) and any("allow_numbers" in r for r in reasons), reasons + assert any("单元格引用" in r for r in reasons) and any("允许无出处的数字" in r for r in reasons), reasons fresh = copy.deepcopy(before) fresh["nodes"].append(node("extra", "output", "另一个出口", contract={**skeleton, "cells": True})) - assert any("cells" in r for r in forbidden_changes(before, fresh)) + assert any("单元格引用" in r for r in forbidden_changes(before, fresh)) def test_overwriting_an_existing_node_is_forbidden(): @@ -478,7 +478,7 @@ def test_overwriting_an_existing_node_is_forbidden(): after = copy.deepcopy(before) find(after, "write")["type"] = "llm" [reason] = forbidden_changes(before, after) - assert "报告撰写" in reason and "换成" in reason and "删了重建" in reason, reason + assert "报告撰写" in reason and "换成" in reason and "删除后重建" in reason, reason def test_a_type_change_shows_in_the_preview(): diff --git a/backend/tests/test_caliber_from.py b/backend/tests/test_caliber_from.py index 7e4df79f..294ed0f7 100644 --- a/backend/tests/test_caliber_from.py +++ b/backend/tests/test_caliber_from.py @@ -197,7 +197,7 @@ async def test_a_newer_upstream_blocks_formal_runs_without_a_policy(client): res = await formal(client, weekly({"workflow_id": lib, "workflow_version": 1, "node_id": "caliber"})) assert res.status_code == 409, res.text detail = res.json()["detail"] - assert "「本地口径卡」" in detail and "v1" in detail and "v2" in detail and "upgrade_policy" in detail + assert "「本地口径卡」" in detail and "v1" in detail and "v2" in detail and "「上游发布新版本时」" in detail async def test_a_declared_policy_is_recorded(client): @@ -211,7 +211,7 @@ async def test_a_declared_policy_is_recorded(client): assert event.node_id == "card" assert {k: event.data.get(k) for k in ("workflow_id", "pinned", "latest", "policy", "policy_label", "caliber_node")} == { - "workflow_id": lib, "pinned": 1, "latest": 2, "policy": "dual", "policy_label": "并排双印新旧口径", + "workflow_id": lib, "pinned": 1, "latest": 2, "policy": "dual", "policy_label": "新旧口径并列展示", "caliber_node": "caliber"} @@ -257,4 +257,4 @@ async def test_subgraphs_keep_the_same_upgrade_rule(client): node("sub", "subgraph", "方法卡", workflow_id=lib, workflow_version=1), node("out", "output", fields=[{"name": "r", "value": "{{ nodes.sub.text }}"}])) res = await formal(client, graph) - assert res.status_code == 409 and "「方法卡」(子工作流)钉在 v1,但上游已有 v2" in res.json()["detail"] + assert res.status_code == 409 and "「方法卡」(子工作流)固定在 v1,但上游已有 v2" in res.json()["detail"] diff --git a/backend/tests/test_code_evidence_role.py b/backend/tests/test_code_evidence_role.py index 859d8f2d..7d62621f 100644 --- a/backend/tests/test_code_evidence_role.py +++ b/backend/tests/test_code_evidence_role.py @@ -78,7 +78,7 @@ def test_unknown_role_is_refused(monkeypatch): ctx, sandbox = _ctx(monkeypatch, limits={}, evidence_role="fetch") with pytest.raises(NodeError) as info: _run(ctx) - assert "evidence_role" in str(info.value) and "source" in str(info.value) + assert "「证据角色」" in str(info.value) and "「取数」" in str(info.value) assert sandbox.calls == [], "角色写错了还去跑沙箱" diff --git a/backend/tests/test_continue_run.py b/backend/tests/test_continue_run.py index da67dce6..2a6f984f 100644 --- a/backend/tests/test_continue_run.py +++ b/backend/tests/test_continue_run.py @@ -181,7 +181,7 @@ async def test_continue_refuses_a_graph_that_fails_validation(): GraphSpec.model_validate(graph_with(condition=BROKEN)) ), "这个用例的前提是骨架不变" - with pytest.raises(ValueError, match="没有通过校验"): + with pytest.raises(ValueError, match="未通过校验"): await run_manager.continue_failed(run_id, graph=bad) @@ -227,4 +227,4 @@ async def test_continue_through_the_api(client): resumed = [r for r in rows if r["type"] == "run.resumed"] assert resumed, "接着跑必须在时间线上留下痕迹" msg = resumed[-1]["data"].get("message", "") - assert "接着跑" in msg and "保留" in msg, msg + assert "继续运行" in msg and "保留" in msg, msg diff --git a/backend/tests/test_contract_cells.py b/backend/tests/test_contract_cells.py index 3efc6d86..6f22f06b 100644 --- a/backend/tests/test_contract_cells.py +++ b/backend/tests/test_contract_cells.py @@ -458,7 +458,7 @@ def test_turning_cells_on_unasked_is_still_loosening(): before["nodes"][-1]["data"]["config"]["contract"].pop("cells") after = cells_only() [why] = forbidden_changes(before, after) - assert "cells" in why + assert "单元格引用" in why assert forbidden_changes(before, after, chosen={("out", "contract.cells")}) == [] @@ -471,9 +471,9 @@ def test_only_a_newly_raised_human_choice_error_is_let_through(): other = {"level": "error", "code": "contract.strict_off", "node_id": "out", "message": "strict 关了"} assert judge([no_contract], [cells]) is None # 补上契约、cells 留给人:算更好 assert worse([], [cells]) is None - assert "冒出新的问题" in (judge([no_contract], [other]) or "") # 别的新 error 照样作废 + assert "出现了新的问题" in (judge([no_contract], [other]) or "") # 别的新 error 照样作废 assert judge([no_contract], [cells, other]) is not None # 原来就有的 cells 照常计数:修它的那一步,改完还在就是没修好 - assert "还在" in (judge([cells], [cells], target=("contract.cells_undeclared", "out")) or "") + assert "仍然存在" in (judge([cells], [cells], target=("contract.cells_undeclared", "out")) or "") assert judge([cells], [], target=("contract.cells_undeclared", "out")) is None - assert judge([cells], [cells]) == "改完错误没有变少" # 原来就有、改完还在:Copilot 兜底不算修好 + assert judge([cells], [cells]) == "修改后错误没有减少" # 原来就有、改完还在:Copilot 兜底不算修好 diff --git a/backend/tests/test_contract_citations.py b/backend/tests/test_contract_citations.py index d3b26171..d09844d8 100644 --- a/backend/tests/test_contract_citations.py +++ b/backend/tests/test_contract_citations.py @@ -239,7 +239,7 @@ async def test_a_report_nobody_sees_is_a_gap(monkeypatch): fields=[{"name": "周期", "value": "{{ input.week }}"}])) issuance = row.output["_issuance"] assert issuance["tier"] == "degraded" - assert any("没有哪个字段" in g for g in issuance["gaps"]), issuance["gaps"] + assert any("没有任何字段" in g for g in issuance["gaps"]), issuance["gaps"] async def test_rebuilds_the_catalog_with_the_report_nodes_own_parameters(monkeypatch): diff --git a/backend/tests/test_contract_claims.py b/backend/tests/test_contract_claims.py index b3e9bd79..4c90237b 100644 --- a/backend/tests/test_contract_claims.py +++ b/backend/tests/test_contract_claims.py @@ -292,14 +292,14 @@ def test_the_effective_claims_policy_is_the_stricter_one(written, declared, gove def test_a_run_in_flight_across_the_upgrade_keeps_the_old_gap(): - """升级前写的报告(产出里没有 claims)碰上写了 require_citation 的契约:照旧记「这一版还不支持」,不判档。""" + """升级前写的报告(产出里没有 claims)碰上写了 require_citation 的契约:照旧只记一条缺口,不判档。""" from app.engine.nodes.io import _claims out = {"gaps": [], "claims_policy": None, "uncited": None, "claims": None} _claims(out, {"claims": "require_citation"}, {"text": "x"}, evidence_on=True, governed=False, uncited=[{"unit": "u1", "span": [0, 4], "text": "增长很快"}]) assert out["claims_policy"] is None and out["claims"] is None - assert len(out["gaps"]) == 1 and "这一版还不支持" in out["gaps"][0] + assert len(out["gaps"]) == 1 and "生成于系统升级前" in out["gaps"][0] # -------------------------------------------------------------------------- diff --git a/backend/tests/test_contract_judge.py b/backend/tests/test_contract_judge.py index 281704f9..d259ed5c 100644 --- a/backend/tests/test_contract_judge.py +++ b/backend/tests/test_contract_judge.py @@ -7,7 +7,7 @@ - judge 在挂引用这件事上和 require_citation 一样严:没挂依据的结论句照样计入缺口 - 探索运行按需裁判:出口只标注(候选句都是「未裁判 · 按需」),不因判定改档位 - 契约也能写 claims: judge:只能收紧(on_unsupported 取更严的);报告节点没开 judge 的,照实记缺口 -- 升级前的运行照旧:契约写了也记「这一版还不支持」 +- 升级前的运行照旧:契约写了也只记一条缺口「报告生成于系统升级前,结论句未核对」 """ from __future__ import annotations @@ -187,7 +187,7 @@ async def test_a_failed_judge_is_a_gap_not_a_withheld_report(monkeypatch): issuance = await issued(weekly(report={"judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}})) assert issuance["tier"] == "degraded", "没判成不能盖完整出具,也不能当成「不支持」不予出具" [gap] = [g for g in issuance["gaps"] if "裁判" in g] - assert gap.startswith("报告「write」") and "没裁判" in gap and "网关 502" in gap + assert gap.startswith("报告「write」") and "未裁判" in gap and "网关 502" in gap assert issuance["claims"]["complete"] is False and issuance["claims"]["counts"]["unjudged"] == 2 @@ -196,7 +196,7 @@ async def test_hitting_a_limit_is_a_gap(monkeypatch): issuance = await issued(weekly(report={"judge": {"max_cost_usd": 0.05, "max_claims": 1}})) assert issuance["tier"] == "degraded" [gap] = [g for g in issuance["gaps"] if "裁判" in g] - assert "已到上限" in gap and "1 句" in gap + assert "已达上限" in gap and "1 句" in gap assert issuance["claims"]["limits_hit"] == ["max_claims"] and issuance["claims"]["counts"]["unjudged"] == 1 @@ -274,20 +274,20 @@ async def test_a_contract_asking_for_judge_on_a_report_without_it_is_a_gap(monke Models(monkeypatch) issuance = await issued(weekly(report={"claims": "require_citation"}, contract={"claims": "judge"})) assert issuance["tier"] == "degraded" - [gap] = [g for g in issuance["gaps"] if "judge" in g] - assert "「write」" in gap and "没有开" in gap and "这一版" not in gap + [gap] = [g for g in issuance["gaps"] if "模型裁判" in g] + assert "「write」" in gap and "未开启" in gap and "这一版" not in gap assert issuance["claims"]["policy"] == "require_citation" def test_a_run_in_flight_across_the_upgrade_keeps_the_old_gap(): - """升级前写的报告(产出里没有 claims)碰上写了 judge 的契约:照旧记「这一版还不支持」,不判档。""" + """升级前写的报告(产出里没有 claims)碰上写了 judge 的契约:照旧只记一条缺口,不判档。""" from app.engine.nodes.io import _claims out = {"gaps": [], "claims_policy": None, "uncited": None, "claims": None, "unsupported": None} _claims(out, {"claims": {"policy": "judge", "on_unsupported": "withhold"}}, {"text": "x"}, evidence_on=True, uncited=[{"unit": "u1", "span": [0, 4], "text": "增长很快"}]) assert out["claims_policy"] is None and out["claims"] is None and out["unsupported"] is None - assert len(out["gaps"]) == 1 and "这一版还不支持" in out["gaps"][0] + assert len(out["gaps"]) == 1 and "生成于系统升级前" in out["gaps"][0] async def test_runs_from_before_the_upgrade_ignore_judge(monkeypatch): diff --git a/backend/tests/test_conversations.py b/backend/tests/test_conversations.py index cbbd2849..cf7b9a5a 100644 --- a/backend/tests/test_conversations.py +++ b/backend/tests/test_conversations.py @@ -279,7 +279,7 @@ async def test_the_first_turn_has_nothing_to_fall_back_on(client, monkeypatch) - ]) assert final["op"] == "final" assert final["graph"]["nodes"] == [] - assert any("空" in str(i.get("message", "")) for i in final["issues"]), final["issues"] + assert any("还没有节点" in str(i.get("message", "")) for i in final["issues"]), final["issues"] # -------------------------------------------------------------------------- diff --git a/backend/tests/test_copilot_evidence_guide.py b/backend/tests/test_copilot_evidence_guide.py index 7b3379bf..9473da07 100644 --- a/backend/tests/test_copilot_evidence_guide.py +++ b/backend/tests/test_copilot_evidence_guide.py @@ -101,7 +101,8 @@ def test_sql_columns_missing_from_the_schema_are_sent_back(): [issue] = authored_issues(spec, [shop]) assert issue["level"] == "error" and issue["code"] == "sql_unknown_column" assert issue["node_id"] == "fetch" and issue["field"] == "args.sql" - assert "amt、wk" in issue["message"] and "amount" in issue["message"] and "db_schema__shop" in issue["message"] + assert "amt、wk" in issue["message"] and "amount" in issue["message"] and "db_schema__shop" in issue["for_model"] + assert "db_schema__" not in issue["message"] and "别凭空猜" not in issue["message"], "给模型的指令不上界面" good = _node("fetch", "tool", tool="db_query__shop", args={"sql": "SELECT SUM(amount) AS gmv, COUNT(*) AS n FROM orders WHERE week = '{{ input.week }}' " @@ -135,7 +136,7 @@ def test_parsing_agent_text_is_sent_back(): ) [issue] = authored_issues(spec, []) assert issue["code"] == "parse_model_text" and issue["level"] == "error" and issue["node_id"] == "parse" - assert "cite_fields" in issue["message"] and "不要用整形节点解析 agent / llm 的文字" in issue["message"] + assert "按出处核对字段" in issue["message"] and "不要用整形节点解析 agent / llm 的文字" in issue["for_model"] # -------------------------------------------------------------------------- @@ -239,6 +240,7 @@ def test_model_text_inside_template_quotes_is_sent_back_with_the_json_filter_fix assert issue["code"] == "parse_model_text" and issue["level"] == "error" assert "{{ nodes.query_logs.text | json }}" in issue["message"] assert "cite_fields" not in issue["message"] and "不要用整形节点解析" not in issue["message"] + assert "不要用整形节点解析" not in issue.get("for_model", "") #: 都是能跑的 SQL:关键字、运算符、排序规则名、窗口名、表达式后面不写 AS 的别名,都不是列 diff --git a/backend/tests/test_copilot_merge.py b/backend/tests/test_copilot_merge.py index 1e24fd1e..71aff232 100644 --- a/backend/tests/test_copilot_merge.py +++ b/backend/tests/test_copilot_merge.py @@ -309,7 +309,7 @@ async def test_dropping_tools_without_being_asked_is_called_out(client, monkeypa assert {i["node_id"] for i in dropped} == {"query_data", "review_team"} assert all(i["level"] == "warning" for i in dropped) text = next(i["message"] for i in dropped if i["node_id"] == "query_data") - assert "数据查询" in text and "db_query__shop、db_schema__shop" in text and "变成了空" in text + assert "数据查询" in text and "db_query__shop、db_schema__shop" in text and "变为无" in text text = next(i["message"] for i in dropped if i["node_id"] == "review_team") assert "取数员" in text and "db_query__shop" in text diff --git a/backend/tests/test_copilot_prompt_evidence.py b/backend/tests/test_copilot_prompt_evidence.py index b4c3d9ae..fe4250e1 100644 --- a/backend/tests/test_copilot_prompt_evidence.py +++ b/backend/tests/test_copilot_prompt_evidence.py @@ -86,7 +86,7 @@ async def test_metrics_from_pointing_at_a_non_card_is_sent_back(client, monkeypa events = await generate(client, monkeypatch, model) sent = issues_of(events, "repairing") assert any(i["code"] == "report.metrics_from_invalid" and i["node_id"] == "write" for i in sent), sent - assert "不是「口径卡」" in model.calls[1] + assert "不是口径卡" in model.calls[1] assert [e["status"] for e in events if e["op"] == "check"] == ["repairing", "passed"] @@ -262,4 +262,4 @@ async def test_the_copilot_still_may_not_switch_cells_on_by_itself(client, monke "cells": True}}}, {"op": "done", "explanation": "补上契约并打开 cells"}]) [rejected] = [r for r in out["rejected"] if r["fix_id"] == "assist"] - assert "cells" in rejected["reason"] and out["ok"] is False + assert "单元格引用" in rejected["reason"] and out["ok"] is False diff --git a/backend/tests/test_custom_tool_schema.py b/backend/tests/test_custom_tool_schema.py index cf878e91..07257212 100644 --- a/backend/tests/test_custom_tool_schema.py +++ b/backend/tests/test_custom_tool_schema.py @@ -90,21 +90,21 @@ def test_a_near_miss_type_gets_a_suggestion(kind, guess): from app.tools.custom import schema_problem problem = schema_problem({"type": "object", "properties": {"n": {"type": kind}}}) - assert problem and f"是不是想写 {guess}" in problem, problem + assert problem and f"是否应为 {guess}" in problem, problem def test_an_unrecognisable_type_gets_no_guess(): from app.tools.custom import schema_problem problem = schema_problem({"type": "object", "properties": {"n": {"type": "timestamp"}}}) - assert problem and "「timestamp」" in problem and "是不是想写" not in problem, problem + assert problem and "「timestamp」" in problem and "是否应为" not in problem, problem async def test_parameters_that_are_not_an_object_are_refused_in_words_too(client): r = await client.post("/api/custom-tools", json={ "name": _name(), "kind": "http", "parameters": ["city"], "config": {}}) assert r.status_code == 422 - assert r.json()["detail"] == "参数定义要是一个 JSON 对象" + assert r.json()["detail"] == "参数定义必须是一个 JSON 对象" async def test_editing_a_tool_into_a_broken_schema_is_refused_and_nothing_changes(client): diff --git a/backend/tests/test_datasource.py b/backend/tests/test_datasource.py index 0e5a9617..aff0ceca 100644 --- a/backend/tests/test_datasource.py +++ b/backend/tests/test_datasource.py @@ -81,7 +81,7 @@ async def test_summary_is_compact_enough_for_a_prompt(source): async def test_summary_says_so_when_never_introspected(source): """没探查过就明说,别让 Copilot 对着空气编表名。""" - assert "还没有探查过" in summary(source) + assert "尚未探查结构" in summary(source) async def test_describe_table_accepts_qualified_name(source): @@ -250,4 +250,4 @@ def test_why_empty_tells_the_two_cases_apart(): assert "失败" in why_empty(_FailedCache.schema_cache) assert "Lost connection" in why_empty(_FailedCache.schema_cache) - assert why_empty({}) == "还没有探查过结构" + assert why_empty({}) == "尚未探查结构" diff --git a/backend/tests/test_evidence_audit.py b/backend/tests/test_evidence_audit.py index 56011a97..02aee673 100644 --- a/backend/tests/test_evidence_audit.py +++ b/backend/tests/test_evidence_audit.py @@ -38,7 +38,7 @@ SQL = "SELECT region, SUM(amount) AS gmv, COUNT(*) AS order_cnt FROM orders GROU #: 和裸数字、没挂依据;第三句是没挂依据的结论 WRITE = ('`orders` 里东区最多, 达 [[v:Q1.r0.gmv]] "含税"。[[see:Q1]]`refund_log` 另算,另有 999 笔待核。' "增长主要来自新客。") -HEADER = ["分组", "报告节点", "成果字段", "片段", "句子编号", "种类", "原文", "状态", "问题", "引用", "证据", +HEADER = ["分组", "报告节点", "成果字段", "片段编号", "句子编号", "种类", "原文", "状态", "问题", "引用", "证据", "证据种类", "证据编号", "工件", "来源节点", "已封存", "句子", "说明", "封存核对"] @@ -192,7 +192,7 @@ async def test_the_audit_groups_every_stateful_piece(client, warehouse, monkeypa body = (await client.get(f"/api/runs/{row.id}/evidence/audit")).json() assert body["run_id"] == row.id and body["schema"] == "agentlab.evidence.audit/1" and body["mode"] == "cited" assert [g["key"] for g in body["groups"]] == ["cited", "none", "suspicious", "candidate"] - assert [g["label"] for g in body["groups"]] == ["有出处", "无证据", "可疑实体", "旧运行猜测"] + assert [g["label"] for g in body["groups"]] == ["有出处", "无证据", "可疑名称", "按数值猜测"] assert body["counts"] == {g["key"]: len(g["rows"]) for g in body["groups"]} assert body["total"] == sum(body["counts"].values()) @@ -214,12 +214,12 @@ async def test_the_audit_groups_every_stateful_piece(client, warehouse, monkeypa [fake] = rows_of(body, "suspicious") assert fake["kind"] == "entity" and fake["issue"] == "unknown_entity" and fake["text"] == "`refund_log`" - assert "可能是编造的名字" in fake["note"] + assert "疑似不存在的名称" in fake["note"] assert rows_of(body, "candidate") == [] seal = body["seal"] assert seal["sealed"] is True and seal["ok"] is True and seal["manifest_seq"] == row.manifest_seq - assert seal["events"] > 0 and seal["message"] == "事件流与封存时一致" + assert seal["events"] > 0 and seal["message"] == "事件记录与封存时一致" [report] = body["reports"] assert report["node_id"] == "write" and report["hash_ok"] is True and report["doc_sealed"] is True assert report["claims"] == "off" and report["stats"]["unknown_entities"] == 1 @@ -231,7 +231,7 @@ async def test_violations_without_a_row_of_their_own_are_listed(client, warehous body = (await client.get(f"/api/runs/{row.id}/evidence/audit")).json() [fake] = rows_of(body, "suspicious") assert (fake["kind"], fake["issue"], fake["text"]) == ("violation", "unknown_entity", "refund_log") - assert fake["segment"] and "可能是编造的名字" in fake["note"] + assert fake["segment"] and "疑似不存在的名称" in fake["note"] [bare] = rows_of(body, "none") assert (bare["kind"], bare["issue"], bare["text"]) == ("violation", "uncited_number", "100") assert [r["text"] for r in rows_of(body, "cited")] == ["400.5"] @@ -269,8 +269,8 @@ async def test_the_audit_exports_json_and_csv(client, warehouse, monkeypatch): assert cell[0] == "有出处" and cell[7] == "有出处" and cell[15] == "是" and cell[10] == "Q1.r0.gmv" # 句子里的 ASCII 逗号和双引号原样读回来 assert cell[16] == '`orders` 里东区最多, 达 400.5 "含税"。' - fake = next(line for line in table[1:] if line[8] == "可能是编造的名字") - assert fake[0] == "可疑实体" and fake[6] == "`refund_log`" + fake = next(line for line in table[1:] if line[8] == "疑似不存在的名称") + assert fake[0] == "可疑名称" and fake[6] == "`refund_log`" # 存下来的文件自己带着封存核对的结果(响应头离了浏览器就没了) assert {line[18] for line in table[1:]} == {f"封存核对通过(封存于第 {row.manifest_seq} 条事件)"} @@ -305,13 +305,13 @@ async def test_a_broken_seal_marks_every_row_unsealed(client, warehouse, monkeyp started.data = {**(started.data or {}), "note": "事后改过"} await session.commit() body = (await client.get(f"/api/runs/{row.id}/evidence/audit")).json() - assert body["seal"]["ok"] is False and "对不上" in body["seal"]["message"] + assert body["seal"]["ok"] is False and "不一致" in body["seal"]["message"] assert all(r["sealed"] is False for r in rows_of(body, "cited")) as_csv = await client.get(f"/api/runs/{row.id}/evidence/audit", params={"format": "csv"}) assert as_csv.headers["x-evidence-seal"] == "broken" table = list(csv.reader(io.StringIO(as_csv.content.decode("utf-8")[1:]))) assert {line[15] for line in table[1:] if line[0] == "有出处"} == {"否"} - assert {line[18] for line in table[1:]} == {"封存核对没通过:封存之后有事件被改过、删过或插过"} + assert {line[18] for line in table[1:]} == {"封存核对未通过:封存后有事件被修改、删除或插入"} async def test_a_run_waiting_for_approval_is_audited_as_unsealed(client, warehouse, monkeypatch): @@ -334,7 +334,7 @@ async def test_a_run_waiting_for_approval_is_audited_as_unsealed(client, warehou as_csv = await client.get(f"/api/runs/{run.id}/evidence/audit", params={"format": "csv"}) assert as_csv.headers["x-evidence-seal"] == "unsealed" table = list(csv.reader(io.StringIO(as_csv.content.decode("utf-8")[1:]))) - assert len(table) > 1 and {line[18] for line in table[1:]} == {"未封存:运行还没跑完,或者停在人工审批"} + assert len(table) > 1 and {line[18] for line in table[1:]} == {"未封存:运行尚未结束,或正停在人工审批"} CLAIMED = "`orders` 里东区最多,达 [[m:gmv]]。[[see:m:gmv]]增长主要来自新客。" diff --git a/backend/tests/test_evidence_entities.py b/backend/tests/test_evidence_entities.py index b4df237b..668f2c38 100644 --- a/backend/tests/test_evidence_entities.py +++ b/backend/tests/test_evidence_entities.py @@ -175,7 +175,7 @@ def test_unknown_marker_is_suspicious_not_unresolved(catalog): doc = compose_doc("退款看 [[t:refund_log]]。字段写错 [[t:amount]]。", catalog) fake, wrong = entity_segments(doc) assert fake["text"] == "refund_log" and fake["state"] == "none" and fake["issue"] == "unknown_entity" - assert "可能是编造的名字" in fake["cite"]["reason"] + assert "疑似不存在的名称" in fake["cite"]["reason"] # 字段当表写:名字是真的,写法错了——这是解析不了,要重写 assert wrong["issue"] == "unresolved_ref" and wrong["text"].startswith("⟦?t:") assert codes(doc) == ["unknown_entity", "unresolved_ref"] @@ -305,7 +305,7 @@ def test_a_truncated_schema_cannot_call_a_name_made_up(catalog): assert segs[1]["cite"]["unverified"] is True and "unknown" not in segs[1]["cite"] # 违规按位置排:句末依据 [[see:]] 的位置记的是整句,排在最前 assert codes(doc) == ["unverified_entity", "unverified_entity", "unverified_entity", "unknown_entity"] - assert "核对不了" in doc["violations"][0]["message"] and "编造" not in doc["violations"][0]["message"] + assert "无法核实" in doc["violations"][0]["message"] and "疑似不存在" not in doc["violations"][0]["message"] assert doc["stats"]["unverified_entities"] == 3 and doc["stats"]["unknown_entities"] == 1 checked = verify_doc(doc, cut) assert checked["violations"] == doc["violations"] and checked["stats"] == doc["stats"] @@ -618,7 +618,7 @@ async def test_report_with_a_bad_entities_value_fails(engine_up, warehouse, monk monkeypatch.setattr(mock_model.MockChatModel, "_decide", lambda self, messages: seen.append(1) or AIMessage("x")) row = await finish(tool_graph(node("write", "report", instructions="写一句", entities="bogus"))) assert row.status == "failed" - assert "entities 只能是 link / off,写的是 'bogus'" in (row.error or ""), row.error + assert "「表名、字段名」只能是「核对」或「不核对」,当前为「bogus」" in (row.error or ""), row.error assert seen == [], "写错的配置不该先花一次模型调用" diff --git a/backend/tests/test_evidence_entity_chain.py b/backend/tests/test_evidence_entity_chain.py index 937bf98f..2c854e12 100644 --- a/backend/tests/test_evidence_entity_chain.py +++ b/backend/tests/test_evidence_entity_chain.py @@ -237,7 +237,7 @@ async def test_a_made_up_name_explains_itself_and_suggests_real_ones(client, war assert 0 < len(step["closest"]) <= 3 assert step["closest"][0] == {"alias": "t:refunds", "kind": "table", "name": "refunds"} assert step["checked"] == {"schemas": 1, "queries": 1} - assert "可能是编造的名字" in body["note"] + assert "疑似不存在的名称" in body["note"] assert [v["code"] for v in body["violations"]] == ["unknown_entity"] @@ -255,7 +255,7 @@ async def test_a_name_a_partial_snapshot_cannot_check_is_not_called_made_up(clie body = await opened(client, row.id, seg_where(doc, kind="entity", issue="unverified_entity")) [step] = body["chain"] assert step["status"] == "unverified" and step["name"] == "refund_log" - assert step["reason"] == UNVERIFIED_ENTITY_REASON and "编造" not in body["note"] and "核对不了" in body["note"] + assert step["reason"] == UNVERIFIED_ENTITY_REASON and "疑似不存在" not in body["note"] and "无法核实" in body["note"] table = await opened(client, row.id, seg_where(doc, kind="entity", ref="t:orders")) assert table["chain"][0]["snapshot_truncated"] is True assert {s["kind"]: s for s in table["chain"][0]["sources"]}["schema"]["truncated"] is True @@ -365,4 +365,4 @@ async def test_an_unmatched_quote_has_no_chain(client, monkeypatch): seg = seg_where(doc, kind="quote") assert seg["state"] == "none" body = await opened(client, row.id, seg) - assert body["chain"] == [] and "找不到这句原话" in body["note"] + assert body["chain"] == [] and "找不到这段引文的原文" in body["note"] diff --git a/backend/tests/test_evidence_judge.py b/backend/tests/test_evidence_judge.py index 944ac797..f274bebc 100644 --- a/backend/tests/test_evidence_judge.py +++ b/backend/tests/test_evidence_judge.py @@ -433,9 +433,9 @@ async def test_claims_over_max_claims_are_unjudged(monkeypatch, stored): assert sorted(judge.judged[0]) == sorted([ids[CITED], ids[CITED2]]), "先判挂了依据的" for text in (CAUSAL, NUMBER): v = status_of(outcome, doc, text) - assert (v["status"], v["reason"]) == ("unjudged", "max_claims") and "已到上限" in v["rationale"] + assert (v["status"], v["reason"]) == ("unjudged", "max_claims") and "已达上限" in v["rationale"] assert outcome["limits_hit"] == ["max_claims"] and outcome["unjudged"] == {"max_claims": 2} - assert outcome["gaps"] and "已到上限" in outcome["gaps"][0] + assert outcome["gaps"] and "已达上限" in outcome["gaps"][0] async def test_cost_truncation_follows_priority(monkeypatch, stored): @@ -521,9 +521,9 @@ async def test_a_model_without_a_price_ignores_money_limits(monkeypatch, stored) budget=Budget(max_claims=None, max_cost_usd=1e-9, timeout_s=None, daily_max_usd=1e-9), emit=lambda kind, **data: events.append((str(kind), data))) assert len(judge.calls) == 1 and outcome["counts"]["unjudged"] == 0 - assert outcome["priced"] is False and any("按令牌估不出金额" in n for n in outcome["notes"]) + assert outcome["priced"] is False and any("无法按 token 数估算金额" in n for n in outcome["notes"]) [log] = [d for k, d in events if k == EventType.LOG and d.get("code") == "judge_unpriced"] - assert "按令牌估不出金额" in log["message"] + assert "无法按 token 数估算金额" in log["message"] # -------------------------------------------------------------------------- diff --git a/backend/tests/test_evidence_judge_api.py b/backend/tests/test_evidence_judge_api.py index 1524cbab..8bb20cc2 100644 --- a/backend/tests/test_evidence_judge_api.py +++ b/backend/tests/test_evidence_judge_api.py @@ -296,7 +296,7 @@ async def test_hitting_the_click_limit_is_a_result_not_an_error(client, monkeypa body = res.json() assert body["limited"] is True and body["limits_hit"] == ["max_cost_usd"] assert body["unjudged"] == {"max_cost_usd": 1} - assert body["message"].startswith("已到上限") and "这次点击" in body["message"] + assert body["message"].startswith("已达上限") and "这次点击" in body["message"] assert any("设置" in how and "不限" in how for how in body["adjust"]) verdict = body["verdicts"][uid] assert verdict["status"] == "unjudged" and verdict["reason"] == "max_cost_usd" and verdict["post_seal"] is True @@ -369,7 +369,7 @@ async def test_formal_runs_are_judged_inside_the_node_not_on_demand(client, monk calls = len(models.judges) res = await judge(client, row.id, [unit_ids(doc_of(row))[CAUSAL]]) assert res.status_code == 409 and res.json()["code"] == "evidence_judge_formal" - assert "正式运行的裁判在节点内完成" in res.json()["detail"] + assert "正式运行的结论句已在报告撰写节点内完成裁判" in res.json()["detail"] assert len(models.judges) == calls and await judged_events(row.id) == [] @@ -431,7 +431,7 @@ async def test_a_run_continued_during_the_judge_call_records_no_event(client, mo body = res.json() assert len(models.judges) == 1 and body["calls"] == 1, "模型问过了" assert body["verdicts"][uid]["status"] == "unsupported" and body["judged"] == [uid], "判定照样交回" - assert body["event"] is None and "接着跑" in body["message"] and "没有记进运行记录" in body["message"] + assert body["event"] is None and "运行已继续执行" in body["message"] and "未写入运行记录" in body["message"] assert await judged_events(row.id) == [] async with SessionLocal() as session: after = await session.get(Run, row.id) @@ -463,7 +463,7 @@ async def test_a_continue_that_wins_the_row_between_check_and_write_gets_no_even monkeypatch.setattr(bus, "set_seq", claimed_in_between) body = (await judge(client, row.id, [uid])).json() assert body["verdicts"][uid]["status"] == "unsupported" and body["event"] is None - assert "没有记进运行记录" in body["message"] and await judged_events(row.id) == [] + assert "未写入运行记录" in body["message"] and await judged_events(row.id) == [] async with SessionLocal() as session: after = await session.get(Run, row.id) assert after.status == "running" and after.last_seq == row.last_seq @@ -518,7 +518,7 @@ async def test_the_segment_shows_the_verdict_and_whether_it_can_still_be_asked(c assert "模型" in after["note"] and "后续版本" not in after["note"] other = (await client.get(f"/api/runs/{row.id}/evidence/segments/{seg_in(doc, ids[CITED])}")).json() assert other["unit"]["on_demand"]["available"] is True - assert "挂了依据" in other["note"] and "模型" in other["note"] and "后续版本" not in other["note"] + assert "附有依据" in other["note"] and "模型" in other["note"] and "后续版本" not in other["note"] link = (await client.get(f"/api/runs/{row.id}/evidence/segments/{seg_in(doc, ids[LINK])}")).json() assert link["unit"]["on_demand"]["reason"] == "not_a_claim" and "verdict" not in link["unit"] diff --git a/backend/tests/test_evidence_markers.py b/backend/tests/test_evidence_markers.py index 782a3d59..30c1a218 100644 --- a/backend/tests/test_evidence_markers.py +++ b/backend/tests/test_evidence_markers.py @@ -254,7 +254,7 @@ def test_unresolved_references(catalog): reasons = {v["ref"]: v["message"] for v in bad} assert "gmvx" in reasons["m:gmvx"] assert "没有值" in reasons["m:gone"] - assert "目录里没有 Q4" in reasons["v:Q4.r0.amount"] # 单元格二期起支持,这份目录里没有 Q4 + assert "查询结果 Q4 不存在" in reasons["v:Q4.r0.amount"] # 单元格二期起支持,这份目录里没有 Q4 assert "百分数" in reasons["m:wow|pct"] for s in iter_segments(doc): if s.get("ref"): diff --git a/backend/tests/test_evidence_query_chain.py b/backend/tests/test_evidence_query_chain.py index 7cd3db19..d93d0752 100644 --- a/backend/tests/test_evidence_query_chain.py +++ b/backend/tests/test_evidence_query_chain.py @@ -244,7 +244,7 @@ async def test_masks_recorded_at_query_time_survive_a_renamed_source(client, mon email = step["columns"].index("email") assert {r[email] for r in step["rows"]} == {"已遮罩"} and step["masked"] == ["email"], step assert body["redacted"]["columns"] == ["email"] - assert "「shop」" in step["mask_note"] and "查询当时" in step["mask_note"], step + assert "「shop」" in step["mask_note"] and "按查询时记录的遮罩" in step["mask_note"], step async def test_masks_added_after_the_query_still_apply(client, monkeypatch, shop): diff --git a/backend/tests/test_evidence_quotes.py b/backend/tests/test_evidence_quotes.py index d1802d18..ca29904e 100644 --- a/backend/tests/test_evidence_quotes.py +++ b/backend/tests/test_evidence_quotes.py @@ -21,7 +21,8 @@ from app.core import artifact_store from app.db.base import SessionLocal from app.db.models import Run, RunEvent from app.engine.evidence import ( - LATER_REASON, + LEGACY_LATER_REASON, + PHASE_TWO_REASON, StreamRenderer, build_catalog, catalog_prompt, @@ -83,7 +84,7 @@ def test_one_changed_character_is_not_a_quote(catalog): [seg] = quotes(doc) # 正文照样显示引文本身,只是标成没有出处 assert seg["text"] == "退款主要集中在西区" and seg["state"] == "none" and seg["issue"] == "unresolved_ref" - assert "逐字" in seg["cite"]["reason"] + assert "找不到这段引文的原文" in seg["cite"]["reason"] assert [v["code"] for v in doc["violations"]] == ["unresolved_ref"] assert doc["stats"]["quotes"] == 0 @@ -115,8 +116,8 @@ def test_numbers_inside_a_verified_quote_are_not_bare(catalog): @pytest.mark.parametrize("text, words", [ - ("[[q:K9|退款主要集中在东区]]", "目录里没有 K9"), - ("[[q:K1|]]", "引文是空的"), + ("[[q:K9|退款主要集中在东区]]", "检索结果 K9 不存在"), + ("[[q:K1|]]", "引文为空"), ("[[q:K1|东区]]", "太短"), ]) def test_quotes_that_cannot_be_checked(catalog, text, words): @@ -149,11 +150,11 @@ def test_exit_check_rereads_the_snapshot(catalog): def phase_two(doc): - """把文档改回二期组装的样子:那时 q / t / c 一律判为解析不了,正文是占位,原因是 LATER_REASON。 + """把文档改回二期组装的样子:那时 q / t / c 一律判为解析不了,正文是占位,原因是 LEGACY_LATER_REASON。 占位的字和现在「目录里没有 K9」时一样,只有记下的原因不同。""" for seg in iter_segments(doc): if seg.get("issue") == "unresolved_ref" and seg["ref"][:2] in ("q:", "t:", "c:"): - seg["cite"]["reason"] = LATER_REASON + seg["cite"]["reason"] = LEGACY_LATER_REASON return doc @@ -165,7 +166,7 @@ def test_quotes_from_before_the_upgrade_are_rechecked_the_old_way(catalog): assert seg["text"] == "⟦?q:K1|退款主要集中在东区⟧" checked = verify_doc(doc, catalog, loader=LOAD) assert [v["code"] for v in checked["violations"]] == ["unresolved_ref"] - assert LATER_REASON in checked["violations"][0]["message"] + assert PHASE_TWO_REASON in checked["violations"][0]["message"] # 只认占位:正文被改成了引文本身、又自称是二期的,照样按现在的规矩查 seg["text"] = "退款主要集中在东区" doc["markdown"] = "售后说退款主要集中在东区。" diff --git a/backend/tests/test_evidence_validate.py b/backend/tests/test_evidence_validate.py index 6b926a38..245a0170 100644 --- a/backend/tests/test_evidence_validate.py +++ b/backend/tests/test_evidence_validate.py @@ -29,15 +29,15 @@ SCHEMA = {"type": "object", "properties": {"gmv": {"type": "number"}}} def test_output_schema_without_cite_fields_warns(): bot = node("bot", "agent", prompt="查", tools=["db_query__shop"], output_schema=SCHEMA, model="m") - [issue] = [i for i in issues(START, bot, OUT, node_id="bot") if "cite_fields" in i.message] + [issue] = [i for i in issues(START, bot, OUT, node_id="bot") if "按出处核对字段" in i.message] assert issue.level == "warning" and issue.field == "output_schema" - assert issue.message.startswith("output_schema 要开 cite_fields 才生效,会多一次抽取调用") + assert issue.message.startswith("「结构化输出 Schema」需要同时开启「按出处核对字段」才会生效(会多一次抽取调用)") cited = node("bot", "agent", prompt="查", tools=["db_query__shop"], output_schema=SCHEMA, cite_fields=True, model="m") - assert not [i for i in issues(START, cited, OUT, node_id="bot") if "cite_fields" in i.message] + assert not [i for i in issues(START, cited, OUT, node_id="bot") if "按出处核对字段" in i.message] plain = node("bot", "agent", prompt="查", tools=["db_query__shop"], model="m") - assert not [i for i in issues(START, plain, OUT, node_id="bot") if "cite_fields" in i.message] + assert not [i for i in issues(START, plain, OUT, node_id="bot") if "按出处核对字段" in i.message] def test_caliber_fed_by_a_compute_code_node_warns(): @@ -47,17 +47,17 @@ def test_caliber_fed_by_a_compute_code_node_warns(): {"id": "gmv", "expression": "vars.agg.gmv"}, {"id": "gmv2", "expression": "nodes.fetch.gmv * 2"}]) return issues(START, fetch, card, OUT, node_id="card") - [issue] = [i for i in graph() if "evidence_role" in i.message] + [issue] = [i for i in graph() if "「证据角色」" in i.message] assert issue.level == "warning" and issue.field == "metrics[0].expression" - assert "「取数脚本」" in issue.message and "source" in issue.message - assert [i for i in graph(evidence_role="compute") if "evidence_role" in i.message] - assert not [i for i in graph(evidence_role="source") if "evidence_role" in i.message] + assert "「取数脚本」" in issue.message and "「取数」" in issue.message + assert [i for i in graph(evidence_role="compute") if "「证据角色」" in i.message] + assert not [i for i in graph(evidence_role="source") if "「证据角色」" in i.message] def test_evidence_role_must_be_source_or_compute(): fetch = node("fetch", "code", code="print(1)", evidence_role="取数") [issue] = [i for i in issues(START, fetch, OUT, node_id="fetch") if i.field == "evidence_role"] - assert issue.level == "error" and "source" in issue.message and "compute" in issue.message + assert issue.level == "error" and "「取数」" in issue.message and "「计算」" in issue.message def test_report_without_a_model_gets_the_same_warning_as_llm(): @@ -86,7 +86,7 @@ def test_caliber_from_replaces_local_metrics(): policy = node("card", "metrics", caliber_from=pinned, upgrade_policy="auto") [issue] = [i for i in issues(START, policy, OUT, node_id="card") if i.field == "upgrade_policy"] - assert issue.level == "error" and "recompute" in issue.message + assert issue.level == "error" and "「用新口径回算历史」" in issue.message ok = node("card", "metrics", caliber_from=pinned, upgrade_policy="dual") assert not [i for i in issues(START, ok, OUT, node_id="card") if i.level == "error"] diff --git a/backend/tests/test_expressions.py b/backend/tests/test_expressions.py index 226913a7..3555efee 100644 --- a/backend/tests/test_expressions.py +++ b/backend/tests/test_expressions.py @@ -52,7 +52,7 @@ def test_braces_inside_a_string_literal_are_left_alone(): @pytest.mark.parametrize("expr, hint", [ ("{{ vars.items | length }} > 0", "len(x)"), # 模板过滤器 ("vars.gate in {'ok', 'fail'}", "用列表"), # 集合写法 - ("foo(vars.gate)", "能用的只有"), # 不认识的函数 + ("foo(vars.gate)", "可用的函数"), # 不认识的函数 ("'{{ vars.gate }}' == 'ok'", "不会被渲染"), # 引号里的模板永远不成立 ("vars.gate = 'ok'", "=="), # 赋值当比较 ("[x for x in vars.items]", "列表推导式"), @@ -103,7 +103,7 @@ def issues_of(*nodes): def test_a_broken_loop_condition_blocks_the_run(): found = issues_of(node("lp", "loop", mode="while", condition="{{ vars.items | length }} > 0")) - assert any(level == "error" and "循环条件写错了" in msg and "len(x)" in msg for level, msg in found), found + assert any(level == "error" and "循环条件有误" in msg and "len(x)" in msg for level, msg in found), found def test_braces_are_a_warning_not_an_error(): @@ -121,26 +121,26 @@ def test_fields_that_are_not_evaluated_in_this_mode_are_not_checked(): node("lp", "loop", mode="foreach", items="[1]", condition="这不是表达式 >>>"), node("t", "transform", mode="template", template="x", expression="这也不是 >>>"), ) - assert not [m for lv, m in found if "写错了" in m], found + assert not [m for lv, m in found if "有误" in m], found def test_branch_in_llm_mode_is_not_checked_either(): found = issues_of(node("br", "branch", mode="llm", cases=[{"key": "a", "condition": "随便写的描述"}])) - assert not [m for lv, m in found if "写错了" in m], found + assert not [m for lv, m in found if "有误" in m], found def test_skip_if_and_metrics_are_checked(): found = issues_of(node("t", "transform", expression="1", skip_if="vars.x = 1")) - assert any("跳过条件写错了" in m for _, m in found), found + assert any("跳过条件有误" in m for _, m in found), found found = issues_of(node("m", "metrics", metrics=[{"id": "r", "expression": "foo(1)"}])) - assert any("指标「r」的表达式写错了" in m for _, m in found), found + assert any("指标「r」的表达式有误" in m for _, m in found), found def test_empty_while_condition_and_empty_transform_expression(): found = issues_of(node("lp", "loop", mode="while", condition="")) - assert any(lv == "warning" and "一次都不会跑" in m for lv, m in found), found + assert any(lv == "warning" and "循环体不会执行" in m for lv, m in found), found found = issues_of(node("t", "transform", mode="expression", expression="")) - assert any(lv == "error" and "没有填表达式" in m for lv, m in found), found + assert any(lv == "error" and "还没有填写表达式" in m for lv, m in found), found # -------------------------------------------------------------------------- diff --git a/backend/tests/test_gov_wrapup.py b/backend/tests/test_gov_wrapup.py index 263f3590..d28c060a 100644 --- a/backend/tests/test_gov_wrapup.py +++ b/backend/tests/test_gov_wrapup.py @@ -146,7 +146,7 @@ def test_removing_the_schema_of_a_cited_agent_is_refused(): after = copy.deepcopy(before) config(after, "ask").pop("output_schema") [reason] = forbidden_changes(before, after) - assert "「查数助手」" in reason and "output_schema" in reason + assert "「查数助手」" in reason and "「结构化输出 Schema」" in reason config(after, "ask")["output_schema"] = {} assert forbidden_changes(before, after) @@ -175,7 +175,7 @@ async def test_copilot_self_check_still_sees_report_policy_without_defaults(clie wf = await create(client, graph) await client.post(f"/api/workflows/{wf}/autofix", json={"level": "governed", "apply": [], "assist": True}) human = next(text for role, text in model.calls[0] if role == "human") - assert "要写明" in human + assert "需要调整核对规则" in human def test_the_assist_rules_forbid_marking_sources_and_loosening_reports(): diff --git a/backend/tests/test_governance_judge.py b/backend/tests/test_governance_judge.py index 4052d3ee..627dff9f 100644 --- a/backend/tests/test_governance_judge.py +++ b/backend/tests/test_governance_judge.py @@ -85,7 +85,7 @@ def test_judge_without_a_budget_is_an_error_at_governed(judge): graph = traceable(report=report) [issue] = by_code(graph, BUDGET) assert issue.level == "error" and issue.node_id == "write" and issue.field == "judge.max_cost_usd" - assert "max_cost_usd" in issue.message and "不限" in issue.message and "null" in issue.message + assert "「金额上限(美元)」" in issue.message and "不限" in issue.message and "「结论句裁判」" in issue.message assert by_code(graph, "governed.report_policy") == [], "judge 本身合规,只缺预算" assert [i.level for i in by_code(graph, BUDGET, "published")] == ["warning"] @@ -114,7 +114,8 @@ def test_a_malformed_budget_is_left_to_validate(): def test_a_loose_claims_setting_names_both_accepted_values(claims): report = {"numbers": "strict", "on_violation": "fail", **({"claims": claims} if claims else {})} [issue] = by_code(traceable(report=report), "governed.report_policy") - assert issue.field == "claims" and "claims: require_citation" in issue.message and "judge" in issue.message + assert issue.field == "claims" and "「未附依据的结论句」设为「计入缺口」" in issue.message \ + and "「计入缺口并由模型逐句判断」" in issue.message def test_judge_needs_no_other_report_policy_fix(): @@ -181,7 +182,7 @@ def test_a_choice_outside_the_options_is_refused(): graph = traceable(report={**STRICT, "claims": "judge"}) fid = f"{BUDGET}:write" out = apply_fixes(graph, [fid], {fid: 99}, level="governed") - assert out["applied"] == [] and "不在候选里" in out["rejected"][0]["reason"] + assert out["applied"] == [] and "不在候选项中" in out["rejected"][0]["reason"] def test_published_level_budget_warnings_get_no_fix(): @@ -222,13 +223,13 @@ def test_moving_up_to_judge_is_not_loosening(): def test_moving_down_from_judge_is_loosening(after): report_after = None if after is None else {**JUDGED, "claims": after} [reason] = _changed(JUDGED, report_after) - assert "「报告撰写」" in reason and "claims" in reason and "judge" in reason + assert "「报告撰写」" in reason and "「未附依据的结论句」" in reason and "「计入缺口并由模型逐句判断」" in reason def test_dropping_a_judge_set_in_the_graph_defaults_is_loosening(): [reason] = _changed({"numbers": "strict", "on_violation": "fail"}, {**STRICT, "claims": "off"}, defaults={"claims": "judge", "judge": {"max_cost_usd": 0.05}}) - assert "claims" in reason and "judge" in reason + assert "「未附依据的结论句」" in reason and "「计入缺口并由模型逐句判断」" in reason def test_changing_the_budget_is_not_loosening(): @@ -248,16 +249,16 @@ WITHHOLD = {**JUDGED, "judge": {"max_cost_usd": 0.05, "on_unsupported": "withhol ]) def test_relaxing_on_unsupported_on_the_node_is_loosening(judge, dropped): [reason] = _changed(WITHHOLD, {**WITHHOLD, "judge": judge}) - assert "「报告撰写」" in reason and "judge.on_unsupported" in reason - assert "withhold" in reason and "degrade" in reason - assert ("去掉了写明的值" in reason) is dropped, reason + assert "「报告撰写」" in reason and "「结论句裁判 · 证据不支持时」" in reason + assert "「不予出具」" in reason and "「出具降档」" in reason + assert ("删除了已设置的值" in reason) is dropped, reason def test_replacing_the_whole_judge_block_to_add_a_budget_is_loosening(): """补预算把 judge 整个换成 {max_cost_usd}:连同裁判模型、withhold 一起丢了。""" before = {**STRICT, "claims": "judge", "judge": {"model": "judge-model", "on_unsupported": "withhold"}} [reason] = _changed(before, {**before, "judge": {"max_cost_usd": 0.05}}) - assert "judge.on_unsupported" in reason and "withhold" in reason + assert "「结论句裁判 · 证据不支持时」" in reason and "「不予出具」" in reason assert _changed(before, {**before, "judge": {**before["judge"], "max_cost_usd": 0.05}}) == [], \ "带着原来的键补预算不算放宽" @@ -267,8 +268,8 @@ def test_a_withhold_from_the_graph_defaults_lost_by_a_node_judge_is_loosening(): defaults = {"judge": {"on_unsupported": "withhold", "max_cost_usd": 0.05}} report = {**STRICT, "claims": "judge"} [reason] = _changed(report, {**report, "judge": {"max_cost_usd": 0.05}}, defaults=defaults) - assert "judge.on_unsupported" in reason and "从 withhold(跟随全图默认)" in reason, reason - assert "不再跟随全图默认" in reason, "说清楚为什么全图默认里的 withhold 不生效了" + assert "「结论句裁判 · 证据不支持时」" in reason and "从「不予出具」(跟随工作流默认设置)" in reason, reason + assert "不再跟随工作流默认设置" in reason, "说清楚为什么全图默认里的 withhold 不生效了" assert _changed(report, {**report, "judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}}, defaults=defaults) == [] @@ -279,7 +280,7 @@ def test_relaxing_on_unsupported_in_the_graph_defaults_is_loosening(): new = copy.deepcopy(old) new["defaults"]["judge"]["on_unsupported"] = "degrade" [reason] = forbidden_changes(old, new) - assert "「报告撰写」" in reason and "judge.on_unsupported" in reason + assert "「报告撰写」" in reason and "「结论句裁判 · 证据不支持时」" in reason @pytest.mark.parametrize("before, after", [ @@ -296,7 +297,7 @@ def test_tightening_or_keeping_on_unsupported_is_fine(before, after): def test_dropping_withhold_along_with_judge_is_one_reason(): """从 judge 退回 require_citation:claims 那一条已经说了,不再为 on_unsupported 另记一条。""" [reason] = _changed(WITHHOLD, {**STRICT, "judge": {"max_cost_usd": 0.05}}) - assert "claims" in reason and "on_unsupported" not in reason + assert "「未附依据的结论句」" in reason and "证据不支持时" not in reason @pytest.mark.parametrize("before", ["require_citation", "judge"]) @@ -305,7 +306,10 @@ def test_moving_claims_to_an_unknown_value_is_loosening(before): 「没让图变好」。原来就认不出的不比较。""" report = {**STRICT, "claims": before, **({"judge": {"max_cost_usd": 0.05}} if before == "judge" else {})} [reason] = _changed(report, {**report, "claims": "sometimes"}) - assert "「报告撰写」" in reason and before in reason and "sometimes" in reason and "不认识" in reason + from app.engine.labels import option_label + + assert "「报告撰写」" in reason and f"「{option_label('claims', before)}」" in reason and "sometimes" in reason \ + and "无法识别" in reason assert _changed({**STRICT, "claims": "sometimes"}, {**STRICT, "claims": "off"}) == [] assert _changed({**STRICT, "claims": "off"}, {**STRICT, "claims": "sometimes"}) == [] @@ -331,7 +335,7 @@ def _contract_changed(before, after) -> list[str]: ]) def test_loosening_a_judge_contract_is_refused(before, after): [reason] = _contract_changed(before, after) - assert "「出具」" in reason and "claims" in reason + assert "「出具」" in reason and "对结论句的要求" in reason @pytest.mark.parametrize("before, after", [ diff --git a/backend/tests/test_governance_report_lint.py b/backend/tests/test_governance_report_lint.py index 8b8ba76f..5205b542 100644 --- a/backend/tests/test_governance_report_lint.py +++ b/backend/tests/test_governance_report_lint.py @@ -126,7 +126,7 @@ async def test_a_governed_contract_without_report_from_is_refused(client): graph = traceable(report_from=None, narrative="{{ nodes.write.text }}") [issue] = by_code(graph, "governed.report_from_required") assert issue.level == "error" and issue.node_id == "done" and issue.field == "contract.report_from" - assert "report_from" in issue.message and "narrative" in issue.message + assert "「报告来自」" in issue.message and "「叙述」" in issue.message body = await publish(client, graph) assert body["ok"] is False assert "governed.report_from_required" in {i["code"] for i in body["issues"] if i["level"] == "error"} @@ -258,7 +258,8 @@ def test_a_report_node_must_spell_out_the_strict_settings(): graph = traceable(report={}) [issue] = by_code(graph, "governed.report_policy") assert issue.level == "error" and issue.node_id == "write" and issue.field == "numbers" - for piece in ("numbers: strict", "on_violation: fail", "claims: require_citation"): + for piece in ("「未引用的数字」设为「计为违规,要求重写」", "「重写后仍有违规时」设为「判为失败」", + "「未附依据的结论句」设为「计入缺口」"): assert piece in issue.message assert [i.level for i in by_code(graph, "governed.report_policy", "published")] == ["warning"] @@ -267,9 +268,11 @@ def test_a_report_node_must_spell_out_the_strict_settings(): def test_a_looser_setting_is_named(key, value): graph = traceable(report={**STRICT, key: value}) [issue] = by_code(graph, "governed.report_policy") - assert issue.field == key and f"现在是 {value}" in issue.message + from app.engine.labels import field_label, option_label + + assert issue.field == key and f"当前为「{option_label(key, value)}」" in issue.message for other in set(STRICT) - {key}: - assert f"{other}:" not in issue.message + assert f"「{field_label(other)}」" not in issue.message def test_graph_defaults_count_like_they_do_at_run_time(): @@ -284,7 +287,7 @@ def test_an_unsupported_claims_value_is_left_to_validate(): graph = traceable(report={**STRICT, "claims": "sometimes"}) assert by_code(graph, "governed.report_policy") == [] [bad] = [i for i in validate_graph(GraphSpec.model_validate(graph)).issues if i.code == "report.claims_invalid"] - assert bad.level == "error" and "off / require_citation" in bad.message + assert bad.level == "error" and "「不参与出具判档」、「计入缺口」" in bad.message # -------------------------------------------------------------------------- @@ -301,7 +304,7 @@ def test_compute_code_feeding_a_caliber_card_is_refused(role): config(graph, "card")["metrics"].append({"id": "ratio", "expression": "vars.calc.ratio"}) [issue] = by_code(graph, "governed.caliber_compute_input") assert issue.level == "error" and issue.node_id == "calc" and issue.field == "evidence_role" - assert "「周报口径卡」" in issue.message and "source" in issue.message + assert "「周报口径卡」" in issue.message and "「取数」" in issue.message assert [i.level for i in by_code(graph, "governed.caliber_compute_input", "published")] == ["warning"] config(graph, "calc")["evidence_role"] = "source" assert by_code(graph, "governed.caliber_compute_input") == [] @@ -466,7 +469,7 @@ def test_judge_is_supported_now(): @pytest.mark.parametrize("value", ["strict", "Require_Citation", 1, ["off"], {"policy": "judge"}]) def test_other_claims_values_are_errors(value): [issue] = claims_issues(value) - assert issue.level == "error" and "off / require_citation" in issue.message and repr(value) in issue.message + assert issue.level == "error" and "「不参与出具判档」、「计入缺口」" in issue.message and f"「{value}」" in issue.message def test_claims_from_graph_defaults_are_checked_too(): diff --git a/backend/tests/test_guardrails.py b/backend/tests/test_guardrails.py index 829be00b..33ca08e4 100644 --- a/backend/tests/test_guardrails.py +++ b/backend/tests/test_guardrails.py @@ -85,7 +85,7 @@ async def test_a_run_past_its_time_limit_is_stopped(monkeypatch): started = time.perf_counter() run = await _run(SIMPLE) assert run.status == "failed" - assert "1 秒的上限" in (run.error or "") + assert "1 秒的时长上限" in (run.error or "") assert time.perf_counter() - started < 10, "上限没起作用,等到了节点自己结束" diff --git a/backend/tests/test_judge_settings.py b/backend/tests/test_judge_settings.py index 82603175..88fd6de3 100644 --- a/backend/tests/test_judge_settings.py +++ b/backend/tests/test_judge_settings.py @@ -97,7 +97,10 @@ async def test_bad_values_are_refused_with_a_reason(key, value): await c.put("/api/settings", content='{"values": {"judge": {"%s": NaN}}}' % key, headers={"content-type": "application/json"}) assert r.status_code == 422, r.text - assert key in r.json()["detail"] + # 报错写设置页上的叫法(「每日金额上限(美元)」),不写键名;认不出的键原样点名 + from app.engine.judge import SETTING_LABEL + + assert SETTING_LABEL.get(key, key) in r.json()["detail"] assert (await c.get("/api/settings")).json()["judge"] == JUDGE_DEFAULTS, "整组都没写进去" @@ -224,23 +227,23 @@ def test_every_limit_can_be_unlimited(): @pytest.mark.parametrize("judge,field,words", [ ("fast", "judge", "对象"), - ({"max_cost": 1}, "judge.max_cost", "max_cost_usd"), + ({"max_cost": 1}, "judge.max_cost", "「金额上限(美元)」"), ({"max_claims": 0}, "judge.max_claims", "正整数"), ({"max_claims": 2.5}, "judge.max_claims", "正整数"), ({"max_claims": True}, "judge.max_claims", "正整数"), ({"max_cost_usd": -1}, "judge.max_cost_usd", "大于 0"), ({"max_cost_usd": "0.05"}, "judge.max_cost_usd", "大于 0"), ({"timeout_s": 0}, "judge.timeout_s", "大于 0"), - ({"rewrite_once": "yes"}, "judge.rewrite_once", "true 或 false"), - ({"on_unsupported": "ignore"}, "judge.on_unsupported", "degrade / withhold"), - ({"model": 3}, "judge.model", "模型 id"), + ({"rewrite_once": "yes"}, "judge.rewrite_once", "开启或关闭"), + ({"on_unsupported": "ignore"}, "judge.on_unsupported", "「出具降档」或「不予出具」"), + ({"model": 3}, "judge.model", "模型 ID"), ]) def test_a_malformed_judge_block_is_an_error(judge, field, words): [issue] = issues(graph({"claims": "judge", "judge": judge}), "report.judge_invalid") assert issue.level == "error" and issue.node_id == "write" and issue.field == field assert words in issue.message, issue.message if field in ("judge.max_claims", "judge.max_cost_usd", "judge.timeout_s", "judge.model"): - assert "null" in issue.message, "上限、模型都说清写 null 是什么意思" + assert ("留空" if field == "judge.model" else "不限") in issue.message, "上限、模型都说清不填是什么意思" def test_graph_defaults_are_checked_like_at_run_time(): @@ -256,7 +259,7 @@ def test_judging_with_the_writing_model_is_a_warning(): [warn] = [i for i in validate_graph(GraphSpec.model_validate(graph( {"claims": "judge", "model": "writer-x", "judge": {"model": "writer-x"}}))).issues if i.code == "report.judge_same_model"] - assert warn.level == "warning" and warn.field == "judge.model" and "自己审自己" in warn.message + assert warn.level == "warning" and warn.field == "judge.model" and "裁判模型与写作模型相同" in warn.message assert not [i for i in validate_graph(GraphSpec.model_validate(graph( {"claims": "judge", "model": "writer-x", "judge": {"model": "judge-y"}}))).issues if i.code == "report.judge_same_model"] diff --git a/backend/tests/test_lint_contract_report_from.py b/backend/tests/test_lint_contract_report_from.py index 96467be0..59a9fc7f 100644 --- a/backend/tests/test_lint_contract_report_from.py +++ b/backend/tests/test_lint_contract_report_from.py @@ -86,7 +86,7 @@ def test_without_report_from_or_narrative_the_gate_still_asks(level, expected): del contract_of(graph)["report_from"] [issue] = [i for i in lint(graph, level) if i.code == "contract.report_from_missing"] assert issue.level == expected and issue.node_id == "done" - assert "report_from" in issue.message and "narrative" in issue.message + assert "「报告来自」" in issue.message and "「叙述」" in issue.message def test_an_empty_report_from_counts_as_missing(): diff --git a/backend/tests/test_manage_api.py b/backend/tests/test_manage_api.py index 6fd931fd..f4b83b09 100644 --- a/backend/tests/test_manage_api.py +++ b/backend/tests/test_manage_api.py @@ -258,7 +258,7 @@ async def test_testing_a_mistyped_sqlite_path_does_not_create_the_file(client, t "readonly": False}) body = r.json() assert body["ok"] is False, body - assert "打不开这个数据库文件" in body["error"] and body["hint"] and body["detail"] + assert "无法打开该数据库文件" in body["error"] and body["hint"] and body["detail"] assert not missing.exists(), "测连接把一个空库建出来了" r = await client.post("/api/datasources/test", json={"kind": "sqlite", "database": "", "readonly": False}) @@ -275,6 +275,45 @@ async def test_testing_a_mistyped_sqlite_path_does_not_create_the_file(client, t await client.delete(f"/api/datasources/{saved['id']}") +async def test_database_connect_failures_get_database_hints(client): + """连不上、等超时、密码错这几类,按错误类别换成数据库的说法:说主机和端口、用户名和密码, + 不说 API Key、Base URL。以前按报错文字全等比较,通用那句多了半句就永远比不上,数据库的提示从不出现; + 前缀「连不上:」还和原因「连不上对方的服务」叠成同一句话说两遍。""" + import asyncio + import socket + + from app.api.datasources import _explain_connect + + # 真连一个没人监听的端口:驱动抛的是自己的异常类,走的是类别判断,不是字面匹配 + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + r = await client.post("/api/datasources/test", json={"kind": "postgres", "host": "127.0.0.1", "port": port, + "database": "x", "username": "u", "password": "p"}) + body = r.json() + assert body["ok"] is False, body + if "驱动" not in body["error"]: # 没装 asyncpg 的环境只能测到「没装驱动」 + assert body["error"] == "连接失败:网络不通,或数据库服务未启动", body + assert "「主机」" in body["hint"] and "「端口」" in body["hint"], body + assert "API" not in body["hint"] and "Base URL" not in body["hint"], body + + reason, hint = _explain_connect(ConnectionRefusedError(61, "Connection refused"), "mysql") + assert (reason, "「主机」" in hint) == ("网络不通,或数据库服务未启动", True) + reason, hint = _explain_connect(asyncio.TimeoutError(), "postgres") + assert reason == "数据库长时间没有响应" and "「端口」" in hint + + class InvalidAuthorizationSpecificationError(Exception): + """asyncpg 的鉴权异常:原文不一定带 password 字样,按类名认""" + + reason, hint = _explain_connect(InvalidAuthorizationSpecificationError("role \"u\" is not permitted"), "postgres") + assert reason == "用户名或密码错误" and "「用户名」" in hint and "API Key" not in hint + + # 测连接的错误不能把同一句话说两遍 + for e in (ConnectionRefusedError(61, "Connection refused"), asyncio.TimeoutError()): + reason, _ = _explain_connect(e, "postgres") + assert "连不上" not in f"连接失败:{reason}" and "连接" not in reason + + async def test_draft_test_of_an_existing_source_keeps_the_saved_password(client, shop_db): from app.api.datasources import DataSourceTestIn, _draft_source from app.core.crypto import decrypt, encrypt @@ -495,7 +534,7 @@ async def test_a_csv_upload_is_pointed_at_datasources(client): r = await client.post("/api/kb/upload", files={"file": ("sales.csv", b"a,b\n1,2", "text/csv")}) assert r.status_code == 415 detail = r.json()["detail"] - assert "数据源" in detail and "传表格" in detail, detail + assert "「数据」页" in detail and "上传表格" in detail, detail # -------------------------------------------------------------------------- @@ -546,7 +585,7 @@ async def test_only_a_succeeded_run_can_become_a_template(client): for status in ("failed", "cancelled", "interrupted", "running"): r = await client.post("/api/copilot/from-run", json={"run_id": await _run_with(status)}) assert r.status_code == 409, (status, r.text) - assert "没有跑完" in r.json()["detail"] + assert "未成功结束" in r.json()["detail"] before = await _count(Workflow) r = await client.post("/api/copilot/from-run", json={"run_id": await _run_with("succeeded")}) diff --git a/backend/tests/test_markup_leak.py b/backend/tests/test_markup_leak.py index d79f435d..d2cbf6dd 100644 --- a/backend/tests/test_markup_leak.py +++ b/backend/tests/test_markup_leak.py @@ -115,7 +115,7 @@ async def test_an_agent_that_keeps_writing_markup_fails(monkeypatch): node("out", "output", fields=[{"name": "r", "value": "{{ nodes.query.text }}"}]), )) assert row.status == "failed", f"一堆标记被当成了答案:{row.output}" - assert "工具调用的原始标记" in (row.error or "") and "没有真正调用工具" in (row.error or "") + assert "工具调用的原始标记" in (row.error or "") and "未实际调用工具" in (row.error or "") assert row.error_node_id == "query" assert "tool_markup_leak" in [e.data.get("code") for e in events if e.type == "log"] @@ -187,9 +187,9 @@ async def test_markup_in_the_settle_round_keeps_what_the_agent_found(monkeypatch assert row.status == "succeeded", row.error assert [e.type for e in events].count("tool.end") == 2 assert "<||DSML" not in row.output["r"] - assert "先算第 2 步。" in row.output["r"] and "用满了 2 步" in row.output["r"], row.output + assert "先算第 2 步。" in row.output["r"] and "已用完 2 步" in row.output["r"], row.output leak = [e.data for e in events if e.type == "log" and e.data.get("code") == "tool_markup_leak"] - assert leak and "收尾轮" in leak[0]["message"], leak + assert leak and "收尾时" in leak[0]["message"], leak async def test_markup_to_the_very_end_without_any_real_call_still_fails(monkeypatch): diff --git a/backend/tests/test_model_error.py b/backend/tests/test_model_error.py index 4c83d1ed..fee33570 100644 --- a/backend/tests/test_model_error.py +++ b/backend/tests/test_model_error.py @@ -31,7 +31,7 @@ def test_invalid_model_says_model_not_key() -> None: assert "deepseek-chat" in msg, "必须说清是哪个模型,否则没法排查" assert "不存在" in msg - assert "设置" in msg and "供应商" in msg, "要给出下一步去哪儿改" + assert "「设置 → 模型接入」" in msg, "要给出下一步去哪儿改:设置页里这一组叫「模型接入」" # 别把用户往换 key 的方向带 assert "401" not in msg assert "Authentication" not in msg diff --git a/backend/tests/test_net_fake_ip.py b/backend/tests/test_net_fake_ip.py index 5d68eafd..42363b95 100644 --- a/backend/tests/test_net_fake_ip.py +++ b/backend/tests/test_net_fake_ip.py @@ -118,7 +118,7 @@ async def test_a_name_public_dns_does_not_know_is_blocked(monkeypatch): DoH({"doh-a.test:A": {"Status": 3}, "doh-a.test:AAAA": {"Status": 3}}).install(monkeypatch) with pytest.raises(UnsafeUrlError) as e: await assert_safe_url("http://build-server.internal/") - assert "查不到" in str(e.value) + assert "无法解析" in str(e.value) async def test_when_no_resolver_answers_it_fails_closed(monkeypatch): diff --git a/backend/tests/test_publish_check_api.py b/backend/tests/test_publish_check_api.py index 9bff08d2..06d36a35 100644 --- a/backend/tests/test_publish_check_api.py +++ b/backend/tests/test_publish_check_api.py @@ -203,10 +203,10 @@ async def test_bad_requests(client): assert r.status_code == 404 body = (await client.post(f"/api/workflows/{wf}/publish-check", json={"level": "governed", "graph": {"nodes": [{"id": "a", "type": "nope"}]}})).json() - assert body["ok"] is False and body["fixes"] == [] and "读不懂" in body["issues"][0]["message"] + assert body["ok"] is False and body["fixes"] == [] and "无法解析" in body["issues"][0]["message"] body = (await client.post(f"/api/workflows/{wf}/autofix", json={ "level": "governed", "graph": {"nodes": [{"id": "a", "type": "nope"}]}, "apply": ["x:y"]})).json() - assert body["ok"] is False and body["applied"] == [] and "读不懂" in body["remaining"][0]["message"] + assert body["ok"] is False and body["applied"] == [] and "无法解析" in body["remaining"][0]["message"] async def test_the_draft_in_the_database_is_the_default(client): diff --git a/backend/tests/test_query_deadline.py b/backend/tests/test_query_deadline.py index 92df4e5a..cacf282e 100644 --- a/backend/tests/test_query_deadline.py +++ b/backend/tests/test_query_deadline.py @@ -105,7 +105,7 @@ async def test_sqlite_stops_a_runaway_query_at_the_limit(sqlite_source): run_query(source, RUNAWAY, limits=QueryLimits(timeout_seconds=1)), 6) assert back, "查询时限到了,语句还在数据库里跑,调用一直没回来" assert isinstance(outcome, SqlRejected), outcome - assert "1s" in str(outcome) and "被中断" in str(outcome) + assert "1 秒" in str(outcome) and "被中断" in str(outcome) assert took < 3, f"1s 的时限等了 {took:.1f}s" engine = await engines.get(source) assert engine.sync_engine.pool.checkedout() == 0, "被中断的查询还占着连接" @@ -144,7 +144,7 @@ async def test_a_source_can_set_its_own_limit(sqlite_source): source = await sqlite_source(query_timeout_s="1") back, outcome, took = await _within(run_query(source, RUNAWAY), 6) assert back and isinstance(outcome, SqlRejected), outcome - assert "1s" in str(outcome) and took < 3 + assert "1 秒" in str(outcome) and took < 3 def test_the_limit_is_read_from_options_and_defaults_otherwise(shop_db): @@ -183,7 +183,7 @@ async def test_the_query_tool_declares_the_limit(sqlite_source, monkeypatch): assert limit.seconds == 1 and limit.kind == "query" and limit.self_timed back, outcome, took = await _within(tool.coroutine(sql=RUNAWAY), 6) - assert back and "1s" in str(outcome) and took < 3, (outcome, took) + assert back and "1 秒" in str(outcome) and took < 3, (outcome, took) # -------------------------------------------------------------------------- @@ -320,7 +320,7 @@ async def test_a_query_stopped_by_the_database_reads_as_a_timeout(monkeypatch, k _fake(monkeypatch, mariadb=kind == "mariadb", fail=RuntimeError(driver_error)) with pytest.raises(SqlRejected) as caught: await run_query(_remote(kind), "SELECT 1", limits=QueryLimits(timeout_seconds=5)) - assert "查询超过 5s 被中断" in str(caught.value), caught.value + assert "查询超过 5 秒被中断" in str(caught.value), caught.value class _PgCanceled(Exception): @@ -348,7 +348,7 @@ async def test_a_localized_timeout_is_recognised_by_its_code(monkeypatch, kind, _fake(monkeypatch, mariadb=kind == "mariadb", fail=error) with pytest.raises(SqlRejected) as caught: await run_query(_remote(kind), "SELECT 1", limits=QueryLimits(timeout_seconds=5)) - assert "查询超过 5s 被中断" in str(caught.value), caught.value + assert "查询超过 5 秒被中断" in str(caught.value), caught.value async def test_other_errors_are_not_mistaken_for_a_timeout(monkeypatch): @@ -420,7 +420,7 @@ async def test_a_slow_connection_does_not_let_the_backstop_beat_the_database(mon assert 0 < sent < 1000, f"数据库拿到的该是剩下的预算,实际是 {sent}ms" assert not isinstance(caught.value.__cause__, TimeoutError), \ "该是数据库按时限停下的那条路(deadline.stopped),不是后端兜底的 TimeoutError" - assert "查询超过 1s 被中断" in str(caught.value) + assert "查询超过 1 秒被中断" in str(caught.value) async def test_a_budget_spent_waiting_for_a_connection_sends_nothing(monkeypatch): @@ -429,7 +429,7 @@ async def test_a_budget_spent_waiting_for_a_connection_sends_nothing(monkeypatch with pytest.raises(SqlRejected) as caught: await run_query(_remote("postgres"), "SELECT 1", limits=QueryLimits(timeout_seconds=0.3)) assert pool.log == [], pool.log - assert "查询超过 0.3s 被中断" in str(caught.value) + assert "查询超过 0.3 秒被中断" in str(caught.value) # -------------------------------------------------------------------------- diff --git a/backend/tests/test_replay_side_effects.py b/backend/tests/test_replay_side_effects.py index 43965e6a..4c3f9fc4 100644 --- a/backend/tests/test_replay_side_effects.py +++ b/backend/tests/test_replay_side_effects.py @@ -261,7 +261,7 @@ async def test_an_old_pause_after_tools_ran_is_refused(monkeypatch): assert len(CALLS) == 1 _upgrade(monkeypatch) - with pytest.raises(ValueError, match="再执行一次"): + with pytest.raises(ValueError, match="重复执行"): await run_manager.resume(run.id, {"approved": True}) assert len(CALLS) == 1 async with SessionLocal() as session: @@ -312,6 +312,6 @@ async def test_continuing_an_old_failure_after_tools_ran_is_refused(monkeypatch) await run_manager.wait_idle(run.id) _upgrade(monkeypatch) - with pytest.raises(ValueError, match="再执行一次"): + with pytest.raises(ValueError, match="重复执行"): await run_manager.continue_failed(run.id) assert len(CALLS) == 1 diff --git a/backend/tests/test_report_cells.py b/backend/tests/test_report_cells.py index cfdf0afd..197b4079 100644 --- a/backend/tests/test_report_cells.py +++ b/backend/tests/test_report_cells.py @@ -176,13 +176,13 @@ def test_integer_decimal_text_renders_as_a_number(): @pytest.mark.parametrize("marker, words", [ ("[[v:Q1.r7.amount]]", "只有 7 行"), ("[[v:Q1.r0.gmv]]", "没有列「gmv」"), - ("[[v:Q9.r0.amount]]", "目录里没有 Q9"), + ("[[v:Q9.r0.amount]]", "查询结果 Q9 不存在"), ("[[v:K1.r0.amount]]", "不是查询结果"), - ("[[v:Q1.amount]]", "Q<编号>.r<行>.<列>"), - ("[[v:Q2.r0.amount]]", "取不回来"), + ("[[v:Q1.amount]]", "单元格引用格式无法识别"), + ("[[v:Q2.r0.amount]]", "无法读取"), ("[[v:Q1.r0.region|万]]", "不是数"), ("[[v:N:calc.total]]", CODE_REASON), - ("[[v:N:fetch.total]]", "后续版本"), + ("[[v:N:fetch.total]]", "不支持引用节点字段"), ]) def test_unresolvable_cells_say_why(catalog, marker, words): doc = compose_doc(f"值 {marker}。", catalog) @@ -192,6 +192,24 @@ def test_unresolvable_cells_say_why(catalog, marker, words): assert seg["state"] == "none" and seg["issue"] == "unresolved_ref" and seg["text"].startswith("⟦?v:") +def test_reasons_for_people_and_rewrite_instructions_for_the_writer_are_separate(catalog): + """解析不了的原因给人看(证据面板、出具横幅、节点报错),写法指令只交回写作者(模型)改写: + 「单元格要写成 Q<编号>.r<行>.<列>」这类话不上界面,也不存进文档。""" + from app.engine.evidence import describe_violations + + doc = compose_doc("值 [[v:Q1.amount]],另见 [[v:Q9.r0.amount]]。", catalog) + by_ref = {v["ref"]: v for v in doc["violations"] if v["code"] == "unresolved_ref"} + shape, missing = by_ref["v:Q1.amount"], by_ref["v:Q9.r0.amount"] + assert shape["message"] == "引用 [[v:Q1.amount]] 无法解析:单元格引用格式无法识别" + assert "Q<编号>.r<行>.<列>" in shape["for_model"] and "Q<编号>" not in shape["message"] + assert "查询结果 Q9 不存在" in missing["message"] and "证据目录" in missing["for_model"] + for seg in segs(doc): + assert "for_model" not in (seg.get("cite") or {}), "文档里只存给人看的原因" + assert "Q<编号>" not in str((seg.get("cite") or {}).get("reason") or "") + written = describe_violations(doc["violations"]) + assert "Q<编号>.r<行>.<列>" in written and "目录里没有 Q9" in written and "单元格引用格式无法识别" not in written + + def test_tampered_snapshot_is_refused(stored, tmp_path): """取回时复验哈希:工件文件被改过,单元格就解析不了,而不是把改过的数当真。""" path = artifact_store._path_of(stored["snap"]) @@ -200,7 +218,7 @@ def test_tampered_snapshot_is_refused(stored, tmp_path): path.write_text(original.replace("18230.5", "99999.5"), encoding="utf-8") catalog = build_catalog(nodes={}, ledger=[_query(stored["snap"], SNAP)]) doc = compose_doc("值 [[v:Q1.r0.amount]]", catalog) - assert "对不上" in bad(doc)["v:Q1.r0.amount"] + assert "与哈希不一致" in bad(doc)["v:Q1.r0.amount"] assert "99,999.5" not in doc["markdown"] finally: path.write_text(original, encoding="utf-8") @@ -252,10 +270,10 @@ def test_table_defaults_to_the_first_five_rows_and_all_columns(catalog): ("[[table:Q1 rows=5-9]]", "只有 7 行"), ("[[table:Q1 rows=3-1]]", "rows"), ("[[table:Q1 cols=region,gmv]]", "没有列「gmv」"), - ("[[table:Q1 limit=3]]", "不认识的选项"), - ("[[table:Q4]]", "cols="), + ("[[table:Q1 limit=3]]", "无法识别的选项"), + ("[[table:Q4]]", "超过整表上限"), ("[[table:Q5]]", "0 行"), - ("[[table:Q2]]", "取不回来"), + ("[[table:Q2]]", "无法读取"), ("[[table:K1]]", "不是查询结果"), ]) def test_table_problems_are_violations(catalog, marker, words): @@ -394,7 +412,7 @@ def test_catalog_prompt_shows_query_rows_and_how_to_cite(catalog): assert "Q1" in prompt and "region, amount, orders, note" in prompt assert "[[v:Q1.r0.amount]]" in prompt and "[[table:Q1" in prompt assert "r0" in prompt and "华东" in prompt and "18,230.5" in prompt - assert "Q2" in prompt and "取不回来" in prompt + assert "Q2" in prompt and "无法读取" in prompt refused = catalog_prompt(catalog, cells_allowed=False) assert "[[v:" not in refused and "[[see:Q1]]" in refused diff --git a/backend/tests/test_report_claims.py b/backend/tests/test_report_claims.py index 0dfd8f8b..3ad71153 100644 --- a/backend/tests/test_report_claims.py +++ b/backend/tests/test_report_claims.py @@ -148,7 +148,7 @@ async def test_other_values_are_refused(monkeypatch, value): lenient(monkeypatch) row = await finish(weekly(claims=value)) assert row.status == "failed", row.error - assert claims_problem(value) in row.error and "require_citation" in row.error + assert claims_problem(value) in row.error and "「计入缺口」" in row.error async def test_runs_from_before_the_upgrade_are_untouched(monkeypatch): diff --git a/backend/tests/test_report_judge.py b/backend/tests/test_report_judge.py index e5db6f89..aa7168f3 100644 --- a/backend/tests/test_report_judge.py +++ b/backend/tests/test_report_judge.py @@ -243,7 +243,7 @@ async def test_hitting_a_limit_is_reported_not_raised(monkeypatch): checked, doc, _ = await report_of(row.id) assert verdicts(doc)[CITED]["status"] == "supported", "先判挂了依据的" assert (verdicts(doc)[CAUSAL]["status"], verdicts(doc)[CAUSAL]["reason"]) == ("unjudged", "max_claims") - assert checked["judge"]["limits_hit"] == ["max_claims"] and "已到上限" in checked["judge"]["gaps"][0] + assert checked["judge"]["limits_hit"] == ["max_claims"] and "已达上限" in checked["judge"]["gaps"][0] assert CAUSAL not in models.judges[0] @@ -265,7 +265,7 @@ async def test_judging_yourself_is_called_out(monkeypatch): row = await finish(weekly(claims="judge")) assert row.status == "succeeded", row.error [warn] = [e.data for e in await events(row.id, "log") if e.data.get("code") == "judge_same_model"] - assert "mock-fast" in warn["message"] and "自己审自己" in warn["message"] + assert "mock-fast" in warn["message"] and "难以发现写作模型自身的错误" in warn["message"] # -------------------------------------------------------------------------- diff --git a/backend/tests/test_report_node.py b/backend/tests/test_report_node.py index 6d698055..bad7121d 100644 --- a/backend/tests/test_report_node.py +++ b/backend/tests/test_report_node.py @@ -386,7 +386,7 @@ async def test_numbers_the_contract_allows_are_not_repaired(monkeypatch): async def test_bad_on_violation_is_rejected(monkeypatch, value): script(monkeypatch, CLEAN) row = await finish(weekly({"on_violation": value})) - assert row.status == "failed" and "on_violation" in row.error + assert row.status == "failed" and "「重写后仍有违规时」" in row.error async def test_tool_markup_is_nudged_once(monkeypatch): diff --git a/backend/tests/test_report_schema.py b/backend/tests/test_report_schema.py index a3c01ed7..1c6bc211 100644 --- a/backend/tests/test_report_schema.py +++ b/backend/tests/test_report_schema.py @@ -59,7 +59,7 @@ def test_a_well_formed_report_graph_has_no_new_errors(): @pytest.mark.parametrize("metrics_from, words", [ (["nope"], ["nope", "不存在"]), - (["fetch"], ["fetch", "不是「口径卡」"]), + (["fetch"], ["「fetch」", "不是口径卡"]), ]) def test_metrics_from_must_name_a_caliber(metrics_from, words): found = issues(report_graph(metrics_from), "metrics_from") diff --git a/backend/tests/test_retrieval_quality.py b/backend/tests/test_retrieval_quality.py index 4a94a3d4..9d658cb0 100644 --- a/backend/tests/test_retrieval_quality.py +++ b/backend/tests/test_retrieval_quality.py @@ -408,7 +408,7 @@ async def test_each_kind_of_bad_reply_says_which_kind() -> None: cases = { '': 'token', # 空回复 '随便说点什么': 'scores', # 找不到 scores - '{"scores": [1, 2]}': '对不上', # 个数不符 + '{"scores": [1, 2]}': '数量不一致', # 个数不符 '{"scores": ["高", "低", "中"]}': '非数字', # 类型不对 } for reply, want in cases.items(): diff --git a/backend/tests/test_review.py b/backend/tests/test_review.py index 93938c0a..0b895435 100644 --- a/backend/tests/test_review.py +++ b/backend/tests/test_review.py @@ -110,8 +110,8 @@ def test_benign_warns_do_not_trigger_review(): 与结论无关的告警。轨迹里有记录就够了。 """ events = [ - warn("流式失败,回退非流式:connection reset", "stream_fallback"), - warn("节点要求 strict 隔离,但 microVM 未就绪,实际用了 seatbelt", "isolation_fallback"), + warn("流式输出失败,已改用非流式调用:connection reset", "stream_fallback"), + warn("节点要求 strict 隔离,但 microVM 未就绪,实际使用了 seatbelt", "isolation_fallback"), ] assert rv.scan(events, OK_OUTPUT) == [] diff --git a/backend/tests/test_run_races.py b/backend/tests/test_run_races.py index b8172d5c..6e89d179 100644 --- a/backend/tests/test_run_races.py +++ b/backend/tests/test_run_races.py @@ -276,7 +276,7 @@ async def test_an_approval_closed_just_before_it_is_marked_answered(slow, monkey event.listen(engine.sync_engine, "before_cursor_execute", abandon_first) try: - with pytest.raises(ValueError, match="已经处理过了|放弃"): + with pytest.raises(ValueError, match="已处理过|放弃"): await run_manager.resume(run.id, {"approved": True}) finally: event.remove(engine.sync_engine, "before_cursor_execute", abandon_first) diff --git a/backend/tests/test_run_timing.py b/backend/tests/test_run_timing.py index 67ea6c26..8295826d 100644 --- a/backend/tests/test_run_timing.py +++ b/backend/tests/test_run_timing.py @@ -301,4 +301,4 @@ async def test_node_skipped_says_which_node_by_name_not_just_id(): assert skipped.node_id == "bg" assert skipped.data.get("label") == "整理结果" assert skipped.data.get("node_type") == "transform" - assert "skip_if 成立" in skipped.data.get("reason", "") + assert "满足跳过条件" in skipped.data.get("reason", "") diff --git a/backend/tests/test_run_tool_precheck.py b/backend/tests/test_run_tool_precheck.py index 3a932e5b..8d25ea16 100644 --- a/backend/tests/test_run_tool_precheck.py +++ b/backend/tests/test_run_tool_precheck.py @@ -79,7 +79,7 @@ async def test_a_missing_datasource_tool_is_refused_and_named(client): body = res.json() assert body["code"] == "run_tool_missing" assert "「取数」" in body["detail"] and "db_query__nope" in body["detail"] - assert "去数据页接入,或在节点里重新选" in body["detail"] + assert "请到「数据」页接入,或在节点中重新选择" in body["detail"] async def test_every_missing_binding_is_listed(client): diff --git a/backend/tests/test_segment_missing_input.py b/backend/tests/test_segment_missing_input.py index 0930e0ec..bc77cc59 100644 --- a/backend/tests/test_segment_missing_input.py +++ b/backend/tests/test_segment_missing_input.py @@ -125,14 +125,14 @@ async def test_a_metric_missing_its_input_still_opens_its_chain(client, monkeypa assert query["step"] == "query" and query["artifact"] == end.data["query_artifact"] assert query["highlight"]["cells"] == [[0, "refunds"], [0, "orders"]] assert query["rows"] == [[300.5, 2, None]] - # 片段本身的说法不变:引用解析不了,缺输入 - assert "缺输入" in body["note"] and body["segment"]["cite"]["status"] == "unresolved" + # 片段本身的说法不变:引用无法解析,缺少输入 + assert "缺少输入" in body["note"] and body["segment"]["cite"]["status"] == "unresolved" async def test_a_wrong_reference_still_has_no_chain(client, monkeypatch): row, doc = await run_weekly(monkeypatch) body = await segment(client, row.id, seg_by_ref(doc, "m:nope")["id"]) - assert body["chain"] == [] and "目录里没有指标" in body["note"] + assert body["chain"] == [] and "引用的指标「nope」不存在" in body["note"] async def test_resolved_metrics_are_unchanged(client, monkeypatch): diff --git a/backend/tests/test_step_budget.py b/backend/tests/test_step_budget.py index ab1aaec0..0ceb496d 100644 --- a/backend/tests/test_step_budget.py +++ b/backend/tests/test_step_budget.py @@ -116,7 +116,7 @@ async def test_an_unguarded_cycle_still_stops_and_says_why(engine_up, monkeypatc edge("br", "out", "default")], }) assert row.status == "failed" - assert "走满了 12 步" in row.error and "loop 节点" in row.error, row.error + assert "已执行 12 步" in row.error and "「循环」节点" in row.error, row.error assert "recursion_limit" not in row.error @@ -160,5 +160,5 @@ async def test_an_unguarded_cycle_inside_a_subgraph_says_which_one(engine_up, mo } row = await _finish(await _parent_of(spinning, "空转的子图")) assert row.status == "failed" - assert "子图「空转的子图」走满了 12 步" in row.error, row.error + assert "子工作流「空转的子图」已执行 12 步" in row.error, row.error assert "recursion_limit" not in row.error diff --git a/backend/tests/test_supervisor.py b/backend/tests/test_supervisor.py index ae5b452f..41f4fedd 100644 --- a/backend/tests/test_supervisor.py +++ b/backend/tests/test_supervisor.py @@ -307,4 +307,4 @@ async def test_schedule_is_reported_for_the_ui(runner, monkeypatch): # 调度决策本身也要在事件流里,否则界面上这个节点就是个跑了 N 秒的黑盒 dispatches = [d["message"] for d in steps(events, "log") if d.get("round") is not None] - assert any("同时进行" in m for m in dispatches), dispatches + assert any("同时执行" in m for m in dispatches), dispatches diff --git a/backend/tests/test_tabular.py b/backend/tests/test_tabular.py index dd381d18..0a009f67 100644 --- a/backend/tests/test_tabular.py +++ b/backend/tests/test_tabular.py @@ -184,7 +184,7 @@ def test_unsupported_formats_say_what_to_do(tmp_path): db = tmp_path / "t.db" with pytest.raises(UnsupportedTable, match="另存为"): load_into(str(db), b"x", "old.xls") - with pytest.raises(UnsupportedTable, match="只认"): + with pytest.raises(UnsupportedTable, match="仅支持"): load_into(str(db), b"x", "a.pdf") @@ -281,7 +281,7 @@ async def test_upload_will_not_hijack_a_real_database(client): resp = await _upload(client, "tab_real", xlsx({"s": [["a"], [1]]})) assert resp.status_code == 409 - assert "换个名字" in resp.json()["detail"] + assert "请换一个名称" in resp.json()["detail"] def test_broken_excel_message_has_no_exception_class_name(): @@ -294,5 +294,5 @@ def test_broken_excel_message_has_no_exception_class_name(): with pytest.raises(UnsupportedTable) as info: read_tables(b"not really an xlsx", "orders.xlsx") text = str(info.value) - assert text.startswith("这个 Excel 读不开") + assert text.startswith("无法打开该 Excel 文件") assert "BadZipFile" not in text and "Error" not in text and "Exception" not in text diff --git a/backend/tests/test_team_exhausted.py b/backend/tests/test_team_exhausted.py index 0a31e293..7ed5b214 100644 --- a/backend/tests/test_team_exhausted.py +++ b/backend/tests/test_team_exhausted.py @@ -253,7 +253,7 @@ async def test_nobody_delivering_is_not_a_finished_team(monkeypatch): row, events = await _finish(_graph()) assert row.status == "failed", f"失败说明被当成了成果:{row.output}" assert row.error_node_id == "team" - assert "没有交出结论" in row.error and "查不到了,先这样" in row.error, row.error + assert "未交出结论" in row.error and "查不到了,先这样" in row.error, row.error # 失败的原因一起带上:界面照它说「模型没有真正调用工具」、指到画布上去绑工具 assert "工具调用的原始标记" in row.error, row.error assert "撰稿员" in row.error, "从没被派过的成员要点出来" @@ -265,7 +265,7 @@ async def test_nobody_delivering_fails_even_when_set_to_degrade(monkeypatch): _gives_up_after(monkeypatch, "核对员", writes={"复核": DSML, "结论": "不该轮到我"}) row, events = await _finish(_graph(on_exhausted="degrade")) assert row.status == "failed", f"失败说明被当成了成果:{row.output}" - assert "没有交出结论" in row.error and "用完" not in row.error, row.error + assert "未交出结论" in row.error and "用完" not in row.error, row.error assert not [e for e in events if e.data.get("code") == "team_exhausted"] diff --git a/backend/tests/test_tool_args.py b/backend/tests/test_tool_args.py index 6de884fe..b310098c 100644 --- a/backend/tests/test_tool_args.py +++ b/backend/tests/test_tool_args.py @@ -116,7 +116,7 @@ def test_every_problem_is_reported_at_once() -> None: with pytest.raises(ToolArgsError) as e: prepare_args(_QueryLike, {"query": "SELECT 1", "limit": "很多"}) text = str(e.value) - assert "query 不是它的参数" in text + assert "query 不是该工具的参数" in text assert "limit 的值不合法" in text @@ -125,7 +125,7 @@ def test_the_message_is_a_whole_sentence() -> None: for args in ({}, {"foo": 1, "bar": 2}, {"sql": "SELECT 1", "limit": "很多"}): with pytest.raises(ToolArgsError) as e: prepare_args(_QueryLike, args) - assert str(e.value).startswith("参数不对:") + assert str(e.value).startswith("参数有误:") # -------------------------------------------------------------------------- diff --git a/backend/tests/test_tool_deadline.py b/backend/tests/test_tool_deadline.py index cebdc71a..c1713067 100644 --- a/backend/tests/test_tool_deadline.py +++ b/backend/tests/test_tool_deadline.py @@ -148,7 +148,7 @@ async def test_an_agent_gets_control_back_when_the_limit_is_reached(monkeypatch) f"时限 {LIMIT}s,却等到了驱动收尾:{end['duration_ms']}ms" assert end.get("timed_out") is True, end # 模型要知道是超时、超了多久,才会去缩小查询范围 - assert seen and "0.3" in seen[0] and "放弃" in seen[0], seen + assert seen and "0.3" in seen[0] and "停止等待" in seen[0], seen async def test_a_tool_node_reports_the_real_limit(monkeypatch): @@ -160,7 +160,7 @@ async def test_a_tool_node_reports_the_real_limit(monkeypatch): node("out", "output", fields=[]), )) assert row.status == "failed" - assert "0.3" in (row.error or "") and "放弃" in (row.error or ""), row.error + assert "0.3" in (row.error or "") and "停止等待" in (row.error or ""), row.error start = next(e.data for e in events if e.type == "tool.start") assert start["timeout_s"] == LIMIT err = next(e.data for e in events if e.type == "tool.error") @@ -245,7 +245,7 @@ async def test_a_slow_query_is_abandoned_on_time(slow_source, monkeypatch): assert start["timeout_s"] == 1, start end = next(e.data for e in events if e.type in ("tool.end", "tool.error")) assert end["duration_ms"] < 3000, f"1s 的查询时限等了 {end['duration_ms']}ms" - assert "1s" in end["preview"], end + assert "1 秒" in end["preview"], end def test_where_each_limit_comes_from(): diff --git a/backend/tests/test_tool_evidence.py b/backend/tests/test_tool_evidence.py index c122f891..f98fde94 100644 --- a/backend/tests/test_tool_evidence.py +++ b/backend/tests/test_tool_evidence.py @@ -127,7 +127,7 @@ def test_cell_reads_json_text_and_objects(): ((PAYLOAD, 2, "gmv"), "只有 2 行"), ((PAYLOAD, 0, "amount"), "没有列「amount」"), ((PAYLOAD, 0, 5), "只有 2 列"), - ((PAYLOAD, -1, "gmv"), "从 0 数"), + ((PAYLOAD, -1, "gmv"), "从 0 开始"), ((PAYLOAD, True, "gmv"), "整数"), (("查询失败:no such table: orders", 0, "gmv"), "查询失败:no such table: orders"), (({"columns": ["gmv"], "rows": []}, 0, "gmv"), "0 行"), @@ -372,7 +372,7 @@ async def test_cell_out_of_range_fails_the_card_readably(engine_up, shop): card = node("card", "metrics", metrics=[{"id": "x", "expression": "cell(nodes.fetch, 3, 'gmv')"}]) row = await finish(fetch_graph(card)) assert row.status == "failed" - assert "cell() 要第 3 行,但这份查询结果只有 1 行" in (row.error or ""), row.error + assert "cell() 请求第 3 行,但查询结果只有 1 行" in (row.error or ""), row.error # -------------------------------------------------------------------------- diff --git a/backend/tests/test_tool_trust.py b/backend/tests/test_tool_trust.py index fa6468c0..bcdb28ce 100644 --- a/backend/tests/test_tool_trust.py +++ b/backend/tests/test_tool_trust.py @@ -204,7 +204,7 @@ def test_always_button_only_where_it_takes_effect(): @pytest.mark.parametrize("text, expected", [ ('{"verdict": "allow", "reason": "只读"}', (True, "只读")), ('好的:{"verdict":"escalate","reason":"要删数据"}', (False, "要删数据")), - ('{"verdict": "allow"}', (True, "(门控没写理由)")), + ('{"verdict": "allow"}', (True, "(门控未说明理由)")), ('{"verdict": "yes"}', None), ("放行", None), ("", None), @@ -326,7 +326,7 @@ async def test_gate_that_crashes_hands_over_to_a_person(crm, monkeypatch): run = await wait(await start(agent_graph())) assert run.status == "interrupted" [gated] = await events(run.id, "tool.gated") - assert gated.data["verdict"] == "escalate" and "门控模型没答上来" in gated.data["reason"] + assert gated.data["verdict"] == "escalate" and "门控模型未给出判断" in gated.data["reason"] async def test_gate_verdict_is_not_asked_again_when_the_node_replays(crm, monkeypatch): @@ -488,7 +488,7 @@ async def test_team_member_gate_escalation_is_not_executed(crm, monkeypatch): assert run.status == "succeeded", run.error assert crm == [] ends = [e.data.get("preview", "") for e in await events(run.id, "tool.end")] - assert any("门控模型没有放行(拿不准)" in p for p in ends), ends + assert any("门控模型未批准(拿不准)" in p for p in ends), ends async def _set(key: str, level: str) -> None: diff --git a/backend/tests/test_transform_json_error.py b/backend/tests/test_transform_json_error.py index 7c6999a3..e0b90f5f 100644 --- a/backend/tests/test_transform_json_error.py +++ b/backend/tests/test_transform_json_error.py @@ -24,7 +24,7 @@ from app.engine.schema import GraphSpec, validate_graph #: 「他说"好的"」:字符串里的英文引号没转义,json.loads 在「好」那里要逗号 BAD = '{"summary": "他说"好的"然后走了", "count": 3}' -TEMPLATE_HINT = "检查模板里的引号、逗号,字符串值要用 | json 过滤器输出" +TEMPLATE_HINT = "请检查模板中的引号和逗号,字符串值需使用 | json 过滤器输出" @pytest.fixture(autouse=True) @@ -91,7 +91,7 @@ async def test_unescaped_quotes_in_model_text_blame_the_upstream(monkeypatch, te assert error.startswith("上游「查询日志」输出的不是合法 JSON"), error assert "第 17 列附近" in error, error # 在上游那段文字里的位置,不是在整段模板里的 - assert "没转义的英文引号" in error and "output_schema + cite_fields" in error + assert "未转义的英文引号" in error and "「按出处核对字段」" in error assert TEMPLATE_HINT not in error and "| json" not in error # 原文只进技术细节:首行不带模型写的内容 assert "他说" not in error @@ -179,14 +179,14 @@ async def test_a_missing_comma_next_to_valid_model_json_keeps_the_template_hint( async def test_a_json_filtered_value_wrapped_in_quotes_says_to_drop_the_quotes(monkeypatch): script(monkeypatch, "好的") error = template_error(await failure(weekly('{"summary": "{{ nodes.query_logs.text | json }}"}'))) - assert "{{ nodes.query_logs.text | json }} 出来的已经是合法的 JSON(文字自带引号)" in error, error + assert "{{ nodes.query_logs.text | json }} 的结果已是合法的 JSON(文字自带引号)" in error, error assert error.endswith("外面不要再加引号"), error async def test_an_empty_value_in_a_value_slot_names_the_span(monkeypatch): script(monkeypatch, "好的") error = template_error(await failure(weekly('{"summary": {{ input.missing }} , "n": 1}'))) - assert "{{ input.missing }} 取出来是空的" in error, error + assert "{{ input.missing }} 的取值为空" in error, error async def test_plain_text_that_is_not_from_a_model_also_gets_the_json_filter_hint(monkeypatch): @@ -196,7 +196,7 @@ async def test_plain_text_that_is_not_from_a_model_also_gets_the_json_filter_hin @pytest.mark.parametrize("text, reason", [ - ('{"week": "2026-W37", "rows": [1, 2', "没有收尾"), + ('{"week": "2026-W37", "rows": [1, 2', "不完整"), ('```json\n{"gmv": 1}\n```', "代码块"), ("好的,本周销售额是 5 万", "一段文字"), ]) @@ -205,7 +205,7 @@ async def test_model_text_parsed_as_a_whole_says_what_is_wrong_with_it(monkeypat script(monkeypatch, text) error = (await failure(weekly("{{ nodes.query_logs.text }}"))).data["error"] assert error.startswith("上游「查询日志」输出的不是合法 JSON"), error - assert reason in error and "没转义的英文引号" not in error and "output_schema" in error, error + assert reason in error and "未转义的英文引号" not in error and "「结构化输出 Schema」" in error, error # -------------------------------------------------------------------------- @@ -215,7 +215,7 @@ async def test_model_text_parsed_as_a_whole_says_what_is_wrong_with_it(monkeypat def warnings_of(graph, node_id="parse"): return [i for i in validate_graph(GraphSpec.model_validate(graph)).issues - if i.node_id == node_id and "cite_fields" in i.message] + if i.node_id == node_id and "按出处核对字段" in i.message] CARD = node("card", "metrics", "口径卡", caliber="周报口径", metrics=[{"id": "gmv", "expression": "vars.q.gmv"}]) @@ -236,7 +236,7 @@ def agent_graph(template, *, parse_mode="json", after=(CARD,), **agent): def test_validate_warns_when_a_transform_parses_agent_text_into_a_caliber(): [issue] = warnings_of(agent_graph("{{ nodes.query_logs.text }}")) assert issue.level == "warning" and issue.field == "template" - assert "「查询日志」" in issue.message and "output_schema" in issue.message + assert "「查询日志」" in issue.message and "「结构化输出 Schema」" in issue.message # 按 JSON 解析的,不经过口径卡也要说 assert warnings_of(agent_graph("{{ vars.answer }}", after=())) # 表达式模式读文字、流向口径卡 @@ -266,6 +266,6 @@ def test_validate_points_quoted_model_text_at_the_json_filter(): if i.node_id == "parse" and "| json" in i.message] assert issue.level == "warning" and issue.field == "template" assert "{{ nodes.query_logs.text | json }}" in issue.message and "外面不要再加引号" in issue.message - assert "cite_fields" not in issue.message and "「查询日志」" in issue.message + assert "按出处核对字段" not in issue.message and "「查询日志」" in issue.message # 值的位置、整段解析:仍然指向结构化输出 assert warnings_of(agent_graph('{"summary": {{ nodes.query_logs.text }}}', after=())) diff --git a/backend/tests/test_upgrade_assist.py b/backend/tests/test_upgrade_assist.py index 7e37b342..f0ac4351 100644 --- a/backend/tests/test_upgrade_assist.py +++ b/backend/tests/test_upgrade_assist.py @@ -119,7 +119,7 @@ async def test_a_pure_arithmetic_rewrite_is_adopted_as_a_preview(client, monkeyp assert [c for c in body["changes"] if c["rule"] == "assist"] == [ {"fix_id": "assist", "rule": "assist", "node_id": "card", "node_title": "口径卡", "field": "metrics", "before": graph()["nodes"][3]["data"]["config"]["metrics"], "after": REWRITE["config"]["metrics"], - "label": "Copilot 的修改"}] + "label": "助手的修改"}] assert body["ops"][-1] == REWRITE assert not [n for n in body["notes"] if n["rule"] == "R5"] # 口径卡不再读它,建议随之作废 assert await rows() == before # 只是预览 @@ -165,7 +165,7 @@ async def test_non_arithmetic_code_is_kept_with_a_warning(client, monkeypatch): assert body["assist"]["ok"] is True and body["applied"] == [] assert body["assist"]["questions"] == ["「算比率」:它读了一个文件,像是在取数,请确认"] [warning] = body["assist"]["warnings"] - assert "算比率" in warning and "evidence_role" in warning and "口径卡" in warning + assert "算比率" in warning and "「证据角色」" in warning and "口径卡" in warning assert body["graph"] == graph() assert [n["node_id"] for n in body["notes"] if n["rule"] == "R5"] == ["calc"] @@ -176,7 +176,7 @@ async def test_nothing_to_rewrite_means_no_model_call(client, monkeypatch): model = script(monkeypatch, wrap(REWRITE)) body = await upgrade(client, g) assert model.calls == [] and body["assist"]["ok"] is True and body["assist"]["warnings"] == [] - assert "没有要交给 Copilot 改写的" in body["assist"]["summary"] + assert "无需交给助手改写" in body["assist"]["summary"] async def test_a_new_error_is_sent_back_once_and_fixed(client, monkeypatch): @@ -199,7 +199,7 @@ async def test_a_rewrite_that_stays_broken_is_refused(client, monkeypatch): assert len(model.calls) == 3 # 最多交回去改两轮 assert body["assist"]["ok"] is False and "assist" not in body["applied"] [rejected] = [r for r in body["rejected"] if r["fix_id"] == "assist"] - assert "变糟" in rejected["reason"] + assert "未能改善工作流" in rejected["reason"] assert by_id(body["graph"])["card"]["data"]["config"]["metrics"][0]["expression"] == "vars.calc.ratio" @@ -207,7 +207,7 @@ async def test_marking_the_code_as_a_source_is_not_the_copilots_call(client, mon script(monkeypatch, wrap({"op": "update_node", "id": "calc", "config": {"evidence_role": "source"}})) body = await upgrade(client, graph()) [rejected] = [r for r in body["rejected"] if r["fix_id"] == "assist"] - assert "source" in rejected["reason"] and body["graph"] == graph() + assert "「取数」" in rejected["reason"] and body["graph"] == graph() async def test_without_assist_there_is_no_model_call(client, monkeypatch): diff --git a/backend/tests/test_upgrade_evidence.py b/backend/tests/test_upgrade_evidence.py index bbb3e402..2bca4280 100644 --- a/backend/tests/test_upgrade_evidence.py +++ b/backend/tests/test_upgrade_evidence.py @@ -225,7 +225,7 @@ def test_r3_inserts_a_report_between_the_agent_and_the_exit(): rewire = next(ch for ch in out["changes"] if ch["field"] == "edge" and ch["before"]) assert rewire["before"] == {"source": "ask", "target": "out"} and rewire["after"] == {"source": rid, "target": "out"} assert "contract" not in cfg(g, "out") # 契约(和 cells)要人拿主意,不替人加 - assert any("cells" in n["text"] for n in out["notes"]) + assert any("单元格引用" in n["text"] for n in out["notes"]) def test_r3_skips_agents_that_only_read_table_structures(): @@ -247,7 +247,7 @@ def test_r5_only_suggests_marking_the_code_node_as_a_source(): out = upgrade_for_evidence(before) assert out["graph"] == before and out["changes"] == [] [note] = [n for n in out["notes"] if n["rule"] == "R5"] - assert note["node_id"] == "calc" and "source" in note["text"] + assert note["node_id"] == "calc" and "「取数」" in note["text"] assert infos(before) == [] # 只有 R5 的不算「旧结构」 @@ -364,7 +364,7 @@ def test_r3_rewires_the_direct_exit_and_explains_the_indirect_one_whatever_the_n assert cfg(g, "out")["fields"] == [{"name": "answer", "value": f"{{{{ nodes.{rid}.text }}}}"}] assert cfg(g, "out2") == cfg(graph, "out2") # 经过别的节点的出口不替人改 [skipped] = [n for n in out["notes"] if n["rule"] == "R3" and n["level"] == "warning"] - assert "转述" in skipped["text"] and "经过别的节点" in skipped["text"] + assert "转述" in skipped["text"] and "经过其他节点" in skipped["text"] assert infos(graph) and infos(g) == [] again = upgrade_for_evidence(g) assert again["changes"] == [] and again["graph"] == g @@ -404,7 +404,7 @@ def test_an_unset_report_from_is_dropped_when_r3_converts_the_narrative(): def cells_notes(out: dict) -> list: - return [n for n in out["notes"] if n["rule"] == "R3" and "cells: true" in n["text"]] + return [n for n in out["notes"] if n["rule"] == "R3" and "「单元格引用」" in n["text"]] def test_r3_warns_that_governed_formal_runs_fail_without_cells(): @@ -450,7 +450,7 @@ def test_deleting_a_node_is_refused(): before = narrative_graph() after = copy.deepcopy(before) after["nodes"] = [n for n in after["nodes"] if n["id"] != "fetch"] - assert any("删了节点" in r for r in forbidden(before, after)) + assert any("删除了节点" in r for r in forbidden(before, after)) def test_llm_to_report_is_allowed_only_for_the_node_the_upgrade_names(): @@ -469,14 +469,14 @@ def test_only_the_rewired_edge_may_go(): after = copy.deepcopy(before) after["edges"] = [e for e in after["edges"] if (e["source"], e["target"]) != ("ask", "out")] assert forbidden(before, after, rewired={("ask", "out")}) == [] - assert any("删了连线" in r for r in forbidden(before, after)) + assert any("删除了连线" in r for r in forbidden(before, after)) after["edges"] = [] - assert any("start → ask" in r for r in forbidden(before, after, rewired={("ask", "out")})) + assert any("「问题」→「查数作答」" in r for r in forbidden(before, after, rewired={("ask", "out")})) @pytest.mark.parametrize("damage, word", [ (lambda g: cfg(g, "done").pop("contract"), "契约"), - (lambda g: cfg(g, "done")["contract"].update(required=[]), "required"), + (lambda g: cfg(g, "done")["contract"].update(required=[]), "必需指标"), (lambda g: cfg(g, "done")["contract"].update(strict=True), None), ]) def test_contract_rules_are_the_publish_fix_rules(damage, word): @@ -497,7 +497,7 @@ def test_strict_off_and_looser_approval_are_refused(): cfg(after, "ask")["approval"] = "never" cfg(after, "fin")["contract"]["strict"] = False reasons = forbidden(before, after) - assert any("全部自动放行" in r for r in reasons) and any("strict" in r for r in reasons) + assert any("全部无需审批" in r for r in reasons) and any("严格模式" in r for r in reasons) # -------------------------------------------------------------------------- @@ -582,7 +582,7 @@ async def test_the_endpoint_explains_an_unreadable_graph(client): r = await client.post("/api/copilot/upgrade-evidence", json={"graph": {"nodes": [{"id": "bad id!", "type": "llm"}]}}) assert r.status_code == 200 body = r.json() - assert body["changes"] == [] and body["issues"][0]["level"] == "error" and "读不懂" in body["issues"][0]["message"] + assert body["changes"] == [] and body["issues"][0]["level"] == "error" and "无法解析" in body["issues"][0]["message"] async def test_the_endpoint_rejects_an_unknown_level(client): diff --git a/backend/tests/test_validation_text.py b/backend/tests/test_validation_text.py index 14b2dc72..b17fe80b 100644 --- a/backend/tests/test_validation_text.py +++ b/backend/tests/test_validation_text.py @@ -100,7 +100,7 @@ def test_governance_speaks_the_ui_vocabulary(): for internal in ("supervisor", "approval=never", "llm 节点", "contract"): assert internal not in text, f"门禁文案里还有内部词 {internal!r}:{text}" assert "「协作团队」" in text and "多 Agent 协作" in text - assert "审批策略" in text and "全部自动放行" in text + assert "审批策略" in text and "全部无需审批" in text assert "模型调用" in text assert "出具契约" in text diff --git a/backend/tests/test_variables.py b/backend/tests/test_variables.py index 2ee38f67..cfea3959 100644 --- a/backend/tests/test_variables.py +++ b/backend/tests/test_variables.py @@ -272,7 +272,7 @@ def test_no_false_ordering_warning_inside_the_loop_body() -> None: 而那正是循环最正常的写法。 """ report = analyze(_loop_graph()) - assert not [i for i in report.issues if "在这之后才跑" in i.message], \ + assert not [i for i in report.issues if "在这之后才执行" in i.message], \ [i.message for i in report.issues] diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0c617c95..0167cf3b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -244,13 +244,13 @@ function Nav({ stalled }: { stalled: CatalogCheck[] }) {