Files
AgentLab/backend/app/api/governance.py
T
ThearchyHelios 03c18c4d78 界面文案整改:口语改书面、术语统一、不再露出实现细节;修掉几处说错的提示;新增文案检查防回潮
一、文案(前端约 1600 处,后端传到界面的约 880 处)
- 术语统一:工作流层面用「运行」(继续运行、重新运行、试运行),节点和工具层面用「执行」,不再用「跑」;
  总时长 / 执行时长 / 等待审批;服务端;助手;Agent;token;工作流;固定版本;模型接入;系统提示;批准 / 驳回;受管级别
- 口语改书面:取不到、没取回来、读不懂、连不上、多半、照样、兜底、揉成这类说法改成「无法 / 未能 / 失败 / 请」;去掉拟人写法
- 不再露出实现细节:界面上不写 checkpoint、同一拍、哈希(凭证处除外),不写改版历史(「以前…」「老数据」);
  报错、校验、门禁、自动修复里裸写的配置键名和枚举值换成界面上的中文标签,由新的 backend/app/engine/labels.py 统一提供;
  发布弹窗里结论句的选项不再是 off / require_citation
- 同一件事只留一种说法:生成阶段文案、出具档位说明、画布锁定提示各合成一份
- 去掉界面上的工业场景示例(MES、ERP、「张工」「王工」)和真实产品名,换成通用示例

二、说错的提示(都有测试证明)
- 数据库测连接失败时的专用提示以前从不出现(按报错文字全等比较,永远比不上):改为按错误类型判断,不再拼出重复的前缀
- 「设置 → 供应商」改指「设置 → 模型接入」;「在设置里建数据源」改指「数据」页
- 缺少 API Key、模型接入已停用的报错不再夹英文,写明去哪里填
- 两处原因说错(「这种引用在后续版本支持」「这一版还不支持」)改成真实原因
- 节点说明里不准确的说法改正:代码节点在 microVM 或系统沙箱中执行;报告撰写、口径卡的说明不再说过头
- 导出的证据 CSV 里两列同名,第三列改为「片段编号」

三、前后端对齐
- 前端按后端原文识别日志、报错的地方,新旧两种写法都认得(历史运行里存的是旧文字),逐条补了新旧原文的核对
- 后端交回模型的原指令放进单独的 for_model 字段,前端在解析响应时去掉,不会显示到界面上

四、检查
- 检查脚本里按原文匹配的断言改成新文案;改完会变成永远成立的反向断言逐条修正,并做了变异验证
- 新增 check-copy(静态扫描前端界面字符串和后端上界面的文案):再出现「跑」「后端」「多半」「令牌」、
  界面上的 Copilot、裸写的配置键名、半角标点等就报错;确需保留的写进 scripts/copy-allow.json 并注明理由
2026-09-30 08:05:15 +08:00

152 lines
5.4 KiB
Python

from __future__ import annotations
import json
from collections import defaultdict
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.base import get_session
from app.db.models import Run, RunEvent, Workflow
from app.engine.schema import GraphSpec, NodeType
router = APIRouter(prefix="/api/governance", tags=["governance"])
@router.get("/tool-usage")
async def tool_usage(
workflow_id: str,
limit_runs: int = Query(default=100, le=500),
session: AsyncSession = Depends(get_session),
) -> dict[str, Any]:
"""工具白名单衰减报表。
关节层最可能的退化方式不是模板太死,而是白名单为了长尾一个个放宽,
半年后等于没有白名单。这份报表把"授了权但从来没用过"的工具摆到台面上,
放宽才能被定期回收。
"""
workflow = await session.get(Workflow, workflow_id)
if not workflow:
raise HTTPException(404, "工作流不存在,可能已被删除")
spec = GraphSpec.model_validate(workflow.graph)
# 各节点声明的白名单
granted: dict[str, list[str]] = {}
for node in spec.nodes:
if node.type == NodeType.AGENT:
granted[node.id] = list(node.config.get("tools") or [])
elif node.type == NodeType.TOOL and node.config.get("tool"):
granted[node.id] = [node.config["tool"]]
elif node.type == NodeType.SUPERVISOR:
merged: list[str] = []
for agent in node.config.get("agents") or []:
merged.extend(agent.get("tools") or [])
granted[node.id] = sorted(set(merged))
run_ids = [
rid
for (rid,) in await session.execute(
select(Run.id)
.where(Run.workflow_id == workflow_id)
.order_by(Run.created_at.desc())
.limit(limit_runs)
)
]
usage: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
if run_ids:
rows = await session.execute(
select(RunEvent.node_id, RunEvent.data).where(
RunEvent.run_id.in_(run_ids), RunEvent.type == "tool.start"
)
)
for node_id, data in rows:
tool = (data or {}).get("tool")
if node_id and tool:
# supervisor 内部子 agent 的 node_id 形如 "team:researcher"
usage[node_id.split(":")[0]][tool] += 1
report = []
for node_id, tools in granted.items():
used = usage.get(node_id, {})
report.append(
{
"node_id": node_id,
"granted": tools,
"used": dict(used),
"unused": [t for t in tools if not used.get(t)],
"ungrated_but_used": [t for t in used if t not in tools],
}
)
return {
"workflow_id": workflow_id,
"runs_considered": len(run_ids),
"nodes": report,
"hint": "授权后多次运行都未使用的工具说明授权范围偏宽,建议从节点中移除",
}
@router.get("/exploratory-clusters")
async def exploratory_clusters(
limit: int = Query(default=200, le=500),
threshold: float = Query(default=0.62, ge=0.3, le=0.95),
session: AsyncSession = Depends(get_session),
) -> dict[str, Any]:
"""探索性问题聚类:同一个问题被反复问,就该长成模板里的固定一节。
这就是模板生长的触发器。用本地 embedding 做贪心聚类,
出现 ≥3 次的簇标记为晋升候选。
"""
from app.memory.embeddings import cosine, embed_texts
rows = list(
await session.execute(
select(Run.id, Run.input, Run.workflow_name, Run.created_at)
.where(Run.run_class != "formal")
.order_by(Run.created_at.desc())
.limit(limit)
)
)
items = []
for rid, input_payload, wf_name, created in rows:
text = json.dumps(input_payload or {}, ensure_ascii=False, sort_keys=True)
if len(text) <= 4: # 空输入没有聚类意义
continue
items.append({"run_id": rid, "text": text, "workflow": wf_name,
"at": created.isoformat() if created else None})
if not items:
return {"clusters": [], "considered": 0}
vectors = await embed_texts([i["text"] for i in items])
clusters: list[dict[str, Any]] = []
for i, item in enumerate(items):
placed = False
for cluster in clusters:
if cosine(vectors[i], vectors[cluster["seed"]]) >= threshold:
cluster["members"].append(item)
placed = True
break
if not placed:
clusters.append({"seed": i, "members": [item]})
out = [
{
"count": len(c["members"]),
"representative": c["members"][0]["text"][:200],
"workflow": c["members"][0]["workflow"],
"run_ids": [m["run_id"] for m in c["members"]][:20],
"first_at": c["members"][-1]["at"],
"last_at": c["members"][0]["at"],
"promote_candidate": len(c["members"]) >= 3,
}
for c in clusters
if len(c["members"]) >= 2
]
out.sort(key=lambda c: c["count"], reverse=True)
return {
"clusters": out,
"considered": len(items),
"hint": "被标记为可固化的问题反复出现,建议用「提取模板」把它固定为工作流中的一步",
}