mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-23 19:02:00 +00:00
第三波前两批:六个「看着成功其实没干活」的平台漏洞堵上,记录页能回放,管理页与画布收尾
起因是一次探索运行:Copilot 改节点时把工具绑定整份抹掉,agent 没有工具只能写「假设调用」, 校验节点的自动修复编出 total_count=0 让 schema 通过,协作成员把工具调用标记当文字输出了四轮, 轮数用完后节点把原话当成功结果交出去——运行标成已完成,数据库一次都没查。 平台可信度(先写失败测试) - Copilot 修改节点改为合并:没写的字段保留,null 才删除;协作成员按名字合并。前后端同一套规则, 工具集合变小时自查报警、改图回执列出变化 - 新校验规则:提示词点名了某个工具而节点没有绑定它,判错误,Copilot 自查会交回去修 - 校验修复只许改格式:冒出原文没有的值就判修复无效;修复这次模型调用计入用量 - 识别模型把工具调用写成文字的情况(DSML、<tool_call> 等标记):纠正一次,仍然如此就判失败并说明原因 - 协作团队用完轮数不再按成功交付:默认失败,可选降档,点出一次都没派到的成员 - 审批恢复后,同一节点里已经执行过的工具调用复用结果,不再重复执行 后端 - 查询时限交给数据库执行(Oracle call_timeout、PG statement_timeout、MySQL max_execution_time、 SQLite progress handler),可按数据源配置;超时报错与实际耗时一致 - 等审批的运行可以真正取消;会话列表带最后一轮状态;测连接结果持久化;探查结构可只看不存; 自定义工具可草稿试跑、写坏的参数定义保存时拒绝;MCP 服务改动后作废旧工具缓存; 检索命中带贡献分解;重建索引在后台跑并报进度;报错统一收进 core/errors 前端 - 公共层:管理页共用件、失败说明(lib/explain)、健康状态进公共库;目录按表各自加载并有超时, 一张表卡住不再拖垮整站;上传显示真实字节进度;离线横幅只播报不变的句子 - 画布:卡片只说游标所在的那一次执行;等审批时可放弃运行;团队收尾判定与未完成说清楚; 回放用量取那一刻的值 - 编排页:Copilot 合并语义与工具变化回执;「用完轮数时」选项;正式运行期间锁住所有改图入口 - 回答流 / 问数据:新失败类型说人话并给下一步;画布与右栏互相定位;数据源范围、回收站、重新核对 - 记录页:「航迹」页签复用画布时间轴,可拖动回放、列出关键时刻;列表行带执行 / 等人 / 失败缩略条 - 外壳:统一的离开前确认(data router),导航、⌘K、快捷键、后退都会先问 验证(沙箱):tsc 干净,pytest 838 passed(两遍),14 个检查脚本中 13 个全绿; check-ui 余 1 项旧断言(按旧日期格式找运行行),3c 更新。
This commit is contained in:
@@ -8,9 +8,9 @@ from typing import Any, Awaitable, Callable
|
||||
from langgraph.errors import GraphBubbleUp
|
||||
from langgraph.graph import END, START, StateGraph
|
||||
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType
|
||||
from app.engine.context import NodeContext, NodeError, RunContext
|
||||
from app.engine.errors import describe_exception, raw_detail
|
||||
from app.engine.nodes import control, human, io, knowledge, llm, metrics, multi, tools
|
||||
from app.engine.schema import GraphNode, GraphSpec, NodeType, back_edges, innermost_loops
|
||||
from app.engine.state import GraphState
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
"""把异常翻成给人看的一句话。
|
||||
|
||||
界面上出现过的原样报错:「工具 db_query__shop 执行失败:_make_query_tool.<locals>._run()
|
||||
got an unexpected keyword argument 'query'」「TypeError: Integer exceeds 64-bit range」。
|
||||
问数据的业务用户读不懂这些,也不知道下一步该做什么。
|
||||
|
||||
这里只管"原因"那半句,不带异常类名和内部符号;"发生了什么"和"怎么办"由调用方
|
||||
按场景拼。原始异常另外放进事件的 detail 字段、写进日志,排查的人照样拿得到。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
# 供应商 SDK / httpx 的网络类异常。按类名认而不 import:这些包不一定都装了,
|
||||
# 而这里只需要知道"是不是连不上"
|
||||
_NETWORK = {"ConnectError", "ConnectTimeout", "APIConnectionError", "RemoteProtocolError",
|
||||
"ReadError", "NetworkError"}
|
||||
_TIMEOUT = {"ReadTimeout", "WriteTimeout", "PoolTimeout", "APITimeoutError", "TimeoutException"}
|
||||
|
||||
# 内部符号:`a.b.<locals>._run()`、`<function f at 0x…>`、模块路径。对使用者没有意义
|
||||
_LOCALS = re.compile(r"[\w.]*<locals>\.?[\w.]*(\(\))?")
|
||||
_REPR = re.compile(r"<(?:function|bound method|coroutine|object) [^>]*>")
|
||||
# 包在消息里的异常类名("连不上:ConnectError: All connection attempts failed")
|
||||
_CLASS = re.compile(r"\b[A-Z]\w*(?:Error|Exception|Warning)\b:\s*")
|
||||
|
||||
|
||||
def _names(exc: BaseException) -> set[str]:
|
||||
return {cls.__name__ for cls in type(exc).__mro__}
|
||||
|
||||
|
||||
def _scrub(text: str) -> str:
|
||||
text = _LOCALS.sub("内部函数", text)
|
||||
text = _REPR.sub("内部对象", text)
|
||||
text = _CLASS.sub("", text)
|
||||
return " ".join(text.split())[:240]
|
||||
|
||||
|
||||
def describe_exception(exc: BaseException) -> str:
|
||||
"""原因,一句话。常见的几类写成固定说法,其余的去掉内部符号后照实说。"""
|
||||
names = _names(exc)
|
||||
text = str(exc).strip()
|
||||
|
||||
status = getattr(exc, "status_code", None)
|
||||
if isinstance(status, int):
|
||||
if status in (401, 403):
|
||||
return f"鉴权没通过({status}):key 无效、过期,或没有这个模型的权限"
|
||||
if status == 429:
|
||||
return "请求太频繁,或者额度用完了(429)"
|
||||
if status >= 500:
|
||||
return f"对方服务出错了({status}),多半是暂时的"
|
||||
|
||||
if isinstance(exc, TypeError):
|
||||
if m := re.search(r"unexpected keyword argument '(\w+)'", text):
|
||||
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}」"
|
||||
if isinstance(exc, TimeoutError) or names & _TIMEOUT:
|
||||
return "等待超时:对方没有在限定时间内响应"
|
||||
if isinstance(exc, ConnectionError) or names & _NETWORK:
|
||||
return "连不上对方服务:网络不通,或者服务没有启动"
|
||||
if isinstance(exc, PermissionError):
|
||||
return "没有权限访问需要的文件或资源"
|
||||
if isinstance(exc, FileNotFoundError):
|
||||
return f"找不到文件{'「' + str(exc.filename) + '」' if exc.filename else ''}"
|
||||
if isinstance(exc, json.JSONDecodeError):
|
||||
return "返回的内容不是合法的 JSON"
|
||||
if isinstance(exc, KeyError):
|
||||
return f"缺少字段「{exc.args[0] if exc.args else '?'}」"
|
||||
if isinstance(exc, (OverflowError, MemoryError)):
|
||||
return f"数据超出了能处理的范围{':' + _scrub(text) if text else ''}"
|
||||
return _scrub(text) or "没有给出原因的内部错误"
|
||||
|
||||
|
||||
def raw_detail(exc: BaseException | None) -> str | None:
|
||||
"""原始异常,给排查的人看。只进事件的 detail 字段和日志,不进首行报错。"""
|
||||
if exc is None:
|
||||
return None
|
||||
text = str(exc).strip()
|
||||
return f"{type(exc).__name__}: {text}"[:2000] if text else type(exc).__name__
|
||||
@@ -1,15 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from langgraph.types import interrupt
|
||||
|
||||
from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.engine.approval import read_decision
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.state import GraphState, message_text, template_context
|
||||
from app.engine.replay import ask, once
|
||||
from app.engine.state import GraphState, merge_usage, message_text, template_context
|
||||
from app.providers import catalog
|
||||
from app.providers.factory import ModelSpec, get_chat_model
|
||||
|
||||
|
||||
@@ -32,10 +34,9 @@ async def run_human(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if mode == "edit":
|
||||
payload["draft"] = ctx.render(ctx.cfg("draft", ""), state)
|
||||
|
||||
ctx.emit(EventType.HUMAN_REQUESTED, **payload)
|
||||
response = interrupt(payload)
|
||||
response = await ask(ctx, payload, **payload)
|
||||
# 谁批的跟着事件走:时间线要写得出"张工驳回了",没署名就是 None,不再默认写"你"
|
||||
ctx.emit(EventType.HUMAN_RESOLVED, response=response, actor=ctx.actor())
|
||||
await once(ctx, EventType.HUMAN_RESOLVED, response=response, actor=ctx.actor())
|
||||
decision = read_decision(response)
|
||||
|
||||
if mode == "approve":
|
||||
@@ -79,6 +80,7 @@ async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"""按 JSON Schema 校验上游产出。
|
||||
|
||||
校验失败时可以把错误原样喂回模型让它改 —— 这比在 prompt 里祈祷它输出正确格式可靠得多。
|
||||
但修复只许改格式:修出来的值要能在原文里找到,找不到的就是模型编的(见 _invented)。
|
||||
"""
|
||||
import jsonschema
|
||||
|
||||
@@ -87,24 +89,35 @@ async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
raise NodeError(ctx.node.id, "校验节点需要一个 JSON Schema")
|
||||
|
||||
source_cfg = ctx.cfg("source", "{{ last_message }}")
|
||||
raw = ctx.render(source_cfg, state) if not isinstance(source_cfg, str) else ctx.render_str(source_cfg, state)
|
||||
original = ctx.render(source_cfg, state) if not isinstance(source_cfg, str) else ctx.render_str(source_cfg, state)
|
||||
max_retries = int(ctx.cfg("max_retries", 2) or 0)
|
||||
repair = bool(ctx.cfg("repair_with_llm", True))
|
||||
|
||||
attempt = 0
|
||||
errors: list[str] = []
|
||||
raw: Any = original
|
||||
value: Any = raw
|
||||
usage: dict[str, Any] = {}
|
||||
|
||||
while True:
|
||||
value, parse_error = _coerce_json(raw)
|
||||
invented = [] if parse_error or raw is original else _invented(value, original, schema)
|
||||
if parse_error:
|
||||
errors = [parse_error]
|
||||
elif invented:
|
||||
# 修复编出了原文没有的值(真实运行里是凭空的 total_count: 0)。这次修复作废,
|
||||
# 下一次仍从原文修,而不是在编出来的那份上接着改
|
||||
errors = [f"修复时出现了原文没有的值:{'、'.join(invented[:5])}"]
|
||||
ctx.emit(EventType.LOG, level="warn", code="repair_invented",
|
||||
message=f"第 {attempt} 次修复作废:{errors[0]}")
|
||||
else:
|
||||
try:
|
||||
jsonschema.validate(value, schema)
|
||||
ctx.emit(EventType.LOG, level="info", message=f"校验通过(第 {attempt + 1} 次尝试)")
|
||||
result = {"valid": True, "data": value, "attempts": attempt + 1, "errors": []}
|
||||
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
|
||||
if usage:
|
||||
updates["usage"] = usage
|
||||
var_name = ctx.cfg("assign_to", "")
|
||||
if var_name:
|
||||
updates["vars"] = {var_name: value}
|
||||
@@ -113,17 +126,19 @@ async def run_validate(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
path = "/".join(str(p) for p in e.absolute_path) or "(根)"
|
||||
errors = [f"{path}: {e.message}"]
|
||||
|
||||
ctx.emit(EventType.LOG, level="warn", message=f"第 {attempt + 1} 次校验失败:{errors[0]}",
|
||||
code="validate_retry")
|
||||
if not invented:
|
||||
ctx.emit(EventType.LOG, level="warn", message=f"第 {attempt + 1} 次校验失败:{errors[0]}",
|
||||
code="validate_retry")
|
||||
attempt += 1
|
||||
if attempt > max_retries or not repair:
|
||||
break
|
||||
raw = await _repair(raw, schema, errors, ctx, state)
|
||||
raw, spent = await _repair(original, schema, errors, ctx)
|
||||
usage = merge_usage(usage, spent)
|
||||
|
||||
result = {"valid": False, "data": value, "attempts": attempt, "errors": errors}
|
||||
if ctx.cfg("fail_fast", True):
|
||||
raise NodeError(ctx.node.id, f"结构化校验未通过:{'; '.join(errors)}")
|
||||
return {"nodes": {ctx.node.id: result}}
|
||||
return {"nodes": {ctx.node.id: result}, **({"usage": usage} if usage else {})}
|
||||
|
||||
|
||||
def _coerce_json(raw: Any) -> tuple[Any, str | None]:
|
||||
@@ -150,18 +165,155 @@ def _coerce_json(raw: Any) -> tuple[Any, str | None]:
|
||||
return text, "输出不是合法 JSON"
|
||||
|
||||
|
||||
async def _repair(raw: Any, schema: dict[str, Any], errors: list[str], ctx: NodeContext,
|
||||
state: GraphState) -> str:
|
||||
async def _repair(raw: Any, schema: dict[str, Any], errors: list[str],
|
||||
ctx: NodeContext) -> tuple[str, dict[str, Any]]:
|
||||
"""让模型只改格式地重写一遍。返回 (重写的文本, 这次调用的用量)。"""
|
||||
async with SessionLocal() as session:
|
||||
model, _ = await get_chat_model(
|
||||
model, model_id = await get_chat_model(
|
||||
session,
|
||||
ModelSpec(provider=ctx.cfg("provider"), model=ctx.cfg("model"), max_tokens=4096),
|
||||
)
|
||||
prompt = (
|
||||
"下面这段输出没有通过 JSON Schema 校验,请修正后重新输出。\n\n"
|
||||
"下面这段输出没有通过 JSON Schema 校验,请只调整格式后重新输出。\n\n"
|
||||
"规矩:你只能搬运原始输出里已经有的值,不许补数据。原始输出里没有的值一律填 null,"
|
||||
"即使 Schema 要求它不能为空——不许用 0、空字符串或任何猜测的值凑数,不许编造。"
|
||||
"值要从原文里原样抄过来。\n\n"
|
||||
f"Schema:\n{json.dumps(schema, ensure_ascii=False, indent=2)}\n\n"
|
||||
f"错误:\n- " + "\n- ".join(errors) + "\n\n"
|
||||
f"原始输出:\n{str(raw)[:6000]}\n\n"
|
||||
f"原始输出:\n{_as_text(raw)[:6000]}\n\n"
|
||||
"只输出修正后的 JSON,不要任何解释或代码围栏。"
|
||||
)
|
||||
return message_text(await model.ainvoke(prompt))
|
||||
started = time.perf_counter()
|
||||
response = await model.ainvoke(prompt)
|
||||
# 修复是一次真实的模型调用,以前不发 llm.end、不进 usage,钱花了账上看不见
|
||||
meta = getattr(response, "usage_metadata", None) or {}
|
||||
inp, out = int(meta.get("input_tokens") or 0), int(meta.get("output_tokens") or 0)
|
||||
spent = {"input_tokens": inp, "output_tokens": out, "total_tokens": inp + out,
|
||||
"cost_usd": round(catalog.estimate_cost(model_id, inp, out), 6), "calls": 1}
|
||||
ctx.emit(EventType.LLM_END, model=model_id, purpose="repair",
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), **spent)
|
||||
return message_text(response), spent
|
||||
|
||||
|
||||
def _as_text(raw: Any) -> str:
|
||||
return raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
# 原文里的数字:可带千分位、小数、正负号
|
||||
_NUMBER = re.compile(r"-?\d[\d,]*(?:\.\d+)?")
|
||||
_PERCENT = re.compile(r"(-?\d[\d,]*(?:\.\d+)?)\s*[%%]")
|
||||
# 字符串值里要能在原文找到的片段:数字、拉丁词、连续的汉字
|
||||
_PIECE = re.compile(r"\d+(?:\.\d+)?|[A-Za-z]+|[\u4e00-\u9fff]+")
|
||||
|
||||
# 数字的证据不从代码里取。「假设调用工具 + 一段 SQL」正是最常见的造假形状,而 SQL 里
|
||||
# 到处是数字:WHERE status > 0、deleted = 0、LIMIT 10。认它们的话,编出来的
|
||||
# total_count: 0 就有了「出处」。要去掉的是:代码围栏(sql / python / shell 之类)、
|
||||
# "sql": "…" 这类字符串值、以及正文里看起来像 SQL 的那一段(SELECT … FROM … 到句末,
|
||||
# 后面接着的 WHERE / LIMIT 之类的行一并算进去)
|
||||
_CODE_FENCE = re.compile(
|
||||
r"```[ \t]*(?:sql|mysql|postgres(?:ql)?|sqlite|plsql|python|py|bash|sh|shell|zsh"
|
||||
r"|javascript|js|typescript|ts)\b.*?(?:```|$)", re.I | re.S)
|
||||
_CODE_VALUE = re.compile(r'"(?:sql|query|statement|code|script|command)"\s*:\s*"(?:[^"\\]|\\.)*"',
|
||||
re.I)
|
||||
_SQL_RUN = re.compile(
|
||||
r"\b(?:select\b|with\s+(?:recursive\s+)?\w+\s*(?:\([^)]*\))?\s+as\s*\()"
|
||||
r"(?:(?!\.\s)[^;;。]){0,400}?\bfrom\b[^\n;;。,]*"
|
||||
r"(?:\n[ \t]*(?:where|and|or|group|order|having|limit|offset|union|on|join|left|right|inner"
|
||||
r"|outer|full|cross)\b[^\n;;。,]*)*", re.I)
|
||||
|
||||
|
||||
def _without_code(text: str) -> str:
|
||||
for pattern in (_CODE_FENCE, _CODE_VALUE, _SQL_RUN):
|
||||
text = pattern.sub(" ", text)
|
||||
return text
|
||||
|
||||
|
||||
def _numbers_in(text: str) -> set[float]:
|
||||
"""原文里(代码之外)所有数字的值。中文写法(十二条、3.5万)按出具回指那套规则一并认;
|
||||
带百分号的另认它的小数写法(12.5% → 0.125 是格式换算,不是编造)。"""
|
||||
from app.engine.issuance import extract_numbers
|
||||
|
||||
text = _without_code(text)
|
||||
out: set[float] = {token.value for token in extract_numbers(text)}
|
||||
for token in _NUMBER.findall(text):
|
||||
try:
|
||||
out.add(float(token.replace(",", "")))
|
||||
except ValueError:
|
||||
continue
|
||||
for token in _PERCENT.findall(text):
|
||||
try:
|
||||
out.add(float(token.replace(",", "")) / 100)
|
||||
except ValueError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def _literals(schema: Any) -> set[str]:
|
||||
"""Schema 自己规定的取值(enum / const):把「成功」映射成 "ok" 是格式,不是编造。"""
|
||||
found: set[str] = set()
|
||||
if isinstance(schema, dict):
|
||||
for key in ("enum", "const"):
|
||||
value = schema.get(key)
|
||||
for item in value if isinstance(value, list) else [value]:
|
||||
if item is not None:
|
||||
found.add(str(item))
|
||||
for value in schema.values():
|
||||
found |= _literals(value)
|
||||
elif isinstance(schema, list):
|
||||
for value in schema:
|
||||
found |= _literals(value)
|
||||
return found
|
||||
|
||||
|
||||
def _invented(value: Any, original: Any, schema: dict[str, Any]) -> list[str]:
|
||||
"""修复结果里原文没有的值,写成 "路径=值"。
|
||||
|
||||
数字按数值比(原文写 1,284,修出来 1284 算有);非空字符串要么原样出现在原文里,
|
||||
要么它的每个数字、拉丁词、汉字片段都能在原文里找到(2026年9月1日 → 2026-09-01
|
||||
算搬运)。布尔、null 不查:null 正是「没有这个数据」的诚实写法。
|
||||
"""
|
||||
text = _as_text(original)
|
||||
lowered = text.lower()
|
||||
numbers = _numbers_in(text)
|
||||
allowed = _literals(schema)
|
||||
found: list[str] = []
|
||||
|
||||
def known_number(n: float) -> bool:
|
||||
return any(abs(n - m) <= 1e-9 for m in numbers)
|
||||
|
||||
def walk(node: Any, path: str) -> None:
|
||||
if isinstance(node, dict):
|
||||
for key, item in node.items():
|
||||
walk(item, f"{path}.{key}" if path else str(key))
|
||||
elif isinstance(node, list):
|
||||
for i, item in enumerate(node):
|
||||
walk(item, f"{path}[{i}]")
|
||||
elif isinstance(node, bool) or node is None:
|
||||
return
|
||||
elif isinstance(node, (int, float)):
|
||||
if not known_number(float(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 "(根)"}=""')
|
||||
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]}")
|
||||
return
|
||||
if s.lower() in lowered:
|
||||
return
|
||||
pieces = _PIECE.findall(s)
|
||||
ok = bool(pieces) and all(
|
||||
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]}")
|
||||
|
||||
walk(value, "")
|
||||
return found
|
||||
|
||||
@@ -78,6 +78,8 @@ def _apply_contract(
|
||||
# 没有它,一个写错的节点名会让所有列表都是空的,看起来和"全部通过"一模一样。
|
||||
gaps: list[str] = []
|
||||
unresolved: list[str] = []
|
||||
#: 指标 id → 它来自哪张口径卡(「销售口径 @ v2」),逐个数字回指时标出处
|
||||
caliber_of: dict[str, str] = {}
|
||||
for source in sources:
|
||||
payload = nodes.get(source)
|
||||
if isinstance(payload, dict) and payload.get("kind") == "metric_set":
|
||||
@@ -89,6 +91,9 @@ def _apply_contract(
|
||||
"version": payload.get("caliber_version", ""),
|
||||
}
|
||||
)
|
||||
label = " @ ".join(str(v) for v in (payload.get("caliber"), payload.get("caliber_version")) if v)
|
||||
for m in payload.get("metrics") or []:
|
||||
caliber_of.setdefault(str(m.get("id")), label)
|
||||
else:
|
||||
# 节点不存在、还没跑到、或者根本不是口径卡——指标集就是缺的,
|
||||
# 不能当作"这次没有指标要查"
|
||||
@@ -121,6 +126,14 @@ def _apply_contract(
|
||||
if sources and not metrics:
|
||||
gaps.append("指标集为空,叙述里的数字无从回指")
|
||||
|
||||
# 上游有协作团队用完轮数、按降档交付的:叙述里的话不是调度者认可的结论,
|
||||
# 数字全都对得上也不能盖「完整出具」
|
||||
titles = {n.id: n.title for n in ctx.run.spec.nodes}
|
||||
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,
|
||||
missing_expected=missing_expected,
|
||||
@@ -129,6 +142,11 @@ def _apply_contract(
|
||||
gaps=gaps,
|
||||
)
|
||||
|
||||
# 逐个数字的出处。以前只有一个计数,界面标不出「这个数来自哪个指标」
|
||||
matched = [
|
||||
{**hit, **({"caliber": caliber_of[hit["metric"]]} if caliber_of.get(hit.get("metric")) else {})}
|
||||
for hit in (trace.matched if trace else [])
|
||||
][:50]
|
||||
issuance = {
|
||||
"tier": tier,
|
||||
"calibers": calibers, # 口径版本照常印
|
||||
@@ -137,6 +155,7 @@ def _apply_contract(
|
||||
"missing_expected": missing_expected, # 缺数据声明照常印
|
||||
"unmatched_numbers": unmatched[:20],
|
||||
"matched_numbers": len(trace.matched) if trace else 0,
|
||||
"matched": matched,
|
||||
# 校验没跑全的原因照实印出来——读的人要能分辨"查过都对"和"根本没查"
|
||||
"gaps": gaps,
|
||||
"declared_at": datetime.now(timezone.utc).isoformat(),
|
||||
@@ -153,6 +172,7 @@ def _apply_contract(
|
||||
gaps=gaps,
|
||||
metrics_checked=len(metrics),
|
||||
matched_numbers=len(trace.matched) if trace else 0,
|
||||
matched=matched,
|
||||
)
|
||||
return issuance
|
||||
|
||||
|
||||
+146
-82
@@ -7,17 +7,27 @@ from typing import Any
|
||||
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage
|
||||
from langchain_core.tools import BaseTool
|
||||
from langgraph.func import task
|
||||
from langgraph.types import interrupt
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import Skill
|
||||
from app.engine.approval import read_decision
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.errors import describe_exception
|
||||
from app.engine.replay import ask, once
|
||||
from app.engine.state import GraphState, message_text, template_context, thinking_text
|
||||
from app.engine.toolcalls import (
|
||||
TOOL_MARKUP_ERROR,
|
||||
TOOL_MARKUP_NUDGE,
|
||||
ToolTimeout,
|
||||
leaked_markup,
|
||||
limit_fields,
|
||||
limit_of,
|
||||
markup_warning,
|
||||
run_bounded,
|
||||
)
|
||||
from app.providers import catalog
|
||||
from app.providers.factory import (
|
||||
ModelSpec,
|
||||
@@ -27,6 +37,7 @@ from app.providers.factory import (
|
||||
)
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
ToolBuildError,
|
||||
ToolContext,
|
||||
args_model_of,
|
||||
build_tools,
|
||||
@@ -124,6 +135,14 @@ def _usage_of(message: BaseMessage, model_id: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _report_call(ctx: NodeContext, response: BaseMessage, model_id: str, started: float) -> dict[str, Any]:
|
||||
"""一次模型调用一条 llm.end。返回这一次的用量。"""
|
||||
usage = _usage_of(response, model_id)
|
||||
ctx.emit(EventType.LLM_END, model=model_id,
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), **usage)
|
||||
return usage
|
||||
|
||||
|
||||
def explain_model_error(exc: Exception, model_id: str) -> str:
|
||||
"""把供应商的原始报错翻成能照着做的一句话。
|
||||
|
||||
@@ -218,6 +237,8 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
messages = await _build_messages(state, ctx)
|
||||
schema = ctx.cfg("output_schema")
|
||||
started = time.perf_counter()
|
||||
#: 这个节点里每次模型调用的用量。正常只有一次;模型把工具调用写成文字时会多一次纠正
|
||||
spent: list[dict[str, Any]] = []
|
||||
|
||||
if schema:
|
||||
# 要结构化结果就走原生 structured output,这条路径拿不到 token 流
|
||||
@@ -241,9 +262,23 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
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)}
|
||||
response: BaseMessage = AIMessage(content=output["text"])
|
||||
spent.append(_report_call(ctx, response, model_id, started))
|
||||
else:
|
||||
response = await _invoke_streaming(model, messages, ctx, model_id)
|
||||
spent.append(_report_call(ctx, response, model_id, started))
|
||||
text = message_text(response)
|
||||
if snippet := leaked_markup(text):
|
||||
# 模型把工具调用当正文写了出来:这个节点压根没有工具,那段"调用"什么都没查到。
|
||||
# 带一句纠正再问一次;还这样就判失败,别让一堆标记当答案往下游走
|
||||
ctx.emit(EventType.LOG, level="warn", code="tool_markup_leak",
|
||||
message=f"{markup_warning(snippet)},已提醒它重试一次")
|
||||
retried = time.perf_counter()
|
||||
response = await _invoke_streaming(
|
||||
model, [*messages, response, HumanMessage(content=TOOL_MARKUP_NUDGE)], ctx, model_id)
|
||||
spent.append(_report_call(ctx, response, model_id, retried))
|
||||
text = message_text(response)
|
||||
if leaked_markup(text):
|
||||
raise NodeError(ctx.node.id, TOOL_MARKUP_ERROR)
|
||||
reasoning = thinking_text(response)
|
||||
if not text and reasoning:
|
||||
# 思考型模型把额度全花在推理上了,正文是空的 —— 说清楚而不是抛个空结果给下游
|
||||
@@ -252,14 +287,9 @@ async def run_llm(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
code="empty_completion")
|
||||
output = {"text": text, "thinking": reasoning}
|
||||
|
||||
usage = _usage_of(response, model_id)
|
||||
elapsed = int((time.perf_counter() - started) * 1000)
|
||||
ctx.emit(
|
||||
EventType.LLM_END,
|
||||
model=model_id,
|
||||
duration_ms=elapsed,
|
||||
**usage,
|
||||
)
|
||||
usage = {key: sum(one[key] for one in spent) for key in spent[0]}
|
||||
usage["cost_usd"] = round(usage["cost_usd"], 6)
|
||||
|
||||
result = {**output, "model": model_id, "duration_ms": elapsed}
|
||||
updates: dict[str, Any] = {
|
||||
@@ -289,7 +319,11 @@ async def _resolve_tools(ctx: NodeContext, state: GraphState) -> list[BaseTool]:
|
||||
collection=ctx.cfg("collection") or ctx.run.collection,
|
||||
)
|
||||
async with SessionLocal() as session:
|
||||
return await build_tools(names, tool_ctx, session=session)
|
||||
try:
|
||||
return await build_tools(names, tool_ctx, session=session)
|
||||
except ToolBuildError as e:
|
||||
# 绑的工具自己坏了(参数定义写坏的自定义工具):说清是哪个、去哪里改
|
||||
raise NodeError(ctx.node.id, str(e)) from e
|
||||
|
||||
|
||||
SKIPPED_NOTE = (
|
||||
@@ -333,6 +367,10 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
|
||||
这里没有用 prebuilt 的 create_react_agent,因为需要在循环内部做三件它不做的事:
|
||||
每步工具调用都往画布推事件、对危险工具逐个弹人工审批、以及步数护栏。
|
||||
|
||||
人工审批恢复时整个节点从头重放。模型调用和工具调用都包在 @task 里,重放时结果
|
||||
取自 checkpoint,不重复计费、不重复执行;它们的事件也发在 task 里面,于是轨迹里
|
||||
同一次调用只出现一回。写在 task 外面的事件一律经 replay.once 发,道理相同。
|
||||
"""
|
||||
model_spec = _model_spec(ctx)
|
||||
async with SessionLocal() as session:
|
||||
@@ -354,12 +392,17 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
transcript: list[dict[str, Any]] = []
|
||||
|
||||
def _report(response: BaseMessage, started: float) -> None:
|
||||
# 每次模型调用一条 llm.end:用量在节点跑的过程中就看得到。发在 task 里面,
|
||||
# 节点因审批重放时 task 结果取自 checkpoint,这条不会重复
|
||||
# 每次模型调用一条 llm.end:用量在节点跑的过程中就看得到
|
||||
ctx.emit(EventType.LLM_END, agent=ctx.node.title, model=model_id,
|
||||
duration_ms=int((time.perf_counter() - started) * 1000),
|
||||
**_usage_of(response, model_id))
|
||||
|
||||
def _count(response: BaseMessage) -> None:
|
||||
usage = _usage_of(response, model_id)
|
||||
for key in ("input_tokens", "output_tokens", "calls"):
|
||||
total_usage[key] += usage[key]
|
||||
total_usage["cost_usd"] = round(total_usage["cost_usd"] + usage["cost_usd"], 6)
|
||||
|
||||
# @task 的返回值会进 checkpoint:人工审批导致节点重放时,
|
||||
# 之前已经完成的模型调用和工具执行不会重跑,也就不会重复计费。
|
||||
@task
|
||||
@@ -379,23 +422,75 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
return response
|
||||
|
||||
@task
|
||||
async def tool_step(step: int, name: str, args: dict[str, Any]) -> str:
|
||||
async def tool_step(step: int, name: str, args: dict[str, Any], call_id: str) -> dict[str, Any]:
|
||||
# 失败也在这里收住、作为结果返回:失败的那次同样只执行一回,重放时不再重试
|
||||
tool = tool_map[name]
|
||||
result = await tool.ainvoke(args)
|
||||
return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str)
|
||||
limit = limit_of(tool, name, args)
|
||||
ctx.emit(EventType.TOOL_START, tool=name, args=args, call_id=call_id, **limit_fields(limit))
|
||||
started = time.perf_counter()
|
||||
extra: dict[str, Any] = {}
|
||||
try:
|
||||
result = await run_bounded(tool.ainvoke(args), limit, name)
|
||||
content = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str)
|
||||
ok = True
|
||||
except ToolTimeout as e:
|
||||
# 到点就收回控制权,驱动的收尾在后台做完。模型拿到的是"等了多久、为什么放弃"
|
||||
content, ok = str(e), False
|
||||
extra = {"error": str(e), "timed_out": True}
|
||||
except Exception as e: # noqa: BLE001 - 工具失败要喂回模型,让它自己纠错
|
||||
content = f"工具执行失败:{describe_exception(e)}"
|
||||
schema = args_model_of(tool)
|
||||
if isinstance(e, TypeError) and schema is not None:
|
||||
# 签名对不上还能走到这儿,说明 schema 和函数本身不一致(工具的 bug)。
|
||||
# 模型改不了这个,但把参数表摊开至少让它别在同一个地方反复试
|
||||
content += f"\n{describe_args(schema, args)}"
|
||||
ok = False
|
||||
extra = {"error": content.splitlines()[0][:300], "detail": raw_detail(e)}
|
||||
elapsed = int((time.perf_counter() - started) * 1000)
|
||||
snapshot_id: str | None = None
|
||||
if ok:
|
||||
from app.core.artifact_store import put_json
|
||||
|
||||
try:
|
||||
snapshot_id = await put_json(
|
||||
{"tool": name, "args": args, "result": content},
|
||||
kind="tool_snapshot", run_id=ctx.run.run_id, node_id=ctx.node.id,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
snapshot_id = None
|
||||
ctx.emit(
|
||||
EventType.TOOL_END if ok else EventType.TOOL_ERROR,
|
||||
tool=name,
|
||||
call_id=call_id,
|
||||
duration_ms=elapsed,
|
||||
preview=content[:2000],
|
||||
artifact=snapshot_id,
|
||||
**extra,
|
||||
)
|
||||
return {"content": content, "ok": ok, "duration_ms": elapsed}
|
||||
|
||||
final_text = ""
|
||||
#: 模型把工具调用写成了文字:纠正过一次了没有
|
||||
nudged = False
|
||||
for step in range(max_steps):
|
||||
response = await llm_step(step, messages)
|
||||
messages.append(response)
|
||||
usage = _usage_of(response, model_id)
|
||||
for key in ("input_tokens", "output_tokens", "calls"):
|
||||
total_usage[key] += usage[key]
|
||||
total_usage["cost_usd"] = round(total_usage["cost_usd"] + usage["cost_usd"], 6)
|
||||
_count(response)
|
||||
|
||||
tool_calls = getattr(response, "tool_calls", None) or []
|
||||
if not tool_calls:
|
||||
final_text = message_text(response)
|
||||
if snippet := leaked_markup(final_text):
|
||||
# 没有真实的调用,正文里却是一段调用标记:这一步什么都没查到。
|
||||
# 纠正一次;再来一次就是这个节点/模型根本调不了工具,判失败
|
||||
if nudged:
|
||||
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)},已提醒它重试一次")
|
||||
messages.append(HumanMessage(content=TOOL_MARKUP_NUDGE))
|
||||
final_text = ""
|
||||
continue
|
||||
break
|
||||
|
||||
run_calls, deferred = split_tool_calls(tool_calls, parallel=parallel_tools)
|
||||
@@ -421,35 +516,25 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 不执行,把"它接受什么"原样喂回去。模型下一步照着改就行,
|
||||
# 这才是失败之后真正能自愈的重试——以前喂回去的是一句
|
||||
# TypeError,里面既没有正确参数名也没有字段说明
|
||||
ctx.emit(EventType.TOOL_ERROR, tool=name, call_id=call_id, error=str(e))
|
||||
await once(ctx, EventType.TOOL_ERROR, tool=name, call_id=call_id, error=str(e))
|
||||
messages.append(ToolMessage(content=str(e), tool_call_id=call_id))
|
||||
transcript.append({"tool": name, "args": args, "ok": False, "result": str(e)})
|
||||
continue
|
||||
if fix_note:
|
||||
ctx.emit(EventType.LOG, level="warn",
|
||||
message=f"工具 {name}:{fix_note}", code="tool_args_fixed")
|
||||
await once(ctx, EventType.LOG, level="warn",
|
||||
message=f"工具 {name}:{fix_note}", code="tool_args_fixed")
|
||||
|
||||
if _needs_approval(ctx, tool_map[name], args):
|
||||
ctx.emit(
|
||||
EventType.HUMAN_REQUESTED,
|
||||
mode="approve",
|
||||
tool=name,
|
||||
args=args,
|
||||
title=f"Agent 想调用工具 {name}",
|
||||
)
|
||||
decision = interrupt(
|
||||
{
|
||||
"kind": "tool_approval",
|
||||
"node_id": ctx.node.id,
|
||||
"tool": name,
|
||||
"args": args,
|
||||
"title": f"是否允许调用 {name}?",
|
||||
}
|
||||
decision = await ask(
|
||||
ctx,
|
||||
{"kind": "tool_approval", "node_id": ctx.node.id, "tool": name, "args": args,
|
||||
"title": f"是否允许调用 {name}?"},
|
||||
mode="approve", tool=name, args=args, title=f"Agent 想调用工具 {name}",
|
||||
)
|
||||
verdict = read_decision(decision)
|
||||
note = verdict.note
|
||||
ctx.emit(EventType.HUMAN_RESOLVED, tool=name, approved=verdict.approved, note=note,
|
||||
actor=ctx.actor())
|
||||
await once(ctx, EventType.HUMAN_RESOLVED, tool=name, approved=verdict.approved,
|
||||
note=note, actor=ctx.actor())
|
||||
if not verdict.approved:
|
||||
messages.append(
|
||||
ToolMessage(
|
||||
@@ -462,41 +547,10 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if verdict.args:
|
||||
args = verdict.args
|
||||
|
||||
ctx.emit(EventType.TOOL_START, tool=name, args=args, call_id=call_id)
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
content = await tool_step(step, name, args)
|
||||
ok = True
|
||||
except Exception as e: # noqa: BLE001 - 工具失败要喂回模型,让它自己纠错
|
||||
content = f"工具执行失败:{describe_exception(e)}"
|
||||
if isinstance(e, TypeError) and schema is not None:
|
||||
# 签名对不上还能走到这儿,说明 schema 和函数本身不一致(工具的 bug)。
|
||||
# 模型改不了这个,但把参数表摊开至少让它别在同一个地方反复试
|
||||
content += f"\n{describe_args(schema, args)}"
|
||||
ok = False
|
||||
elapsed = int((time.perf_counter() - started) * 1000)
|
||||
snapshot_id: str | None = None
|
||||
if ok:
|
||||
from app.core.artifact_store import put_json
|
||||
|
||||
try:
|
||||
snapshot_id = await put_json(
|
||||
{"tool": name, "args": args, "result": content},
|
||||
kind="tool_snapshot", run_id=ctx.run.run_id, node_id=ctx.node.id,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
snapshot_id = None
|
||||
ctx.emit(
|
||||
EventType.TOOL_END if ok else EventType.TOOL_ERROR,
|
||||
tool=name,
|
||||
call_id=call_id,
|
||||
duration_ms=elapsed,
|
||||
preview=content[:2000],
|
||||
artifact=snapshot_id,
|
||||
)
|
||||
transcript.append(
|
||||
{"tool": name, "args": args, "ok": ok, "duration_ms": elapsed, "result": content[:4000]}
|
||||
)
|
||||
outcome = await tool_step(step, name, args, call_id)
|
||||
content = outcome["content"]
|
||||
transcript.append({"tool": name, "args": args, "ok": outcome["ok"],
|
||||
"duration_ms": outcome["duration_ms"], "result": content[:4000]})
|
||||
messages.append(ToolMessage(content=content, tool_call_id=call_id))
|
||||
|
||||
# 没跑的那些排在执行过的后面,保持模型原本的调用顺序
|
||||
@@ -506,7 +560,7 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
{"tool": call.get("name", ""), "args": call.get("args", {}) or {}, "skipped": True}
|
||||
)
|
||||
else:
|
||||
# 步数用完了。走到这儿一定意味着最后那步**要求了工具**(不要工具会 break),
|
||||
# 步数用完了:最后那步要么要求了工具,要么是纠正之后还没来得及答。
|
||||
# 也就是说模型从来没拿到过"说结论"的那一轮——它只是被掐断在半路。
|
||||
#
|
||||
# 所以先补上那一轮:不给工具,让它基于已经查到的东西收口。这比把中间
|
||||
@@ -520,14 +574,23 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
)))
|
||||
try:
|
||||
response = await settle_step(messages)
|
||||
usage = _usage_of(response, model_id)
|
||||
for key in ("input_tokens", "output_tokens", "calls"):
|
||||
total_usage[key] += usage[key]
|
||||
total_usage["cost_usd"] = round(total_usage["cost_usd"] + usage["cost_usd"], 6)
|
||||
_count(response)
|
||||
settled = message_text(response).strip()
|
||||
except Exception as e: # noqa: BLE001 - 收尾失败不能把已有成果一起赔进去
|
||||
ctx.emit(EventType.LOG, level="warn",
|
||||
message=f"收尾轮没跑成:{describe_exception(e)}", code="settle_failed")
|
||||
await once(ctx, EventType.LOG, level="warn",
|
||||
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):
|
||||
# 从头到尾一次真调用都没有,步数全耗在写标记上:还是那个「调不了工具」
|
||||
raise NodeError(ctx.node.id, TOOL_MARKUP_ERROR)
|
||||
# 收尾轮拿的是没绑工具的模型,它还是写了一段调用标记:想接着查、没能收口。
|
||||
# 这不是「节点没绑工具」(前面的步数里工具是真调过的),不能套 TOOL_MARKUP_ERROR
|
||||
# 判失败、把已经查到的一起丢掉——按收尾轮没说出话处理,取它之前说过的话
|
||||
await once(ctx, EventType.LOG, level="warn", code="tool_markup_leak",
|
||||
message=f"{markup_warning(snippet)}:步数用完后的收尾轮仍想调用工具,"
|
||||
"没能给出结论")
|
||||
settled = ""
|
||||
|
||||
if settled:
|
||||
final_text = settled
|
||||
@@ -546,7 +609,8 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 管道文案冒充结论,比明说"没跑完"糟糕得多。
|
||||
final_text = next(
|
||||
(text for m in reversed(messages)
|
||||
if isinstance(m, AIMessage) and (text := message_text(m).strip())),
|
||||
if isinstance(m, AIMessage) and (text := message_text(m).strip())
|
||||
and not leaked_markup(text)),
|
||||
"",
|
||||
)
|
||||
hint = (
|
||||
|
||||
@@ -10,12 +10,21 @@ from langgraph.errors import GraphRecursionError
|
||||
from langgraph.func import task
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import Workflow
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.errors import describe_exception
|
||||
from app.engine.state import GraphState, message_text, template_context
|
||||
from app.engine.toolcalls import (
|
||||
TOOL_MARKUP_NUDGE,
|
||||
ToolTimeout,
|
||||
leaked_markup,
|
||||
limit_fields,
|
||||
limit_of,
|
||||
markup_warning,
|
||||
run_bounded,
|
||||
)
|
||||
from app.providers import catalog
|
||||
from app.providers.factory import ModelSpec, bind_tools_safely, get_chat_model
|
||||
from app.tools.registry import (
|
||||
@@ -32,6 +41,10 @@ _MAX_DEPTH = 3
|
||||
#: 调度者在 llm.end 里的 agent 名。成员用各自的名字
|
||||
COORDINATOR = "调度者"
|
||||
|
||||
#: 成员把工具调用写成文字、纠正之后还是这样时,交给调度者的那句话
|
||||
MEMBER_MARKUP_FAILED = ("模型输出了工具调用的原始标记,但没有真正调用工具,这一步什么都没查到"
|
||||
"(常见原因:这个成员没有绑定工具,或者模型、服务不支持工具调用)")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Supervisor:一个调度者 + 若干专家
|
||||
@@ -52,6 +65,9 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
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)}
|
||||
max_rounds = min(int(ctx.cfg("max_rounds", 6) or 6), settings.max_agent_steps)
|
||||
#: 轮数用完、调度者始终没判定完成时怎么办。fail:判失败;degrade:照样交付但标明降档。
|
||||
#: 缺省 fail——成员的原话不是结论,把它当成功交出去比失败更糟
|
||||
on_exhausted = "degrade" if ctx.cfg("on_exhausted") == "degrade" else "fail"
|
||||
|
||||
goal = ctx.render_str(ctx.cfg("goal", "{{ last_message }}"), state)
|
||||
if not goal.strip():
|
||||
@@ -115,11 +131,12 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
return {"input_tokens": i, "output_tokens": o,
|
||||
"cost_usd": round(catalog.estimate_cost(model_id, i, o), 6)}
|
||||
|
||||
def _accumulate(one: dict[str, Any]) -> None:
|
||||
usage_total["input_tokens"] += one["input_tokens"]
|
||||
usage_total["output_tokens"] += one["output_tokens"]
|
||||
usage_total["calls"] += 1
|
||||
usage_total["cost_usd"] = round(usage_total["cost_usd"] + one["cost_usd"], 6)
|
||||
def _accumulate(one: dict[str, Any], into: dict[str, Any] | None = None) -> None:
|
||||
into = usage_total if into is None else into
|
||||
into["input_tokens"] += one["input_tokens"]
|
||||
into["output_tokens"] += one["output_tokens"]
|
||||
into["calls"] += one.get("calls", 1)
|
||||
into["cost_usd"] = round(into["cost_usd"] + one["cost_usd"], 6)
|
||||
|
||||
def _report(who: str, model_id: str, one: dict[str, Any], t0: float) -> None:
|
||||
# 每次模型调用各发一条 llm.end,界面上的用量才能实时涨,而且分得清是谁花的。
|
||||
@@ -127,24 +144,8 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
ctx.emit(EventType.LLM_END, agent=who, model=model_id,
|
||||
duration_ms=int((time.perf_counter() - t0) * 1000), **one)
|
||||
|
||||
@task
|
||||
async def route(round_no: int, progress: str) -> dict[str, Any]:
|
||||
prompt = (
|
||||
f"你是团队调度者。目标:\n{goal}\n\n"
|
||||
f"可用成员:\n{roster}\n\n"
|
||||
f"当前进展:\n{progress or '(还没有任何进展)'}\n\n"
|
||||
"决定这一轮把什么任务交给谁,每个任务给一句明确的指令。\n\n"
|
||||
f"**互不依赖的任务可以放在同一轮**(最多 {max_parallel} 个),它们会同时执行,"
|
||||
"总耗时按最慢的那个算。判断依据只有一条:**后一个任务需不需要看到前一个的结果**。\n"
|
||||
" 可以同时派:「查 A 产品的资料」和「查 B 产品的资料」——两边互不相干\n"
|
||||
" 不能同时派:「查资料」和「根据资料写报告」——后者要等前者\n"
|
||||
" 不能同时派:「写初稿」和「校对初稿」——同上\n\n"
|
||||
"同时派出去的成员看到的是**同一份进展快照**,谁也看不见谁这一轮干了什么。"
|
||||
"拿不准是否独立时就分两轮派,代价只是慢一点;派错了则是两个人基于同样的"
|
||||
"旧信息重复劳动,而这在结果里很难看出来。\n\n"
|
||||
"目标已经达成时,done 填 true、assignments 给空数组。"
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
async def _decide(prompt: str, *, closing: bool = False) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""问调度者一次。返回 (决定, 这次调用的用量)。"""
|
||||
spent = {"input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0}
|
||||
try:
|
||||
# include_raw:结构化结果之外把原始消息也要回来,用量在那条消息上。
|
||||
@@ -161,19 +162,139 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
value = json.loads(message_text(value))
|
||||
except Exception: # noqa: BLE001
|
||||
# 不支持结构化输出的模型退回文本:从回复里认出一个成员名,按单人派
|
||||
# 不支持结构化输出的模型退回文本:从回复里认出一个成员名,按单人派。
|
||||
# 收尾判定时同理:回复里还点着哪个成员,就是还没完
|
||||
reply = await supervisor_model.ainvoke(prompt)
|
||||
spent = _usage(reply, sup_model_id)
|
||||
raw = message_text(reply)
|
||||
picked = next((n for n in names if n in raw), None)
|
||||
value = ({"assignments": [{"agent": picked, "instruction": raw[:500]}]}
|
||||
if picked else {"assignments": [], "done": True, "reason": raw[:200]})
|
||||
# 在 task 里发:节点重放时 task 结果取自 checkpoint,这条不会重复
|
||||
if closing:
|
||||
value = {"assignments": [], "done": picked is None, "reason": raw[:200]}
|
||||
else:
|
||||
value = ({"assignments": [{"agent": picked, "instruction": raw[:500]}]}
|
||||
if picked else {"assignments": [], "done": True, "reason": raw[:200]})
|
||||
return (value if isinstance(value, dict) else {}), spent
|
||||
|
||||
def _batch_of(decision: dict[str, Any]) -> list[tuple[str, str]]:
|
||||
# 只留认得出的成员,并按上限截断。模型偶尔会重复派同一个人或者编一个
|
||||
# 不存在的名字——这两种在并发里都是纯浪费
|
||||
batch: list[tuple[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
for item in decision.get("assignments") or []:
|
||||
name = str((item or {}).get("agent") or "")
|
||||
if name in agent_map and name not in seen:
|
||||
seen.add(name)
|
||||
batch.append((name, str(item.get("instruction") or goal)))
|
||||
if len(batch) >= max_parallel:
|
||||
break
|
||||
return batch
|
||||
|
||||
def _finished(round_no: int, reason: str, **extra: Any) -> None:
|
||||
# agents / done 是结构化字段,界面照着它渲染。以前只有一句中文
|
||||
# 消息串,解码层得拿正则去拆「调度 → X(理由)」——文案一改就散架
|
||||
ctx.emit(EventType.LOG, level="info", round=round_no, agents=[], done=True,
|
||||
message="调度 → 结束协作" + (f"({reason})" if reason else ""), **extra)
|
||||
|
||||
# 调度者决策前后各一条事件(它常常占掉团队节点大半的时间,以前是黑盒),和派活的
|
||||
# 那条日志一起都在 task 里发:「接着跑」一个失败的团队节点时整个节点重放,前几轮
|
||||
# 的决定取自 checkpoint,这些事件不该在时间线上再出现一遍
|
||||
@task
|
||||
async def route(round_no: int, progress: str) -> dict[str, Any]:
|
||||
ctx.emit(EventType.AGENT_ROUTE_START, round=round_no)
|
||||
prompt = (
|
||||
f"你是团队调度者。目标:\n{goal}\n\n"
|
||||
f"可用成员:\n{roster}\n\n"
|
||||
f"当前进展:\n{progress or '(还没有任何进展)'}\n\n"
|
||||
"决定这一轮把什么任务交给谁,每个任务给一句明确的指令。\n\n"
|
||||
f"**互不依赖的任务可以放在同一轮**(最多 {max_parallel} 个),它们会同时执行,"
|
||||
"总耗时按最慢的那个算。判断依据只有一条:**后一个任务需不需要看到前一个的结果**。\n"
|
||||
" 可以同时派:「查 A 产品的资料」和「查 B 产品的资料」——两边互不相干\n"
|
||||
" 不能同时派:「查资料」和「根据资料写报告」——后者要等前者\n"
|
||||
" 不能同时派:「写初稿」和「校对初稿」——同上\n\n"
|
||||
"同时派出去的成员看到的是**同一份进展快照**,谁也看不见谁这一轮干了什么。"
|
||||
"拿不准是否独立时就分两轮派,代价只是慢一点;派错了则是两个人基于同样的"
|
||||
"旧信息重复劳动,而这在结果里很难看出来。\n\n"
|
||||
"目标已经达成时,done 填 true、assignments 给空数组。"
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
value, spent = await _decide(prompt)
|
||||
_report(COORDINATOR, sup_model_id, spent, t0)
|
||||
|
||||
batch = _batch_of(value)
|
||||
finishing = bool(value.get("done")) or not batch
|
||||
reason = str(value.get("reason", ""))
|
||||
ctx.emit(EventType.AGENT_ROUTE_END, round=round_no,
|
||||
duration_ms=int((time.perf_counter() - t0) * 1000),
|
||||
agents=[] if finishing else [n for n, _ in batch],
|
||||
parallel=0 if finishing else len(batch), done=finishing, reason=reason)
|
||||
if finishing:
|
||||
_finished(round_no, reason)
|
||||
else:
|
||||
who = "、".join(n for n, _ in batch)
|
||||
ctx.emit(
|
||||
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 "")),
|
||||
)
|
||||
return {"decision": value, "usage": spent}
|
||||
|
||||
# 最后一轮派出去的成员(常常就是定稿的那个)交回来之后,调度者还没看过它的产出。
|
||||
# 以前轮数一到就算用完:步数恰好等于最多轮数的正常流水线(查数 → 撰稿,2 轮)也会
|
||||
# 被判成没完成。补这一次只判定、不派活的决定,它说完成了才算完成
|
||||
@task
|
||||
async def work(round_no: int, name: str, instruction: str, progress: str) -> dict[str, Any]:
|
||||
async def verdict(round_no: int, progress: str) -> dict[str, Any]:
|
||||
ctx.emit(EventType.AGENT_ROUTE_START, round=round_no, closing=True)
|
||||
prompt = (
|
||||
f"你是团队调度者。目标:\n{goal}\n\n"
|
||||
f"当前进展:\n{progress or '(还没有任何进展)'}\n\n"
|
||||
f"轮数已经用完({max_rounds} 轮),不能再派任何任务。只判断一件事:按上面的进展,"
|
||||
"目标是不是已经达成、能不能把最后一个成员的产出作为结论交出去。\n"
|
||||
"达成了 done 填 true;没达成 done 填 false,并在 reason 里说清还缺什么。"
|
||||
"assignments 给空数组。"
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
value, spent = await _decide(prompt, closing=True)
|
||||
_report(COORDINATOR, sup_model_id, spent, t0)
|
||||
done = value.get("done") is True
|
||||
reason = str(value.get("reason", ""))
|
||||
ctx.emit(EventType.AGENT_ROUTE_END, round=round_no,
|
||||
duration_ms=int((time.perf_counter() - t0) * 1000),
|
||||
agents=[], parallel=0, done=done, reason=reason, closing=True)
|
||||
if done:
|
||||
_finished(round_no, reason, closing=True)
|
||||
return {"done": done, "reason": reason, "usage": spent}
|
||||
|
||||
# 成员的开始、结束两条事件也在 task 里发,理由同 route。失败也在 task 里收住、作为
|
||||
# 结果缓存:重放时这一步照旧是失败,不会换一个结果。用量随结果带出来再记账——在
|
||||
# task 里直接记进 usage_total 的话,重放取了缓存,这一笔就没了
|
||||
@task
|
||||
async def work(round_no: int, name: str, instruction: str, progress: str,
|
||||
parallel: int = 1) -> dict[str, Any]:
|
||||
ctx.emit(EventType.AGENT_STEP_START, agent=name, instruction=instruction[:300],
|
||||
round=round_no, parallel=parallel)
|
||||
tally = {"input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0, "calls": 0}
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
out: dict[str, Any] = await _member(name, instruction, progress, tally)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except BaseException as exc: # noqa: BLE001 - 一个专家挂了不该拖垮整轮
|
||||
# 把失败当成它的产出交回调度者,让它决定改派还是收工
|
||||
why = describe_exception(exc)
|
||||
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}")
|
||||
each_ms = int((time.perf_counter() - t0) * 1000)
|
||||
# failed / error 让矩阵把这一格画成失败,而不是一个"完成"的格子里写着失败原因
|
||||
failure = {"failed": True, "error": out.get("error") or ""} if out.get("failed") else {}
|
||||
ctx.emit(EventType.AGENT_STEP_END, agent=name, duration_ms=each_ms,
|
||||
round=round_no, parallel=parallel, preview=out["text"][:500], **failure)
|
||||
return {**out, "duration_ms": each_ms, "usage": tally}
|
||||
|
||||
async def _member(name: str, instruction: str, progress: str,
|
||||
tally: dict[str, Any]) -> dict[str, Any]:
|
||||
cfg = agent_map[name]
|
||||
async with SessionLocal() as session:
|
||||
model, model_id = await get_chat_model(
|
||||
@@ -202,20 +323,37 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
calls: list[dict[str, Any]] = []
|
||||
# 和 agent 节点同一个硬顶:成员上配多少步都过不去 max_agent_steps
|
||||
max_steps = min(int(cfg.get("max_steps") or 4), settings.max_agent_steps)
|
||||
nudged = False
|
||||
for _ in range(max_steps):
|
||||
t0 = time.perf_counter()
|
||||
reply = await bound.ainvoke(messages)
|
||||
spent = _usage(reply, model_id)
|
||||
_accumulate(spent)
|
||||
_accumulate(spent, tally)
|
||||
_report(name, model_id, spent, t0)
|
||||
messages.append(reply)
|
||||
tool_calls = getattr(reply, "tool_calls", None) or []
|
||||
if not tool_calls:
|
||||
return {"text": message_text(reply), "tool_calls": calls}
|
||||
text = message_text(reply)
|
||||
snippet = leaked_markup(text)
|
||||
if not snippet:
|
||||
return {"text": text, "tool_calls": calls}
|
||||
# 把工具调用写成了文字:这一步什么都没查到。纠正一次,还这样就记为失败,
|
||||
# 原因交给调度者——以前这段标记会被当成这个成员的结论交上去
|
||||
if nudged:
|
||||
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)},已提醒它重试一次")
|
||||
messages.append(HumanMessage(content=TOOL_MARKUP_NUDGE))
|
||||
continue
|
||||
for call in tool_calls:
|
||||
tname = call.get("name", "")
|
||||
targs = call.get("args", {}) or {}
|
||||
cid = call.get("id") or f"{name}-{tname}"
|
||||
limit = None
|
||||
failure: dict[str, Any] = {}
|
||||
started = time.perf_counter()
|
||||
if tname not in tool_map:
|
||||
ctx.emit(EventType.TOOL_START, tool=tname, args=targs, agent=name, call_id=cid)
|
||||
content = f"错误:没有名为 {tname} 的工具"
|
||||
@@ -229,7 +367,9 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
except ToolArgsError as e:
|
||||
args_error = str(e)
|
||||
# 纠正后的参数才是真正要执行的那份,tool.start 要发它
|
||||
ctx.emit(EventType.TOOL_START, tool=tname, args=targs, agent=name, call_id=cid)
|
||||
limit = limit_of(tool_map[tname], tname, targs)
|
||||
ctx.emit(EventType.TOOL_START, tool=tname, args=targs, agent=name, call_id=cid,
|
||||
**limit_fields(limit))
|
||||
if fix_note:
|
||||
ctx.emit(EventType.LOG, level="warn",
|
||||
message=f"工具 {tname}:{fix_note}", code="tool_args_fixed")
|
||||
@@ -250,11 +390,17 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
message=f"{name} 想调用 {tname},需要人工确认,协作节点里不执行")
|
||||
else:
|
||||
try:
|
||||
raw = await tool_map[tname].ainvoke(targs)
|
||||
raw = await run_bounded(tool_map[tname].ainvoke(targs), limit, tname)
|
||||
content = raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
except ToolTimeout as e:
|
||||
content = str(e)
|
||||
failure = {"error": content, "timed_out": True}
|
||||
except Exception as e: # noqa: BLE001
|
||||
content = f"工具失败:{describe_exception(e)}"
|
||||
ctx.emit(EventType.TOOL_END, tool=tname, agent=name, call_id=cid, preview=content[:1500])
|
||||
failure = {"error": content, "detail": raw_detail(e)}
|
||||
ctx.emit(EventType.TOOL_ERROR if failure else EventType.TOOL_END, tool=tname,
|
||||
agent=name, call_id=cid, preview=content[:1500],
|
||||
duration_ms=int((time.perf_counter() - started) * 1000), **failure)
|
||||
calls.append({"tool": tname, "args": targs, "result": content[:2000]})
|
||||
messages.append(ToolMessage(content=content, tool_call_id=cid))
|
||||
|
||||
@@ -270,14 +416,25 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
t0 = time.perf_counter()
|
||||
settled = await model.ainvoke(messages)
|
||||
spent = _usage(settled, model_id)
|
||||
_accumulate(spent)
|
||||
_accumulate(spent, tally)
|
||||
_report(name, model_id, spent, t0)
|
||||
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)}")
|
||||
text = next((t for m in reversed(messages)
|
||||
if isinstance(m, AIMessage) and (t := message_text(m).strip())), "")
|
||||
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})",
|
||||
"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)}:步数用完后的收尾轮仍想调用工具")
|
||||
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}
|
||||
@@ -285,54 +442,26 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
progress_lines: list[str] = []
|
||||
final_text = ""
|
||||
rounds_meta: list[dict[str, Any]] = []
|
||||
#: 调度者最后一轮给的理由,以及派过活的成员。轮数用完时报错要说清卡在哪、谁从没上过场
|
||||
last_reason = ""
|
||||
dispatched: set[str] = set()
|
||||
finished = False
|
||||
for round_no in range(max_rounds):
|
||||
progress = "\n\n".join(progress_lines)
|
||||
# 调度者决策前后各一条事件。它常常占掉团队节点大半的时间,以前是黑盒
|
||||
ctx.emit(EventType.AGENT_ROUTE_START, round=round_no)
|
||||
route_t0 = time.perf_counter()
|
||||
routed = await route(round_no, progress)
|
||||
route_ms = int((time.perf_counter() - route_t0) * 1000)
|
||||
decision = routed.get("decision", routed) if isinstance(routed, dict) else {}
|
||||
decision = decision if isinstance(decision, dict) else {}
|
||||
_accumulate(routed.get("usage") or _usage(None, sup_model_id))
|
||||
reason = str(decision.get("reason", ""))
|
||||
last_reason = reason or last_reason
|
||||
|
||||
# 只留认得出的成员,并按上限截断。模型偶尔会重复派同一个人或者编一个
|
||||
# 不存在的名字——这两种在并发里都是纯浪费
|
||||
batch: list[tuple[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
for item in decision.get("assignments") or []:
|
||||
name = str((item or {}).get("agent") or "")
|
||||
if name in agent_map and name not in seen:
|
||||
seen.add(name)
|
||||
batch.append((name, str(item.get("instruction") or goal)))
|
||||
if len(batch) >= max_parallel:
|
||||
break
|
||||
|
||||
finishing = bool(decision.get("done")) or not batch
|
||||
ctx.emit(EventType.AGENT_ROUTE_END, round=round_no, duration_ms=route_ms,
|
||||
agents=[] if finishing else [n for n, _ in batch],
|
||||
parallel=0 if finishing else len(batch), done=finishing, reason=reason)
|
||||
|
||||
if finishing:
|
||||
# agents / done 是结构化字段,界面照着它渲染。以前只有一句中文
|
||||
# 消息串,解码层得拿正则去拆「调度 → X(理由)」——文案一改就散架
|
||||
ctx.emit(EventType.LOG, level="info", round=round_no,
|
||||
agents=[], done=True,
|
||||
message="调度 → 结束协作" + (f"({reason})" if reason else ""))
|
||||
batch = _batch_of(decision)
|
||||
if bool(decision.get("done")) or not batch:
|
||||
final_text = progress_lines[-1].split("】", 1)[-1] if progress_lines else ""
|
||||
finished = True
|
||||
break
|
||||
|
||||
who = "、".join(n for n, _ in batch)
|
||||
ctx.emit(
|
||||
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 "")),
|
||||
)
|
||||
|
||||
for name, instruction in batch:
|
||||
ctx.emit(EventType.AGENT_STEP_START, agent=name, instruction=instruction[:300],
|
||||
round=round_no, parallel=len(batch))
|
||||
dispatched.update(n for n, _ in batch)
|
||||
|
||||
# 并发执行。它们拿到的是**同一份** progress 快照——这正是"任务必须
|
||||
# 互不依赖"的技术含义,也是上面提示词里那几条反例的由来。
|
||||
@@ -341,32 +470,23 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
# 时间",那个数必须是量出来的。按 N×墙钟 推算等于假设每个人都跑满了
|
||||
# 最慢那条,而实际上快的那个可能只花了三分之一。
|
||||
#
|
||||
# 结束事件也在这里一完成就发,不等整轮 gather:以前先做完的成员要一直
|
||||
# 显示"进行中",直到最慢的那个做完——矩阵答不了"谁还在跑"
|
||||
async def _timed(name: str, instruction: str, parallel: int) -> tuple[str, Any, int]:
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
out: Any = await work(round_no, name, instruction, progress)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except BaseException as exc: # noqa: BLE001 - 一个专家挂了不该拖垮整轮
|
||||
# 把失败当成它的产出交回调度者,让它决定改派还是收工
|
||||
text = f"({name} 执行失败:{describe_exception(exc)})"
|
||||
out = {"text": text, "tool_calls": []}
|
||||
ctx.emit(EventType.LOG, level="warn", round=round_no,
|
||||
message=f"{name} 这一轮失败了:{text}")
|
||||
each_ms = int((time.perf_counter() - t0) * 1000)
|
||||
ctx.emit(EventType.AGENT_STEP_END, agent=name, duration_ms=each_ms,
|
||||
round=round_no, parallel=parallel, preview=out["text"][:500])
|
||||
return name, out, each_ms
|
||||
# 结束事件也在各自的 task 里一完成就发,不等整轮 gather:以前先做完的成员要
|
||||
# 一直显示"进行中",直到最慢的那个做完——矩阵答不了"谁还在跑"
|
||||
async def _one(name: str, instruction: str, parallel: int) -> dict[str, Any]:
|
||||
return await work(round_no, name, instruction, progress, parallel)
|
||||
|
||||
started = time.perf_counter()
|
||||
results = await asyncio.gather(*(_timed(n, i, len(batch)) for n, i in batch))
|
||||
results = await asyncio.gather(*(_one(n, i, len(batch)) for n, i in batch))
|
||||
wall_ms = int((time.perf_counter() - started) * 1000)
|
||||
|
||||
# 进展仍按派活顺序拼:它是下一轮调度者读的输入,语义不随谁先回来而变
|
||||
sum_ms = 0
|
||||
for (name, instruction), (_, outcome, each_ms) in zip(batch, results):
|
||||
for (name, instruction), result in zip(batch, results):
|
||||
outcome = dict(result)
|
||||
spent = outcome.pop("usage", None)
|
||||
if spent:
|
||||
_accumulate(spent)
|
||||
each_ms = int(outcome.pop("duration_ms", 0) or 0)
|
||||
sum_ms += each_ms
|
||||
progress_lines.append(f"【{name}】{outcome['text']}")
|
||||
transcript.append(
|
||||
@@ -380,6 +500,32 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"parallel": len(batch), "wall_ms": wall_ms, "sum_ms": sum_ms,
|
||||
})
|
||||
|
||||
if not finished and progress_lines:
|
||||
judged = await verdict(max_rounds, "\n\n".join(progress_lines))
|
||||
_accumulate(judged.get("usage") or _usage(None, sup_model_id))
|
||||
last_reason = str(judged.get("reason") or "") or last_reason
|
||||
if judged.get("done"):
|
||||
final_text = progress_lines[-1].split("】", 1)[-1]
|
||||
finished = True
|
||||
|
||||
exhausted: dict[str, Any] = {}
|
||||
if not finished:
|
||||
# 轮数用完,调度者一次都没说「完成」。这时手上只有最后一个成员的原话——
|
||||
# 以前它就被当作团队的结论交了出去:真实运行里是一段没执行的工具调用标记,
|
||||
# 而负责定稿的成员一次都没被派到
|
||||
never = [n for n in names if n not in dispatched]
|
||||
summary = (f"协作团队用完 {max_rounds} 轮仍未完成:"
|
||||
f"{last_reason or '调度者没有给出理由'}")
|
||||
if never:
|
||||
summary += f"。一次都没被派到的成员:{'、'.join(never)}"
|
||||
if on_exhausted == "fail":
|
||||
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}。按降档交付:成果是成员最后的原话,不是调度者认可的结论")
|
||||
|
||||
usage_total["total_tokens"] = usage_total["input_tokens"] + usage_total["output_tokens"]
|
||||
# 并行省下的时间:各轮"串行本该花的"减去"实际花的"。只有并发过才有差值
|
||||
saved_ms = sum(r["sum_ms"] - r["wall_ms"] for r in rounds_meta)
|
||||
@@ -391,6 +537,7 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
"agents": names,
|
||||
"schedule": rounds_meta,
|
||||
"parallel_saved_ms": saved_ms,
|
||||
**exhausted,
|
||||
}
|
||||
updates: dict[str, Any] = {
|
||||
"nodes": {ctx.node.id: result},
|
||||
|
||||
@@ -4,18 +4,19 @@ import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from langgraph.types import interrupt
|
||||
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType
|
||||
from app.db.base import SessionLocal
|
||||
from app.engine.approval import read_decision
|
||||
from app.engine.context import NodeContext, NodeError
|
||||
from app.engine.errors import describe_exception, raw_detail
|
||||
from app.engine.replay import ask, once
|
||||
from app.engine.state import GraphState
|
||||
from app.engine.toolcalls import ToolTimeout, limit_fields, limit_of, run_bounded
|
||||
from app.sandbox.base import SandboxLimits
|
||||
from app.sandbox.manager import sandbox_manager
|
||||
from app.tools.registry import (
|
||||
ToolArgsError,
|
||||
ToolBuildError,
|
||||
ToolContext,
|
||||
build_tools,
|
||||
call_is_dangerous,
|
||||
@@ -34,16 +35,20 @@ def _tool_ctx(ctx: NodeContext) -> ToolContext:
|
||||
)
|
||||
|
||||
|
||||
async def _is_dangerous(name: str, args: dict[str, Any], ctx: NodeContext) -> bool:
|
||||
"""内置工具看 ToolSpec;数据源这类动态工具得先建出来,才问得到这一次危不危险。
|
||||
async def _dynamic_tool(name: str, ctx: NodeContext) -> Any:
|
||||
"""数据源、MCP、自定义这类动态工具得先建出来,才问得到它危不危险、时限多长。
|
||||
|
||||
审批通过后节点会整个重放,这里会再算一遍——所以它必须只取决于 name 和 args。
|
||||
内置工具的这两件事看 ToolSpec 和参数就够,不用建。
|
||||
"""
|
||||
if get_spec(name) is not None:
|
||||
return call_is_dangerous(None, name, args)
|
||||
return None
|
||||
async with SessionLocal() as session:
|
||||
tools = await build_tools([name], _tool_ctx(ctx), session=session)
|
||||
return call_is_dangerous(tools[0] if tools else None, name, args)
|
||||
try:
|
||||
tools = await build_tools([name], _tool_ctx(ctx), session=session)
|
||||
except ToolBuildError as e:
|
||||
# 工具自己的配置写坏了:说清是哪个、去哪里改,不再往下走到 call_tool 里炸
|
||||
raise NodeError(ctx.node.id, str(e)) from e
|
||||
return tools[0] if tools else None
|
||||
|
||||
|
||||
async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
@@ -56,24 +61,27 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
if not isinstance(args, dict):
|
||||
raise NodeError(ctx.node.id, "工具参数必须是对象")
|
||||
|
||||
# 审批通过后节点会整个重放、再算一遍要不要问人,所以这里只能取决于 name 和 args。
|
||||
# 节点没配时取全局设置(「危险工具默认需要人工确认」),见 NodeContext.approval_mode
|
||||
tool = await _dynamic_tool(name, ctx)
|
||||
approval = ctx.approval_mode()
|
||||
if approval == "always" or (approval == "dangerous" and await _is_dangerous(name, args, ctx)):
|
||||
ctx.emit(EventType.HUMAN_REQUESTED, mode="approve", tool=name, args=args,
|
||||
title=f"是否允许调用 {name}?")
|
||||
decision = read_decision(interrupt(
|
||||
if approval == "always" or (approval == "dangerous" and call_is_dangerous(tool, name, args)):
|
||||
decision = read_decision(await ask(
|
||||
ctx,
|
||||
{"kind": "tool_approval", "node_id": ctx.node.id, "tool": name, "args": args,
|
||||
"title": f"是否允许调用 {name}?"}
|
||||
"title": f"是否允许调用 {name}?"},
|
||||
mode="approve", tool=name, args=args, title=f"是否允许调用 {name}?",
|
||||
))
|
||||
if decision.args is not None:
|
||||
args = decision.args
|
||||
ctx.emit(EventType.HUMAN_RESOLVED, tool=name, approved=decision.approved,
|
||||
note=decision.note, actor=ctx.actor())
|
||||
await once(ctx, EventType.HUMAN_RESOLVED, tool=name, approved=decision.approved,
|
||||
note=decision.note, actor=ctx.actor())
|
||||
if not decision.approved:
|
||||
raise NodeError(ctx.node.id, f"用户拒绝执行工具 {name}"
|
||||
+ (f":{decision.note}" if decision.note else ""))
|
||||
|
||||
ctx.emit(EventType.TOOL_START, tool=name, args=args)
|
||||
limit = limit_of(tool, name, args)
|
||||
ctx.emit(EventType.TOOL_START, tool=name, args=args, **limit_fields(limit))
|
||||
started = time.perf_counter()
|
||||
|
||||
def _fixed(note: str) -> None:
|
||||
@@ -82,9 +90,20 @@ 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")
|
||||
|
||||
try:
|
||||
async def _call() -> Any:
|
||||
async with SessionLocal() as session:
|
||||
result = await call_tool(name, args, _tool_ctx(ctx), session=session, on_fix=_fixed)
|
||||
return await call_tool(name, args, _tool_ctx(ctx), session=session, on_fix=_fixed)
|
||||
|
||||
try:
|
||||
result = await run_bounded(_call(), limit, name)
|
||||
except ToolTimeout as e:
|
||||
# 到点就收回控制权,驱动的收尾在后台做完。报错里写的是实际等了多久
|
||||
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
|
||||
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}"
|
||||
@@ -144,16 +163,16 @@ async def run_code(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
if ctx.cfg("approval", "never") == "always":
|
||||
ctx.emit(EventType.HUMAN_REQUESTED, mode="approve", title="是否执行这段代码?",
|
||||
code=code[:4000], language=language)
|
||||
decision = read_decision(interrupt(
|
||||
decision = read_decision(await ask(
|
||||
ctx,
|
||||
{"kind": "code_approval", "node_id": ctx.node.id, "code": code,
|
||||
"language": language, "title": "是否执行这段代码?"}
|
||||
"language": language, "title": "是否执行这段代码?"},
|
||||
mode="approve", title="是否执行这段代码?", code=code[:4000], language=language,
|
||||
))
|
||||
if decision.code:
|
||||
code = decision.code # 允许人工改完再跑
|
||||
ctx.emit(EventType.HUMAN_RESOLVED, approved=decision.approved, note=decision.note,
|
||||
actor=ctx.actor())
|
||||
await once(ctx, EventType.HUMAN_RESOLVED, approved=decision.approved, note=decision.note,
|
||||
actor=ctx.actor())
|
||||
if not decision.approved:
|
||||
raise NodeError(ctx.node.id, "用户拒绝执行代码"
|
||||
+ (f":{decision.note}" if decision.note else ""))
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""节点重放时,已经发生过的事不在轨迹里再发生一次。
|
||||
|
||||
LangGraph 恢复一个停在 interrupt 上的节点,是把节点函数从头再跑一遍:前面几次
|
||||
interrupt() 按顺序直接返回已经给过的答复,@task 包住的调用直接取 checkpoint 里的
|
||||
结果。执行层面不会重复——agent 节点的模型调用、工具调用都在 task 里,副作用只发生
|
||||
一次。可写在 task 外面的 ctx.emit 每重放一次就再发一遍:运行 fac480ff 的轨迹里,
|
||||
同一个 call_id 的 python_exec 有两对 tool.start / tool.end,审批请求也问了两回,
|
||||
签批人还按最后一次恢复的人记。看轨迹的人只能照字面理解成「执行了两次」。
|
||||
「接着跑」一个失败的节点是同一回事。
|
||||
|
||||
所以要落进轨迹、又写在 task 外面的事,经这里发:它本身就是一次 task,第一次真正
|
||||
走到这里时发出,重放时结果取自 checkpoint、不再发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from langgraph.config import get_config
|
||||
from langgraph.func import task
|
||||
from langgraph.types import interrupt
|
||||
|
||||
from app.core.events import EventType
|
||||
from app.engine.context import NodeContext
|
||||
|
||||
#: 重放协议的版本,记在每个 checkpoint 的 metadata 里。
|
||||
#:
|
||||
#: LangGraph 认 task 的缓存靠「函数名 + 节点里第几次调用」。这一版多了 once / ask 的
|
||||
#: 记录 task,agent 的 tool_step 也换了位置和返回值:升级前停下的断点照新代码重放,
|
||||
#: 节点里已经执行过的工具、模型调用对不上旧的位置,会再执行一次(副作用翻倍),缓存
|
||||
#: 下来的旧返回值还可能直接对不上形状。恢复前先看版本,对不上又有这种风险就拒绝
|
||||
#: (见 runner 的 _stale_replay)。以后再改节点里 task 的调用顺序,把它加一
|
||||
PROTOCOL = 2
|
||||
PROTOCOL_KEY = "agentlab_replay"
|
||||
|
||||
|
||||
def protocol_of(metadata: Any) -> int:
|
||||
"""checkpoint 是按哪一版重放协议写的。加这个标记之前的都算 1。"""
|
||||
value = (metadata or {}).get(PROTOCOL_KEY) if isinstance(metadata, dict) else None
|
||||
return int(value) if isinstance(value, int) else 1
|
||||
|
||||
|
||||
def _in_graph() -> bool:
|
||||
try:
|
||||
get_config()
|
||||
except RuntimeError: # 不在图执行上下文里(单独调用执行器的测试)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
async def once(ctx: NodeContext, event_type: EventType | str, **data: Any) -> None:
|
||||
"""发一条事件,节点重放时不再发。"""
|
||||
if not _in_graph():
|
||||
ctx.emit(event_type, **data)
|
||||
return
|
||||
|
||||
@task
|
||||
async def record(kind: str) -> bool:
|
||||
ctx.emit(kind, **data)
|
||||
return True
|
||||
|
||||
await record(str(event_type))
|
||||
|
||||
|
||||
async def ask(ctx: NodeContext, payload: dict[str, Any], **request: Any) -> Any:
|
||||
"""请人审批:human.requested 只在第一次走到这里时发,然后停下等答复。
|
||||
|
||||
返回答复。答复读完之后由调用方用 once() 发 human.resolved——那一条也只该在
|
||||
答复真正到达的那次执行里出现。
|
||||
"""
|
||||
await once(ctx, EventType.HUMAN_REQUESTED, **request)
|
||||
return interrupt(payload)
|
||||
@@ -7,6 +7,7 @@ from typing import Any
|
||||
|
||||
from app.core.events import EventType
|
||||
from app.engine.issuance import extract_numbers, trace_numbers
|
||||
from app.engine.toolcalls import leaked_markup
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 跑完之后的复核层。
|
||||
@@ -70,6 +71,13 @@ WARN_CODES: dict[str, tuple[str, str]] = {
|
||||
"validate_retry": ("validate_retry", DEGRADED),
|
||||
"sandbox_reset": ("sandbox_reset", DEGRADED),
|
||||
"retrieve_degraded": ("retrieve_degraded", DEGRADED),
|
||||
# 模型把工具调用写成了文字。纠正一次好了的,答案是真查过的,只记缺口;
|
||||
# 没好的那次节点已经判失败,node_failed 会按 BROKEN 算
|
||||
"tool_markup_leak": ("tool_markup_leak", DEGRADED),
|
||||
# 协作团队用完轮数、按降档交付:交来的是成员原话,不是调度者认可的结论
|
||||
"team_exhausted": ("team_exhausted", BROKEN),
|
||||
# 校验节点的修复编出了原文没有的值,这次修复被作废
|
||||
"repair_invented": ("repair_invented", DEGRADED),
|
||||
}
|
||||
|
||||
# 这些 kind 重跑一次大概率能好:原因说得清,且不是「问题本身没问明白」。
|
||||
@@ -178,6 +186,9 @@ def scan(events: Iterable[Any], output: Mapping[str, Any] | None = None) -> list
|
||||
add("empty_output", "这次运行没有产出任何成果内容", BROKEN)
|
||||
elif any(mark in text for mark in _PLACEHOLDER_MARKS):
|
||||
add("placeholder_output", "交出来的是一句内部流程说明,不是对问题的回答", BROKEN)
|
||||
elif leaked_markup(text):
|
||||
# 老运行、或者绕过了节点检查的路径:成果本身就是一段没执行的工具调用标记
|
||||
add("markup_output", "交出来的是一段没有执行的工具调用标记,不是对问题的回答", BROKEN)
|
||||
|
||||
return signals
|
||||
|
||||
|
||||
+295
-63
@@ -5,6 +5,7 @@ import contextlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
@@ -15,13 +16,14 @@ from sqlalchemy import select, update
|
||||
|
||||
from app.core.bus import bus
|
||||
from app.core.config import settings
|
||||
from app.core.errors import describe_exception, raw_detail
|
||||
from app.core.events import EventType, RunEventModel
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import Approval, Run, RunEvent, Workflow
|
||||
from app.engine.compiler import compile_graph, initial_state
|
||||
from app.engine.context import NodeError, RunContext
|
||||
from app.engine.errors import describe_exception, raw_detail
|
||||
from app.engine.schema import GraphSpec, loop_steps, topology_of, validate_graph
|
||||
from app.engine.replay import PROTOCOL, PROTOCOL_KEY, protocol_of
|
||||
from app.engine.schema import GraphSpec, NodeType, loop_steps, topology_of, validate_graph
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -42,6 +44,8 @@ class RunManager:
|
||||
self._closing = False
|
||||
#: 已经跑完、正在落状态和封存的运行。关停不去打断它们
|
||||
self._finalizing: set[str] = set()
|
||||
#: 谁停的:取消执行任务时记下,run.cancelled 和关掉的审批上写得出人
|
||||
self._stopped_by: dict[str, str | None] = {}
|
||||
|
||||
# ---------------- 生命周期 ----------------
|
||||
|
||||
@@ -111,16 +115,7 @@ class RunManager:
|
||||
persist: bool = True,
|
||||
ts: float | None = None,
|
||||
) -> None:
|
||||
event = RunEventModel(
|
||||
run_id=run_id,
|
||||
seq=bus.next_seq(run_id),
|
||||
type=EventType(str(event_type)),
|
||||
node_id=node_id,
|
||||
data=data or {},
|
||||
# 节点里发出的事件带着它发生的时刻。以前一律取转发时刻:并行的成员
|
||||
# 先做完的那条也要排到整轮结束才被转发,时间线上的耗时就全错了
|
||||
**({"ts": ts} if ts else {}),
|
||||
)
|
||||
event = self._event(run_id, event_type, node_id=node_id, data=data, ts=ts)
|
||||
# 先落库,再广播。顺序反过来会漏事件,而且是结构性的漏:
|
||||
#
|
||||
# 订阅者的完整性靠"读历史 + 接实时"两段拼起来。它先订阅、再读历史,
|
||||
@@ -133,22 +128,30 @@ class RunManager:
|
||||
# 一半几率就这么没了——界面表现为某个节点永远在转圈。
|
||||
if persist and event.type not in _EPHEMERAL:
|
||||
async with SessionLocal() as session:
|
||||
session.add(
|
||||
RunEvent(
|
||||
run_id=run_id,
|
||||
seq=event.seq,
|
||||
type=str(event.type),
|
||||
node_id=event.node_id,
|
||||
ts=event.ts,
|
||||
data=event.data,
|
||||
)
|
||||
)
|
||||
await session.execute(
|
||||
update(Run).where(Run.id == run_id).values(last_seq=event.seq)
|
||||
)
|
||||
await _stage(session, event)
|
||||
await session.commit()
|
||||
await bus.publish(event)
|
||||
|
||||
@staticmethod
|
||||
def _event(
|
||||
run_id: str,
|
||||
event_type: EventType | str,
|
||||
*,
|
||||
node_id: str | None = None,
|
||||
data: dict[str, Any] | None = None,
|
||||
ts: float | None = None,
|
||||
) -> RunEventModel:
|
||||
return RunEventModel(
|
||||
run_id=run_id,
|
||||
seq=bus.next_seq(run_id),
|
||||
type=EventType(str(event_type)),
|
||||
node_id=node_id,
|
||||
data=data or {},
|
||||
# 节点里发出的事件带着它发生的时刻。以前一律取转发时刻:并行的成员
|
||||
# 先做完的那条也要排到整轮结束才被转发,时间线上的耗时就全错了
|
||||
**({"ts": ts} if ts else {}),
|
||||
)
|
||||
|
||||
async def note(
|
||||
self, run_id: str, event_type: EventType | str, *, node_id: str | None = None,
|
||||
**data: Any,
|
||||
@@ -256,6 +259,11 @@ class RunManager:
|
||||
"这次运行没有可恢复的断点(很可能重启前还没真正开始跑)。"
|
||||
"请重新发起一次运行,而不是恢复——继续下去只会用默认值跑出一份假结果。"
|
||||
)
|
||||
if stale := await _stale_replay(run_id, spec, snapshot):
|
||||
raise ValueError(
|
||||
f"这次运行是升级前停在「{stale}」上的,引擎记录断点的方式已经变了:现在恢复,"
|
||||
f"「{stale}」里已经执行过的工具会再执行一次。请放弃这次运行,重新发起"
|
||||
)
|
||||
|
||||
answers: dict[str, Any] = {}
|
||||
async with SessionLocal() as session:
|
||||
@@ -283,14 +291,21 @@ class RunManager:
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
if target is not None:
|
||||
target.status = "answered" # 已回复,但还没提交给引擎
|
||||
# 存全文,不能用 _safe 截:多条审批并存时,交给引擎的就是这一份
|
||||
# (见下面 answers)。截过的版本会把人工改过的长稿砍掉一截再送进节点
|
||||
full = json.loads(json.dumps(response, ensure_ascii=False, default=str))
|
||||
target.response = full if isinstance(full, dict) else {"value": full}
|
||||
target.resolved_at = now
|
||||
if actor:
|
||||
target.resolved_by = actor
|
||||
# 条件更新:上面读到它还是 pending,到这里之间可能已经被放弃运行关掉
|
||||
# (或者另一个人先批了)。无条件写回去,会把关掉的审批又改成已回复
|
||||
marked = await session.execute(
|
||||
update(Approval)
|
||||
.where(Approval.id == target.id, Approval.status == "pending")
|
||||
.values(status="answered", # 已回复,但还没提交给引擎
|
||||
response=full if isinstance(full, dict) else {"value": full},
|
||||
resolved_at=now, **({"resolved_by": actor} if actor else {}))
|
||||
)
|
||||
if marked.rowcount != 1:
|
||||
await session.rollback()
|
||||
raise ValueError("这条审批已经处理过了,或者这次运行已经放弃了。刷新看看最新状态")
|
||||
await session.commit()
|
||||
|
||||
# 凑齐没有?引擎还在等的每一个 interrupt 都得有答案
|
||||
@@ -299,7 +314,7 @@ class RunManager:
|
||||
select(Approval).where(
|
||||
Approval.run_id == run_id,
|
||||
Approval.status.in_(["answered", "pending"]),
|
||||
)
|
||||
).execution_options(populate_existing=True)
|
||||
)
|
||||
).scalars())
|
||||
by_iid = {a.interrupt_id: a for a in answered if a.interrupt_id}
|
||||
@@ -321,19 +336,26 @@ class RunManager:
|
||||
# 还差人没回。保持 interrupted,把已回复的那条留在 answered 上等齐
|
||||
await session.commit()
|
||||
run = await session.get(Run, run_id)
|
||||
if run.status != "interrupted":
|
||||
# 审批没了是因为运行在这期间被放弃了:不能回一个「已记下」
|
||||
raise ValueError(_cannot_resume(run.status))
|
||||
return run
|
||||
|
||||
# 齐了:正式落 resolved,然后驱动引擎。谁批的跟着交给节点,
|
||||
# human.resolved 里才写得出签批人
|
||||
actors: dict[str, str | None] = {}
|
||||
for rec in answered:
|
||||
if rec.status == "answered":
|
||||
rec.status = "resolved"
|
||||
actors[rec.node_id] = rec.resolved_by
|
||||
ready = [rec for rec in answered if rec.status == "answered"]
|
||||
actors: dict[str, str | None] = {rec.node_id: rec.resolved_by for rec in ready}
|
||||
# 回到 running 也用条件更新占住:从上面读状态到这里隔了好几次 await,
|
||||
# 放弃运行可能正好在这中间把它收成了 cancelled(已经封存、发过 run.cancelled)。
|
||||
# 无条件写 running,一次取消了的运行就又被拉起来跑了
|
||||
await _claim(session, run_id, ("interrupted",), _cannot_resume)
|
||||
await session.execute(
|
||||
update(Approval)
|
||||
.where(Approval.id.in_([rec.id for rec in ready]), Approval.status == "answered")
|
||||
.values(status="resolved")
|
||||
)
|
||||
run = await session.get(Run, run_id)
|
||||
bus.set_seq(run_id, run.last_seq)
|
||||
run.status = "running"
|
||||
run.error = None
|
||||
await session.commit()
|
||||
await session.refresh(run)
|
||||
|
||||
@@ -356,7 +378,7 @@ class RunManager:
|
||||
))
|
||||
self._tasks[run_id] = asyncio.create_task(
|
||||
self._drive(run_id, spec, command, workflow_id=workflow_id, **carried,
|
||||
resumed=[str(n) for n in (getattr(snapshot, "next", None) or ())],
|
||||
resumed=sorted(_replayed(snapshot)),
|
||||
actors=actors)
|
||||
)
|
||||
return run
|
||||
@@ -389,6 +411,7 @@ class RunManager:
|
||||
)).first() is not None
|
||||
if not (run.status == "failed" or (run.status == "interrupted" and not has_pending)):
|
||||
raise ValueError(_cannot_continue(run.status, has_pending))
|
||||
observed = run.status
|
||||
spec = GraphSpec.model_validate(run.graph)
|
||||
workflow_id = run.workflow_id
|
||||
carried = _carried(run)
|
||||
@@ -419,17 +442,22 @@ class RunManager:
|
||||
"这次运行没有留下可以接着跑的断点(多半是还没跑到第一个节点就挂了)。"
|
||||
"请重新发起一次运行——继续下去只会从头跑一遍,还看不出来。"
|
||||
)
|
||||
if stale := await _stale_replay(run_id, spec, snapshot):
|
||||
raise ValueError(
|
||||
f"这次运行是升级前停在「{stale}」上的,引擎记录断点的方式已经变了:现在接着跑,"
|
||||
f"「{stale}」里已经执行过的工具会再执行一次。请重新发起一次运行"
|
||||
)
|
||||
|
||||
done = [n for n in (snapshot.values or {}).get("nodes", {}) if n not in pending]
|
||||
async with SessionLocal() as session:
|
||||
# 和 resume 一样用条件更新占住:读状态之后,放弃运行、或者另一次接着跑
|
||||
# 可能已经先动了它
|
||||
await _claim(session, run_id, (observed,),
|
||||
lambda status: _cannot_continue(status, False),
|
||||
**({"graph": spec.model_dump(mode="json")} if graph is not None else {}),
|
||||
**({"started_by": actor} if actor else {}))
|
||||
run = await session.get(Run, run_id)
|
||||
bus.set_seq(run_id, run.last_seq)
|
||||
run.status = "running"
|
||||
run.error = None
|
||||
if graph is not None:
|
||||
run.graph = spec.model_dump(mode="json")
|
||||
if actor:
|
||||
run.started_by = actor
|
||||
await session.commit()
|
||||
await session.refresh(run)
|
||||
|
||||
@@ -450,12 +478,65 @@ class RunManager:
|
||||
)
|
||||
return run
|
||||
|
||||
async def cancel(self, run_id: str) -> bool:
|
||||
async def cancel(self, run_id: str, *, actor: str | None = None) -> str | None:
|
||||
"""停止一次运行。返回 "stopping"(执行任务已取消,终态由它自己收尾)、
|
||||
"cancelled"(停在断点上的,这里直接收成终态),或者 None(已经是终态、或不存在)。
|
||||
|
||||
停在断点上的运行——等审批的、服务重启挂起的——手上没有执行任务。以前这里只会
|
||||
去取消任务,于是它们一律「不在执行中」:待审批的那张卡只能批了它、让它跑完。
|
||||
"""
|
||||
if run_id in self._finalizing:
|
||||
# 执行任务已经跑完、正在落状态——刚发出 run.interrupted、还在写 interrupted
|
||||
# 的那一刻,界面上已经给出了「放弃这次运行」。这时取消任务会把收尾从中间
|
||||
# 打断:状态停在 running、审批还挂着、任务却没了,再点一次只剩 409。
|
||||
# 等它落完,再按落下的状态处理
|
||||
await self.wait_idle(run_id, timeout=30.0)
|
||||
if run_id in self._finalizing: # 收尾卡住了(库被锁着):也不去打断它
|
||||
return None
|
||||
task = self._tasks.get(run_id)
|
||||
if task and not task.done():
|
||||
self._stopped_by[run_id] = actor
|
||||
task.cancel()
|
||||
return True
|
||||
return False
|
||||
return "stopping"
|
||||
return "cancelled" if await self._abandon(run_id, actor) else None
|
||||
|
||||
async def _abandon(self, run_id: str, actor: str | None) -> bool:
|
||||
"""把停在断点上的运行收成 cancelled:关掉待审批、发 run.cancelled、封存。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
async with SessionLocal() as session:
|
||||
# 条件更新占住这次收尾:同一时刻有人批了它(resume 把它改回 running),
|
||||
# 或者另一个取消先到了,这里就什么都不做
|
||||
claimed = await session.execute(
|
||||
update(Run).where(Run.id == run_id, Run.status == "interrupted")
|
||||
.values(status="cancelled", finished_at=now)
|
||||
)
|
||||
if claimed.rowcount != 1:
|
||||
await session.rollback()
|
||||
return False
|
||||
closed = await _close_approvals(session, run_id, actor, now)
|
||||
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 "用户取消:挂起期间放弃了这次运行"
|
||||
bus.set_seq(run_id, run.last_seq or 0)
|
||||
# 和状态同一个事务提交,理由同 _finalize
|
||||
event = self._event(run_id, EventType.RUN_CANCELLED, data={
|
||||
"timing": timing, "actor": actor,
|
||||
"message": f"放弃了这次运行,{closed} 条待审批一并关闭" if closed
|
||||
else "放弃了这次挂起的运行",
|
||||
})
|
||||
await _stage(session, event, run)
|
||||
await session.commit()
|
||||
|
||||
await bus.publish(event)
|
||||
await self._seal(run_id)
|
||||
# 等审批时在线的连接没有关(它还在等恢复),这里让它收到终态再结束
|
||||
await bus.close(run_id)
|
||||
with contextlib.suppress(Exception):
|
||||
from app.sandbox.manager import sandbox_manager
|
||||
|
||||
await sandbox_manager.cleanup(run_id)
|
||||
return True
|
||||
|
||||
def is_active(self, run_id: str) -> bool:
|
||||
task = self._tasks.get(run_id)
|
||||
@@ -512,7 +593,9 @@ class RunManager:
|
||||
# 实际生效的运行参数进事件流,也就进了封存清单:
|
||||
# 正式运行查的是哪个库、审批默认是什么,事后可复核
|
||||
"memory_scope": memory_scope, "collection": collection,
|
||||
"approval_default": approval_default},
|
||||
"approval_default": approval_default,
|
||||
# 这一段是按哪一版重放协议跑的,恢复时据此认出升级前做下的工作
|
||||
"replay_protocol": PROTOCOL},
|
||||
)
|
||||
|
||||
run_ctx = RunContext(
|
||||
@@ -531,6 +614,8 @@ class RunManager:
|
||||
config = {
|
||||
"configurable": {"thread_id": run_id},
|
||||
"recursion_limit": settings.max_graph_steps + extra_steps,
|
||||
# 进每个 checkpoint 的 metadata:恢复时据此认出旧版引擎停下的断点
|
||||
"metadata": {PROTOCOL_KEY: PROTOCOL},
|
||||
}
|
||||
|
||||
interrupted = False
|
||||
@@ -569,7 +654,7 @@ class RunManager:
|
||||
else:
|
||||
status = "cancelled"
|
||||
error = "用户取消"
|
||||
terminal = (EventType.RUN_CANCELLED, {})
|
||||
terminal = (EventType.RUN_CANCELLED, {"actor": self._stopped_by.pop(run_id, None)})
|
||||
raise
|
||||
except TimeoutError as e:
|
||||
status = "failed"
|
||||
@@ -611,6 +696,7 @@ class RunManager:
|
||||
# gather 在别的事件循环里炸开
|
||||
self._finalizing.discard(run_id)
|
||||
self._tasks.pop(run_id, None)
|
||||
self._stopped_by.pop(run_id, None)
|
||||
# 运行到终态就把沙箱会话收掉。thread_id 每个 run 都是新的,
|
||||
# 不收的话每跑一次带代码节点的图就多一台常驻 microVM(几百 MB),
|
||||
# 而且没有任何自动回收路径会碰它——闲置回收只在"下次有人执行
|
||||
@@ -692,13 +778,41 @@ class RunManager:
|
||||
now = datetime.now(timezone.utc)
|
||||
timing = {"wall_ms": elapsed_ms, "active_ms": elapsed_ms, "wait_ms": 0}
|
||||
|
||||
# 终态事件和运行记录在同一个事务里提交,提交之后再广播。两边都有人在读:
|
||||
# 读到 failed 的一方马上去翻事件,要翻得到 run.failed(报错原因和定位都在
|
||||
# 那条事件里);收到 run.finished 的一方马上 GET 这次运行取完整成果(事件里
|
||||
# 的 output 是截断的),要读得到 succeeded 和 output。分两次提交,总有一边
|
||||
# 会读到半截——以前先提交状态,前一种偶尔翻不到;反过来先落事件,后一种
|
||||
# 每次都读到 running 和空的 output
|
||||
event: RunEventModel | None = None
|
||||
async with SessionLocal() as session:
|
||||
run = await session.get(Run, run_id)
|
||||
if run:
|
||||
timing = await _timing(session, run, elapsed_ms, now)
|
||||
if status != "succeeded":
|
||||
# 状态里的用量只算跑完了的节点。失败、取消、停在审批上的那个节点已经
|
||||
# 花出去的调用(校验修复、agent 的前几步)只在 llm.end 里——以前这部分
|
||||
# 在运行记录上凭空消失,失败的运行看着像没花钱
|
||||
usage = _spent(usage, await _usage_of_events(session, run_id))
|
||||
# duration_ms 是各段执行时长之和(= active_ms)。以前用这一段的耗时
|
||||
# 覆盖它:87 秒、中间等过一次审批的运行,列表上写着 22ms
|
||||
usage.update(duration_ms=timing["active_ms"], **timing)
|
||||
|
||||
if status == "succeeded":
|
||||
# 事件里的 output 仍然截断(事件体积要控制),但截了就要说:消费方据此
|
||||
# 回源 GET /api/runs/{id} 取全文。以前截得悄无声息,问数据页把 2000 字处
|
||||
# 切断的半截答案当成完整结论落了库
|
||||
clipped, truncated = _clip(output)
|
||||
data: dict[str, Any] = {"output": clipped, "usage": usage,
|
||||
"duration_ms": timing["active_ms"], "timing": timing}
|
||||
if truncated:
|
||||
data["output_truncated"] = True
|
||||
event = self._event(run_id, EventType.RUN_FINISHED, data=data)
|
||||
elif terminal is not None:
|
||||
kind, data = terminal
|
||||
event = self._event(run_id, kind, data={**data, "timing": timing})
|
||||
|
||||
if run:
|
||||
run.status = status
|
||||
run.error = error
|
||||
run.output = output
|
||||
@@ -706,21 +820,17 @@ class RunManager:
|
||||
run.error_node_id = error_node
|
||||
if status != "interrupted":
|
||||
run.finished_at = now
|
||||
if status in ("failed", "cancelled"):
|
||||
# 并行支路上已经停下来等人的那张审批卡,运行结束了它也就没有意义了;
|
||||
# 留着的话它一直挂在全局待办里,批了也只会被告知运行不在断点上
|
||||
actor = terminal[1].get("actor") if terminal else None
|
||||
await _close_approvals(session, run_id, actor, now)
|
||||
if event is not None:
|
||||
await _stage(session, event, run)
|
||||
await session.commit()
|
||||
if event is not None:
|
||||
await bus.publish(event)
|
||||
|
||||
if status == "succeeded":
|
||||
# 事件里的 output 仍然截断(事件体积要控制),但截了就要说:消费方据此
|
||||
# 回源 GET /api/runs/{id} 取全文。以前截得悄无声息,问数据页把 2000 字处
|
||||
# 切断的半截答案当成完整结论落了库
|
||||
clipped, truncated = _clip(output)
|
||||
data: dict[str, Any] = {"output": clipped, "usage": usage,
|
||||
"duration_ms": timing["active_ms"], "timing": timing}
|
||||
if truncated:
|
||||
data["output_truncated"] = True
|
||||
await self._emit(run_id, EventType.RUN_FINISHED, data=data)
|
||||
elif terminal is not None:
|
||||
kind, data = terminal
|
||||
await self._emit(run_id, kind, data={**data, "timing": timing})
|
||||
if status != "interrupted":
|
||||
# 终态事件落库之后再封存。以前在 run.finished 之前算,清单里恰恰少了
|
||||
# 那条宣布"跑完了、成果是什么"的事件——改它的成果,清单照样对得上。
|
||||
@@ -900,6 +1010,128 @@ async def _approval_default(*, run_class: str) -> str:
|
||||
return tool_approval_default(await run_defaults(session))
|
||||
|
||||
|
||||
def _replayed(snapshot: Any) -> set[str]:
|
||||
"""从断点驱动时要(重新)执行的节点:还没跑的(next),加上停在 interrupt 上、或者
|
||||
失败了的。恢复过一次的节点手里已经有答复的写入,不在 next 里,只能从 tasks 上认。"""
|
||||
again = {str(x) for x in getattr(snapshot, "next", None) or ()}
|
||||
again.update(str(t.name) for t in getattr(snapshot, "tasks", None) or ()
|
||||
if getattr(t, "interrupts", None) or getattr(t, "error", None))
|
||||
return again
|
||||
|
||||
|
||||
async def _stale_replay(run_id: str, spec: GraphSpec, snapshot: Any) -> str | None:
|
||||
"""旧版重放协议写下的断点,按现在的代码重放会不会把做过的工具再做一遍。会的话返回节点名。
|
||||
|
||||
有风险的是:断点之后,旧版代码在这个节点里已经执行过工具、或者已经批过一次。它们
|
||||
的 task 缓存排在旧的位置上,新代码多插了记录 task,位置全错开了。停在第一次审批上、
|
||||
之前什么都没做的,重放只会多发一条 human.requested,照常放行;人工审批节点同理。
|
||||
|
||||
「断点之后」按 checkpoint 的写入时刻算:同一个 superstep 里恢复不会写新的 checkpoint,
|
||||
所以升级后恢复过一次的运行,断点仍是旧版写的,而那之后的工作是新版做的——
|
||||
哪一段是哪一版,看那一段 run.started 里记的 replay_protocol。
|
||||
"""
|
||||
if protocol_of(getattr(snapshot, "metadata", None)) >= PROTOCOL:
|
||||
return None
|
||||
nodes = spec.node_map()
|
||||
suspects = [n for n in _replayed(snapshot) if n in nodes and nodes[n].type != NodeType.HUMAN]
|
||||
if not suspects:
|
||||
return None
|
||||
try:
|
||||
since = datetime.fromisoformat(str(snapshot.created_at)).timestamp()
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
since = 0.0
|
||||
async with SessionLocal() as session:
|
||||
rows = (await session.execute(
|
||||
select(RunEvent.type, RunEvent.node_id, RunEvent.ts, RunEvent.data)
|
||||
.where(RunEvent.run_id == run_id,
|
||||
RunEvent.type.in_([EventType.RUN_STARTED, EventType.TOOL_START,
|
||||
EventType.HUMAN_RESOLVED]))
|
||||
.order_by(RunEvent.seq)
|
||||
)).all()
|
||||
protocol = 1
|
||||
for kind, owner, ts, data in rows:
|
||||
if kind == EventType.RUN_STARTED:
|
||||
protocol = protocol_of({PROTOCOL_KEY: (data or {}).get("replay_protocol")})
|
||||
continue
|
||||
if protocol >= PROTOCOL or (ts or 0) < since:
|
||||
continue
|
||||
for node_id in suspects:
|
||||
if owner == node_id or (owner or "").startswith(f"{node_id}/"):
|
||||
return nodes[node_id].title or node_id
|
||||
return None
|
||||
|
||||
|
||||
async def _claim(
|
||||
session: Any, run_id: str, expected: tuple[str, ...], refusal: Callable[[str], str],
|
||||
**values: Any,
|
||||
) -> None:
|
||||
"""只在状态仍是 expected 时把运行改成 running;已经被别人改过就回滚、说明原因。"""
|
||||
claimed = await session.execute(
|
||||
update(Run).where(Run.id == run_id, Run.status.in_(expected))
|
||||
.values(status="running", error=None, **values)
|
||||
)
|
||||
if claimed.rowcount != 1:
|
||||
await session.rollback()
|
||||
status = await session.scalar(select(Run.status).where(Run.id == run_id))
|
||||
raise ValueError(refusal(status or ""))
|
||||
|
||||
|
||||
async def _stage(session: Any, event: RunEventModel, run: Run | None = None) -> None:
|
||||
"""把一条事件写进这个 session,随它一起提交。run 已经在 session 里时直接改它的 last_seq。"""
|
||||
session.add(RunEvent(run_id=event.run_id, seq=event.seq, type=str(event.type),
|
||||
node_id=event.node_id, ts=event.ts, data=event.data))
|
||||
if run is not None:
|
||||
run.last_seq = event.seq
|
||||
else:
|
||||
await session.execute(
|
||||
update(Run).where(Run.id == event.run_id).values(last_seq=event.seq)
|
||||
)
|
||||
|
||||
|
||||
async def _close_approvals(session: Any, run_id: str, actor: str | None, now: datetime) -> int:
|
||||
"""运行已经结束,它还没处理完的审批一并关掉。返回关掉了几条。"""
|
||||
rows = list((await session.execute(
|
||||
select(Approval).where(Approval.run_id == run_id,
|
||||
Approval.status.in_(["pending", "answered"]))
|
||||
)).scalars())
|
||||
for approval in rows:
|
||||
approval.status = "cancelled"
|
||||
approval.resolved_at = now
|
||||
approval.resolved_by = actor
|
||||
return len(rows)
|
||||
|
||||
|
||||
_USAGE_KEYS = ("input_tokens", "output_tokens", "cost_usd", "calls")
|
||||
|
||||
|
||||
async def _usage_of_events(session: Any, run_id: str) -> dict[str, Any]:
|
||||
"""按 llm.end 事件逐次加总的用量:每次模型调用都有一条,不管节点最后成没成。"""
|
||||
rows = await session.execute(
|
||||
select(RunEvent.data).where(RunEvent.run_id == run_id, RunEvent.type == EventType.LLM_END)
|
||||
)
|
||||
total: dict[str, Any] = dict.fromkeys(_USAGE_KEYS, 0)
|
||||
for (data,) in rows:
|
||||
for key in _USAGE_KEYS:
|
||||
value = (data or {}).get(key, 1 if key == "calls" else 0)
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
total[key] += value
|
||||
total["cost_usd"] = round(total["cost_usd"], 6)
|
||||
return total
|
||||
|
||||
|
||||
def _spent(state_usage: dict[str, Any], events_usage: dict[str, Any]) -> dict[str, Any]:
|
||||
"""两本账取大的那本。新引擎每次调用都发 llm.end,事件那本不会更少;
|
||||
加这条事件之前的老运行(agent 节点不发 llm.end)状态那本更全。"""
|
||||
out = dict(state_usage)
|
||||
for key in _USAGE_KEYS:
|
||||
mine, theirs = out.get(key) or 0, events_usage.get(key) or 0
|
||||
if isinstance(mine, (int, float)) and theirs > mine:
|
||||
out[key] = theirs
|
||||
if "input_tokens" in out or "output_tokens" in out:
|
||||
out["total_tokens"] = int(out.get("input_tokens") or 0) + int(out.get("output_tokens") or 0)
|
||||
return out
|
||||
|
||||
|
||||
async def _timing(session: Any, run: Run, elapsed_ms: int, now: datetime) -> dict[str, int]:
|
||||
"""wall:从第一次开始到现在的墙钟;active:各段执行时长之和;wait:等人审批的总时长。
|
||||
|
||||
|
||||
+246
-34
@@ -150,6 +150,9 @@ class ValidationIssue(BaseModel):
|
||||
node_id: str | None = None
|
||||
edge_id: str | None = None
|
||||
message: str
|
||||
#: 节点配置里出问题的那个字段:prompt、cases[1].condition、agents[0].system。
|
||||
#: 检查器靠它把问题落到具体的输入框下面;说不清是哪个字段的(连线、图级)为空
|
||||
field: str | None = None
|
||||
|
||||
|
||||
class ValidationResult(BaseModel):
|
||||
@@ -157,9 +160,10 @@ class ValidationResult(BaseModel):
|
||||
issues: list[ValidationIssue] = Field(default_factory=list)
|
||||
|
||||
def add(self, message: str, *, level: str = "error", node_id: str | None = None,
|
||||
edge_id: str | None = None) -> None:
|
||||
edge_id: str | None = None, field: str | None = None) -> None:
|
||||
self.issues.append(
|
||||
ValidationIssue(level=level, message=message, node_id=node_id, edge_id=edge_id) # type: ignore[arg-type]
|
||||
ValidationIssue(level=level, message=message, node_id=node_id, # type: ignore[arg-type]
|
||||
edge_id=edge_id, field=field)
|
||||
)
|
||||
if level == "error":
|
||||
self.ok = False
|
||||
@@ -294,32 +298,33 @@ def innermost_loops(spec: GraphSpec) -> dict[str, str]:
|
||||
return out
|
||||
|
||||
|
||||
def expression_fields(node: GraphNode) -> list[tuple[str, str]]:
|
||||
"""这个节点上按表达式求值的字段:(给人看的名字, 原文)。
|
||||
def expression_fields(node: GraphNode) -> list[tuple[str, str, str]]:
|
||||
"""这个节点上按表达式求值的字段:(给人看的名字, 原文, 字段路径)。
|
||||
|
||||
跟着模式走:foreach 循环的 condition、模板模式整形的 expression 不参与求值,
|
||||
拿它们报错就是误报。
|
||||
"""
|
||||
cfg = node.config
|
||||
out: list[tuple[str, str]] = []
|
||||
out: list[tuple[str, str, str]] = []
|
||||
|
||||
def add(label: str, value: Any) -> None:
|
||||
def add(label: str, value: Any, field: str) -> None:
|
||||
if isinstance(value, str) and value.strip():
|
||||
out.append((label, value))
|
||||
out.append((label, value, field))
|
||||
|
||||
add("跳过条件", cfg.get("skip_if"))
|
||||
add("跳过条件", cfg.get("skip_if"), "skip_if")
|
||||
if node.type == NodeType.BRANCH and cfg.get("mode", "expression") == "expression":
|
||||
for case in cfg.get("cases") or []:
|
||||
for i, case in enumerate(cfg.get("cases") or []):
|
||||
case = case or {}
|
||||
add(f"分支「{case.get('label') or case.get('key') or '?'}」的条件", case.get("condition"))
|
||||
add(f"分支「{case.get('label') or case.get('key') or '?'}」的条件", case.get("condition"),
|
||||
f"cases[{i}].condition")
|
||||
elif node.type == NodeType.LOOP and cfg.get("mode", "foreach") == "while":
|
||||
add("循环条件", cfg.get("condition"))
|
||||
add("循环条件", cfg.get("condition"), "condition")
|
||||
elif node.type == NodeType.TRANSFORM and cfg.get("mode", "expression") == "expression":
|
||||
add("整形表达式", cfg.get("expression"))
|
||||
add("整形表达式", cfg.get("expression"), "expression")
|
||||
elif node.type == NodeType.METRICS:
|
||||
for d in cfg.get("metrics") or []:
|
||||
for i, d in enumerate(cfg.get("metrics") or []):
|
||||
d = d or {}
|
||||
add(f"指标「{d.get('id') or '?'}」的表达式", d.get("expression"))
|
||||
add(f"指标「{d.get('id') or '?'}」的表达式", d.get("expression"), f"metrics[{i}].expression")
|
||||
return out
|
||||
|
||||
|
||||
@@ -345,19 +350,20 @@ def _check_case_keys(node: GraphNode, cases: list[Any], result: ValidationResult
|
||||
case = case or {}
|
||||
key = str(case.get("key") or "").strip()
|
||||
name = case.get("label") or key or f"第 {i} 个"
|
||||
field = f"cases[{i - 1}].key"
|
||||
if not key:
|
||||
result.add(f"「条件分支」的分支「{name}」没有标识(key),连不出边、也走不到它",
|
||||
node_id=node.id)
|
||||
node_id=node.id, field=field)
|
||||
continue
|
||||
if key == "default":
|
||||
result.add(
|
||||
f"分支「{name}」的标识用了 default:这是「其他」兜底出口的保留名,两者会合并成"
|
||||
"同一个出口,跑完分不清走的是哪条。换一个标识,比如 team",
|
||||
level="warning", node_id=node.id,
|
||||
level="warning", node_id=node.id, field=field,
|
||||
)
|
||||
elif key in seen:
|
||||
result.add(f"「条件分支」里有两个分支的标识都是 {key!r}:路由只认标识,"
|
||||
"后一个永远轮不到。给它换一个不重复的标识", node_id=node.id)
|
||||
"后一个永远轮不到。给它换一个不重复的标识", node_id=node.id, field=field)
|
||||
seen.add(key)
|
||||
|
||||
|
||||
@@ -386,43 +392,46 @@ 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)
|
||||
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 case in cases:
|
||||
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!r} 没有连出去的边", 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)
|
||||
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"):
|
||||
result.add("「结构校验」节点需要一个 JSON Schema", node_id=node.id)
|
||||
result.add("「结构校验」节点需要一个 JSON Schema", node_id=node.id, field="schema")
|
||||
elif node.type == NodeType.METRICS:
|
||||
defs = cfg.get("metrics") or []
|
||||
if not defs:
|
||||
result.add("口径卡还没有定义指标", node_id=node.id)
|
||||
for d in defs:
|
||||
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 '(空)'}",
|
||||
node_id=node.id)
|
||||
node_id=node.id, field=f"metrics[{i}]")
|
||||
elif node.type == NodeType.OUTPUT:
|
||||
contract = cfg.get("contract")
|
||||
if contract and not contract.get("metrics_from"):
|
||||
result.add("出具契约缺 metrics_from(指标来自哪个「口径卡」节点)",
|
||||
node_id=node.id)
|
||||
node_id=node.id, field="contract.metrics_from")
|
||||
elif node.type == NodeType.LOOP:
|
||||
if not spec.outgoing(node.id):
|
||||
result.add("「循环」节点没有循环体", node_id=node.id)
|
||||
@@ -433,6 +442,7 @@ def validate_graph(spec: GraphSpec) -> ValidationResult:
|
||||
"没有指定模型,将回退到默认 provider",
|
||||
level="warning",
|
||||
node_id=node.id,
|
||||
field="model",
|
||||
)
|
||||
|
||||
# 表达式:用运行时同一个 parse_expression 先解析一遍。以前写错了只有跑到那一步
|
||||
@@ -441,30 +451,32 @@ def validate_graph(spec: GraphSpec) -> ValidationResult:
|
||||
from app.engine.expressions import ExpressionError, parse_expression
|
||||
|
||||
for node in spec.nodes:
|
||||
for label, text in expression_fields(node):
|
||||
for label, text, field in expression_fields(node):
|
||||
try:
|
||||
_, unwrapped, unknown = parse_expression(text)
|
||||
except ExpressionError as e:
|
||||
result.add(f"{label}写错了:{e}(原文:{text})", node_id=node.id)
|
||||
result.add(f"{label}写错了:{e}(原文:{text})", node_id=node.id, field=field)
|
||||
continue
|
||||
if unwrapped:
|
||||
result.add(
|
||||
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)",
|
||||
level="warning", node_id=node.id,
|
||||
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("while 循环没有写条件,循环体一次都不会跑", 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)
|
||||
result.add("整形节点没有填表达式", node_id=node.id, field="expression")
|
||||
# assign_to 拿到的是 stdout。脚本最后一行写个裸表达式不会输出(那是 notebook
|
||||
# 的行为)——变量是空的,下游的循环条件一上来就不成立、成果也是空的,而整次
|
||||
# 运行照样"成功"。开发库里的「测试 1」就是这样:修好条件之后跑通了,结果为空
|
||||
@@ -478,9 +490,11 @@ def validate_graph(spec: GraphSpec) -> ValidationResult:
|
||||
result.add(
|
||||
f"代码把输出交给 vars.{var},可代码里没有 print:Python 脚本最后一行的表达式"
|
||||
f"不会自动输出,vars.{var} 会是空的。把结果 print 出来;要交给下游一个对象,"
|
||||
"就 print(json.dumps(结果))", node_id=node.id,
|
||||
"就 print(json.dumps(结果))", node_id=node.id, field="code",
|
||||
)
|
||||
|
||||
_check_named_tools(spec, result)
|
||||
|
||||
# 孤儿节点
|
||||
for node in spec.nodes:
|
||||
if node.type in (NodeType.INPUT, NodeType.OUTPUT):
|
||||
@@ -497,6 +511,204 @@ def validate_graph(spec: GraphSpec) -> ValidationResult:
|
||||
# info 级是"产出没人用"这类提示,不进校验(它不影响能不能跑)
|
||||
if issue.level == "info":
|
||||
continue
|
||||
result.add(issue.message, level=issue.level, node_id=issue.node_id)
|
||||
result.add(issue.message, level=issue.level, node_id=issue.node_id,
|
||||
field=issue.field or None)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 提示词点名的工具,节点得真的绑了它
|
||||
#
|
||||
# 一次真实运行:助手改图时把三个查库 agent 的 tools 丢了,提示词里还写着「用
|
||||
# db_query__… 查」。模型拿不到工具,只能写一句「假设调用工具」,再往下编;校验节点
|
||||
# 的修复又替它编了个 0。这张图在跑之前就能认出来。Copilot 的自查读的是同一份
|
||||
# error,搭图时就会交回模型去修。
|
||||
#
|
||||
# 这条是 error,会挡住运行,还会作为 Copilot 自查的阻断项交回模型(模型可能反过来
|
||||
# 把提示词里禁用的工具绑上去),所以宁可漏判不可误判:
|
||||
# - 认得出的工具名才算点名:内置工具、db_query__ / db_schema__ / mcp: 这几种形状,
|
||||
# 以及这张图里别的节点绑过的名字;
|
||||
# - 「不要用 X」「Never call X」「X 的结果」不是在要求用它;
|
||||
# - calculator 这种本身就是个普通词的工具名,只有写在反引号里、或者紧跟在「用 /
|
||||
# 调用 / use / call」后面才算点名;「可以用」「如有需要」「if needed」这类非强制的
|
||||
# 说法也一样。这两种只报 warning。
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_DYNAMIC_TOOL = r"db_(?:query|schema)__[A-Za-z0-9_\-]+|mcp:[\w\-]+/[\w\-.]+"
|
||||
# 工具名紧挨着汉字是常态(「用python_exec核对」),所以边界只排 ASCII 标识符字符
|
||||
_EDGE_BEFORE, _EDGE_AFTER = r"(?<![A-Za-z0-9_:/\-])", r"(?![A-Za-z0-9_\-])"
|
||||
_TEMPLATE_SPAN = re.compile(r"\{\{.*?\}\}", re.S)
|
||||
_NEGATED = re.compile(
|
||||
r"(?:(?:不要|不用|不必|无需|无须|毋须|不需要|不再|别再|别|禁止|停止|不能|不得|不应|不可|避免|切勿|勿|严禁)"
|
||||
r"\s*(?:再|去)?(?:使用|调用|用|执行|运行|跑)?"
|
||||
r"|(?<![A-Za-z])(?:don['’]?t|do\s+not|never|avoid|without|must\s+not|mustn['’]?t|should\s+not"
|
||||
r"|shouldn['’]?t|cannot|can['’]t|no\s+need\s+to|not|no)\s+(?:(?:use|call|invoke|run|execute|using|calling"
|
||||
r"|invoking|running|rely\s+on|touch)\s+)?(?:the\s+|any\s+)?)"
|
||||
r"\s*[「“\"'`]?\s*$", re.I)
|
||||
_REFERENCED = re.compile(r"^\s*[」”\"'`]?\s*(的|返回|给出|查到|产出|输出|结果"
|
||||
r"|(?:'s\b)|(?:results?|outputs?|returned|returns)\b)", re.I)
|
||||
# 普通词形的工具名(calculator)要有明确的「用」字眼紧挨着才算点名
|
||||
_PLAIN_WORD = re.compile(r"[A-Za-z][a-z]*(?:-[a-z]+)*")
|
||||
_USE_VERB = re.compile(r"(?:使用|调用|用|(?<![A-Za-z])(?:use|call|invoke|run))\s*$", re.I)
|
||||
# 非强制的说法:同一句里出现就只算提到,不算要求
|
||||
_OPTIONAL = re.compile(r"可以|可选|如有需要|如需|若需|必要时|需要时|有需要|酌情"
|
||||
r"|(?<![A-Za-z])(?:may|might|can|could|optionally|if\s+(?:needed|necessary|required)"
|
||||
r"|when\s+needed|feel\s+free)(?![A-Za-z])", re.I)
|
||||
_CLAUSE_END = re.compile(r"[。;;!!??\n]|\.(?:\s|$)")
|
||||
# 笼统地要求用工具、却没点名
|
||||
_VAGUE = re.compile(r"(调用|使用|用|借助|通过)\s*(相关|对应|可用|数据库|查询)?\s*工具"
|
||||
r"|查询?数据库|查库|执行\s*SQL|跑\s*SQL", re.I)
|
||||
|
||||
|
||||
def _bound_tools(cfg: dict[str, Any]) -> set[str]:
|
||||
return {t for t in cfg.get("tools") or [] if isinstance(t, str)}
|
||||
|
||||
|
||||
def _covers(bound: set[str], tool: str) -> bool:
|
||||
"""tool 在不在 bound 里。mcp:<server>/*(或只写 mcp:<server>)绑的是这个 server 的全部工具。"""
|
||||
if tool in bound:
|
||||
return True
|
||||
if not tool.startswith("mcp:"):
|
||||
return False
|
||||
server = tool[4:].partition("/")[0]
|
||||
return any(b in (f"mcp:{server}", f"mcp:{server}/", f"mcp:{server}/*") for b in bound)
|
||||
|
||||
|
||||
def _named_tool_pattern(spec: GraphSpec) -> re.Pattern[str]:
|
||||
from app.tools.registry import all_specs
|
||||
|
||||
bound: set[str] = set()
|
||||
for node in spec.nodes:
|
||||
cfg = node.config
|
||||
bound.update(_bound_tools(cfg))
|
||||
if isinstance(cfg.get("tool"), str):
|
||||
bound.add(cfg["tool"])
|
||||
for member in cfg.get("agents") or []:
|
||||
if isinstance(member, dict):
|
||||
bound.update(_bound_tools(member))
|
||||
names = sorted({*all_specs(), *bound}, key=len, reverse=True)
|
||||
literal = "|".join(re.escape(n) for n in names if n)
|
||||
body = f"{_DYNAMIC_TOOL}|{literal}" if literal else _DYNAMIC_TOOL
|
||||
return re.compile(f"{_EDGE_BEFORE}(?:{body}){_EDGE_AFTER}")
|
||||
|
||||
|
||||
# 列举里的分隔:「严禁调用 web_search、web_fetch、http_request 等」「never call a, b or c」
|
||||
_LIST_TAIL = re.compile(r"(?:[\s、,,/和或及与跟以「」“”\"'`]|(?<![A-Za-z])(?:or|and|nor)(?![A-Za-z]))+$",
|
||||
re.I)
|
||||
|
||||
|
||||
def _negated(plain: str, start: int, pattern: re.Pattern[str]) -> bool:
|
||||
"""这个工具名前面是不是一句「不要用」。列举里排在后面的也算:往回跳过前面的工具名和顿号。"""
|
||||
head = plain[max(0, start - 120):start]
|
||||
while True:
|
||||
trimmed = _LIST_TAIL.sub("", head)
|
||||
last = None
|
||||
for last in pattern.finditer(trimmed):
|
||||
pass
|
||||
if last is not None and last.end() == len(trimmed):
|
||||
trimmed = trimmed[:last.start()]
|
||||
if trimmed == head:
|
||||
break
|
||||
head = trimmed
|
||||
return bool(_NEGATED.search(head[-40:] + " "))
|
||||
|
||||
|
||||
def _clause(plain: str, start: int, end: int) -> str:
|
||||
"""工具名所在的那一句。"""
|
||||
before = [m.end() for m in _CLAUSE_END.finditer(plain, 0, start)]
|
||||
after = _CLAUSE_END.search(plain, end)
|
||||
return plain[before[-1] if before else 0:after.start() if after else len(plain)]
|
||||
|
||||
|
||||
def _asked_tools(text: str, pattern: re.Pattern[str]) -> dict[str, bool]:
|
||||
"""文本里被要求使用的工具名,按出现顺序。值是「是不是明确要求」:否的只算提到了。"""
|
||||
# {{ }} 里的是模板引用,不是在点名工具;换成等长空白,位置不变
|
||||
plain = _TEMPLATE_SPAN.sub(lambda m: " " * len(m.group(0)), text)
|
||||
found: dict[str, bool] = {}
|
||||
for m in pattern.finditer(plain):
|
||||
if _negated(plain, m.start(), pattern) or _REFERENCED.match(plain[m.end():m.end() + 12]):
|
||||
continue
|
||||
name = m.group(0)
|
||||
explicit = not _OPTIONAL.search(_clause(plain, m.start(), m.end()))
|
||||
if explicit and _PLAIN_WORD.fullmatch(name):
|
||||
quoted = plain[m.start() - 1:m.start()] == "`" and plain[m.end():m.end() + 1] == "`"
|
||||
explicit = quoted or bool(_USE_VERB.search(plain[max(0, m.start() - 12):m.start()]))
|
||||
found[name] = found.get(name, False) or explicit
|
||||
return found
|
||||
|
||||
|
||||
def _asks_vaguely(text: str) -> bool:
|
||||
plain = _TEMPLATE_SPAN.sub(" ", text)
|
||||
return any(not _NEGATED.search(plain[max(0, m.start() - 12):m.start()])
|
||||
for m in _VAGUE.finditer(plain))
|
||||
|
||||
|
||||
def _check_named_tools(spec: GraphSpec, result: ValidationResult) -> None:
|
||||
agents = [n for n in spec.nodes if n.type in (NodeType.AGENT, NodeType.SUPERVISOR)]
|
||||
if not agents:
|
||||
return
|
||||
pattern = _named_tool_pattern(spec)
|
||||
|
||||
def check(node: GraphNode, texts: list[tuple[str, Any]], tools: Any, who: str = "") -> None:
|
||||
bound = {t for t in tools or [] if isinstance(t, str)}
|
||||
vague_at: str | None = None
|
||||
reported: set[str] = set()
|
||||
asked: dict[str, tuple[bool, str]] = {}
|
||||
for field, text in texts:
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
continue
|
||||
for tool, explicit in _asked_tools(text, pattern).items():
|
||||
# system 和 prompt 里都点了同一个工具,报一次就够:指到先出现的那处,
|
||||
# 哪一处是明确要求就按要求算
|
||||
seen = asked.get(tool)
|
||||
asked[tool] = (explicit or bool(seen and seen[0]), seen[1] if seen else field)
|
||||
if not bound and vague_at is None and _asks_vaguely(text):
|
||||
vague_at = field
|
||||
for tool, (explicit, field) in asked.items():
|
||||
if _covers(bound, tool):
|
||||
continue
|
||||
reported.add(tool)
|
||||
if explicit:
|
||||
message = (f"{who}的提示词要求用「{tool}」,但没有给这个成员绑定它" if who
|
||||
else f"提示词要求用「{tool}」,但节点没有绑定它")
|
||||
result.add(f"{message}:运行时模型拿不到这个工具,只能编一个结果出来。"
|
||||
"把它加进工具里,或者改掉提示词里的要求",
|
||||
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:
|
||||
cfg = node.config
|
||||
if node.type == NodeType.AGENT:
|
||||
check(node, [("system", cfg.get("system")), ("prompt", cfg.get("prompt"))],
|
||||
cfg.get("tools"))
|
||||
continue
|
||||
members = [m for m in cfg.get("agents") or [] if isinstance(m, dict)]
|
||||
team_tools: set[str] = set()
|
||||
for i, member in enumerate(members):
|
||||
name = member.get("name") or f"agent{i}"
|
||||
team_tools.update(_bound_tools(member))
|
||||
check(node, [(f"agents[{i}].system", member.get("system"))], member.get("tools"),
|
||||
who=f"成员「{name}」")
|
||||
# 协作目标是给调度者看的:点了名的工具,至少得有一个成员拿得到
|
||||
goal = cfg.get("goal")
|
||||
if isinstance(goal, str):
|
||||
for tool, explicit in _asked_tools(goal, pattern).items():
|
||||
if _covers(team_tools, tool):
|
||||
continue
|
||||
if explicit:
|
||||
result.add(f"协作目标要求用「{tool}」,但没有哪个成员绑定了它:调度者派出去的人"
|
||||
"谁都调不了它。给负责的成员加上这个工具,或者改掉目标里的要求",
|
||||
node_id=node.id, field="goal")
|
||||
else:
|
||||
result.add(f"协作目标提到了「{tool}」,但没有哪个成员绑定了它:如果是要成员"
|
||||
"调用它,谁都拿不到。需要就给负责的成员加上",
|
||||
level="warning", node_id=node.id, field="goal")
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"""节点里调工具的公共部分:时限,以及「模型把工具调用写成了文字」的识别。
|
||||
|
||||
agent 节点、协作成员、工具节点三处都在调工具。以前时限只有数据层自己那一道
|
||||
wait_for,而 wait_for 取消之后要等被取消的那一方收完尾:驱动关连接、回滚要排在
|
||||
数据库那条语句后面。真实运行里一次「查询超过 30s 被中断」实际等了 90 秒——时限
|
||||
到了、取消也发了,控制权却迟迟回不来,报错写的还是 30。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Awaitable
|
||||
|
||||
QUERY_PREFIX = "db_query__"
|
||||
|
||||
#: 到了工具自己的时限之后再宽限多久才放弃。工具自己的超时报错(「查询超过 30s
|
||||
#: 被中断,加上 WHERE…」)比这里的说法更具体,先让它到;收尾卡住了才由这里兜底
|
||||
GRACE_S = 1.0
|
||||
|
||||
#: 沙箱代码工具的时限来自参数(缺省 30 秒),由沙箱自己执行
|
||||
_SANDBOX_TOOLS = {"python_exec", "shell_exec", "run_code"}
|
||||
_HTTP_TOOLS = {"http_request", "web_fetch"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Limit:
|
||||
"""一次工具调用的时限。seconds 随 tool.start 发给界面,界面据此说「已超出 30s 上限」。"""
|
||||
|
||||
seconds: float
|
||||
#: 到点由引擎收回控制权。只对「时限到了、收尾却可能卡住」的类型开:沙箱的时限
|
||||
#: 里还含着起虚拟机、装依赖,按它掐会误杀冷启动;HTTP 客户端自己掐得准
|
||||
enforce: bool
|
||||
#: query | declared | sandbox | http
|
||||
kind: str
|
||||
|
||||
@property
|
||||
def self_timed(self) -> bool:
|
||||
"""工具自己也按这个时限掐、并且自己收尾(数据层的查询)。引擎放弃它时只撒手、
|
||||
不再取消:它那时多半正在收尾,再取消一次会把关连接那一步打断,连接就再也回不到池里。"""
|
||||
return self.kind == "query"
|
||||
|
||||
|
||||
def limit_of(tool: Any, name: str, args: dict[str, Any]) -> Limit | None:
|
||||
"""这次调用的时限。说不出来就是 None——界面上不写上限,引擎也不掐。
|
||||
|
||||
工具自己在 metadata["timeout_s"] 里声明的优先(数字,或者按参数算的函数)。
|
||||
"""
|
||||
meta = (getattr(tool, "metadata", None) or {}) if tool is not None else {}
|
||||
declared = meta.get("timeout_s")
|
||||
if callable(declared):
|
||||
declared = declared(args)
|
||||
if not (isinstance(declared, (int, float)) and not isinstance(declared, bool) and declared > 0):
|
||||
declared = None
|
||||
if name.startswith(QUERY_PREFIX):
|
||||
# 数据层自己按这个时限掐、自己收尾。数据源声明了自己的时限就用它,
|
||||
# 否则按模块属性现取数据层的缺省——那个数只有这一处定义
|
||||
from app.data import guard
|
||||
|
||||
return Limit(float(declared or guard.QueryLimits().timeout_seconds), True, "query")
|
||||
if declared:
|
||||
return Limit(float(declared), True, "declared")
|
||||
if name in _SANDBOX_TOOLS:
|
||||
try:
|
||||
seconds = float(args.get("timeout") or 30)
|
||||
except (TypeError, ValueError):
|
||||
seconds = 30.0
|
||||
return Limit(seconds, False, "sandbox")
|
||||
if name in _HTTP_TOOLS:
|
||||
from app.core.config import settings
|
||||
|
||||
return Limit(float(settings.http_tool_timeout), False, "http")
|
||||
return None
|
||||
|
||||
|
||||
def limit_fields(limit: Limit | None) -> dict[str, Any]:
|
||||
"""tool.start 上附带的时限字段。没有时限就什么都不带,老客户端照旧。"""
|
||||
if limit is None:
|
||||
return {}
|
||||
return {"timeout_s": int(limit.seconds) if limit.seconds.is_integer() else limit.seconds}
|
||||
|
||||
|
||||
def _seconds(value: float) -> str:
|
||||
return str(int(value)) if float(value).is_integer() else f"{value:g}"
|
||||
|
||||
|
||||
class ToolTimeout(TimeoutError):
|
||||
"""引擎等到时限就放弃了。消息直接给模型和人看:等了多久、为什么放弃、怎么办。"""
|
||||
|
||||
def __init__(self, name: str, limit: Limit) -> None:
|
||||
self.name = name
|
||||
self.limit = limit
|
||||
seconds = _seconds(limit.seconds)
|
||||
if limit.kind == "query":
|
||||
text = (f"查询超过 {seconds}s 没有返回,已放弃等待(数据库那边可能还在跑,连接会在后台"
|
||||
"收回)。加上 WHERE 条件或 LIMIT 缩小范围再查")
|
||||
else:
|
||||
text = f"工具 {name} 超过 {seconds}s 没有返回,已放弃等待"
|
||||
super().__init__(text)
|
||||
|
||||
|
||||
async def run_bounded(call: Awaitable[Any], limit: Limit | None, name: str) -> Any:
|
||||
"""跑一次工具调用;到了时限(加一点宽限)就收回控制权,不等它收尾。
|
||||
|
||||
被放弃的那次调用照样被取消,只是它的收尾(关连接、回滚)挪到后台去做完。
|
||||
"""
|
||||
if limit is None or not limit.enforce:
|
||||
return await call
|
||||
job = asyncio.ensure_future(call)
|
||||
try:
|
||||
done, _ = await asyncio.wait({job}, timeout=limit.seconds + GRACE_S)
|
||||
except asyncio.CancelledError:
|
||||
# 整次运行被取消(用户停止、服务关停):底下那次调用也不该接着跑
|
||||
_abandon(job)
|
||||
raise
|
||||
if job in done:
|
||||
return job.result()
|
||||
_abandon(job, cancel=not limit.self_timed)
|
||||
raise ToolTimeout(name, limit)
|
||||
|
||||
|
||||
def _abandon(job: asyncio.Future[Any], *, cancel: bool = True) -> None:
|
||||
if cancel:
|
||||
job.cancel()
|
||||
# 结果没人要了;把异常取走,免得事件循环报 "exception was never retrieved"
|
||||
job.add_done_callback(lambda f: f.cancelled() or f.exception())
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 模型把工具调用写成了文字
|
||||
#
|
||||
# 有的模型(或它前面那层网关)不认工具调用接口、或者节点根本没绑工具,模型就把自己
|
||||
# 训练时那套调用格式当正文吐出来。这一步没有任何真实调用,数据一次都没查到,而文字
|
||||
# 看上去像是「在查」。认出来之后先纠正一次,仍然如此就判失败。
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_MARKUP = re.compile(
|
||||
r"<[||]{1,2}\s*DSML\s*[||]{1,2}" # DeepSeek 的 DSML
|
||||
r"|<[||]\s*tool[▁_ ]calls?[▁_ ]begin\s*[||]>" # DeepSeek 的特殊 token
|
||||
r"|<\s*(?:tool_call|function_call)\s*>"
|
||||
r"|<\s*invoke\s+name\s*=",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# 只有一段 {"tool": …, "sql": …} 不算:正文里引用一段 JSON 很正常。
|
||||
# 得同时自称是「假设」调的,才是在编
|
||||
_TOOL_JSON = re.compile(r'\{\s*"tool"\s*:')
|
||||
_SQL_KEY = re.compile(r'"sql"\s*:')
|
||||
_PRETEND = re.compile(r"假设(?:调用|使用|执行)了?(?:工具|查询)|假装调用|模拟调用(?:了)?工具")
|
||||
|
||||
TOOL_MARKUP_ERROR = (
|
||||
"模型输出了工具调用的原始标记,但没有真正调用工具,这一步一次都没查到数据。"
|
||||
"常见原因:节点没有绑定工具,或者模型、服务不支持工具调用。"
|
||||
"到画布里给这个节点绑定要用的工具;绑定了还这样,就换一个支持工具调用的模型"
|
||||
)
|
||||
|
||||
TOOL_MARKUP_NUDGE = (
|
||||
"你上一条回复把工具调用写成了文字,系统没有执行它,也就没有拿到任何数据。"
|
||||
"要用工具,请通过工具调用接口发起,不要把调用格式写进正文;手上没有能用的工具,"
|
||||
"就直接说明查不到、缺什么,不要假设调用的结果。"
|
||||
)
|
||||
|
||||
|
||||
def leaked_markup(text: str | None) -> str | None:
|
||||
"""正文里露出来的工具调用标记(截一小段,给警告用)。没有就是 None。"""
|
||||
if not text:
|
||||
return None
|
||||
if m := _MARKUP.search(text):
|
||||
return m.group(0)
|
||||
if _TOOL_JSON.search(text) and _SQL_KEY.search(text) and (m := _PRETEND.search(text)):
|
||||
return m.group(0)
|
||||
return None
|
||||
|
||||
|
||||
def markup_warning(snippet: str, who: str = "模型") -> str:
|
||||
return f"{who}把工具调用写成了文字({snippet[:40]}…),没有真正调用工具"
|
||||
@@ -68,6 +68,8 @@ class VarIssue(BaseModel):
|
||||
message: str
|
||||
node_id: str | None = None
|
||||
path: str = ""
|
||||
#: 引用写在节点配置的哪个字段里(prompt、cases[0].condition)。产出侧的问题为空
|
||||
field: str = ""
|
||||
|
||||
|
||||
class VariableReport(BaseModel):
|
||||
@@ -350,7 +352,7 @@ def analyze(spec: GraphSpec) -> VariableReport:
|
||||
if target.kind == "loop" and target.produced_by:
|
||||
if node.id not in bodies.get(target.produced_by, set()):
|
||||
report.issues.append(VarIssue(
|
||||
level="warning", node_id=node.id, path=path,
|
||||
level="warning", node_id=node.id, path=path, field=field,
|
||||
message=f"{{{{ {path} }}}} 是「{target.produced_by_label}」"
|
||||
f"每轮的循环变量,只在循环体内部有值;"
|
||||
f"这一步不在循环体里,取到的会是空值",
|
||||
@@ -364,7 +366,7 @@ def analyze(spec: GraphSpec) -> VariableReport:
|
||||
and target.order > order
|
||||
):
|
||||
report.issues.append(VarIssue(
|
||||
level="warning", node_id=node.id, path=path,
|
||||
level="warning", node_id=node.id, path=path, field=field,
|
||||
message=f"{{{{ {path} }}}} 由「{target.produced_by_label}」产出,"
|
||||
f"但那一步在这之后才跑,这里取到的会是空值",
|
||||
))
|
||||
@@ -383,7 +385,7 @@ def analyze(spec: GraphSpec) -> VariableReport:
|
||||
hint = _did_you_mean(path, index)
|
||||
report.issues.append(VarIssue(
|
||||
level="error" if known_root else "warning",
|
||||
node_id=node.id, path=path,
|
||||
node_id=node.id, path=path, field=field,
|
||||
message=(
|
||||
f"{{{{ {path} }}}} 没有任何节点产出,"
|
||||
f"是不是想写 {{{{ {hint} }}}}?取不到值会渲染成空字符串,不报错"
|
||||
|
||||
Reference in New Issue
Block a user