mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-17 19:11:57 +00:00
e4f2693918
「引用即渲染」:写报告的模型只写引用标记([[m:指标id]]、[[i:输入字段]]、[[see:…]]),数值由系统按口径卡
填进去,每个数字都挂着一条能复算的证据链。本期是数字层闭环;实体、结论句的概率性证据放在后续几期。
内核(engine/evidence.py,口径卡、出具契约、表达式等)
- 口径卡记录每个指标的来源:原式、代入式(每个输入写成「值 ← 路径」)、复算结果、口径与版本
- 出具契约的数值匹配改为按位置标注;同一个值有几个出处时记为「出处不唯一」并列出候选,不再随便挑一个
- 证据 id 由内容派生,事后对不上就是被改过;零值、结构性数字(列表序号、代码块标签)单独处理
- 口径卡新增 on_missing:缺输入时默认仍是整个节点失败,可以改成记为空值、交给契约判档
报告撰写节点(report)与引用模式的出具契约
- 流式生成时 token 里就是真实数字,不会漏出原始标记;裸数字、不存在的引用当场判违规,交回去重写
(max_repairs,默认 1 次);仍不过时按 on_violation 失败(正式运行默认)或把违规标在报告里(探索运行默认)
- report.checked 事件记下核对结果,落在封存范围内;fail 模式下仍不过时带 failed,运行记录里画成失败
- 出具契约写了 report_from 就按引用核对:取回文档时复验哈希,独立重算一遍,全部带引用才判完整出具
- 成果字段逐字等于报告正文时标注 _evidence;复核只能加说明,不能改写带证据的答案(前后端各拦一道)
证据接口
- GET /api/runs/{id}/evidence 返回证据图;GET …/evidence/segments/{id} 返回一个片段的证据链
- 只认封存范围内的事件能追到的工件,不读 artifacts 表;封存被改过时不把任何一项标成已封存
- 没有报告的旧运行降级为 none 或 legacy_contract
界面
- EvidenceDoc 按块、句、片段渲染报告,片段是和正文一样的按钮;整份报告只占一个 Tab 位,
←/→ 在片段间移动、↑/↓ 按句、n/N 跳到下一处「无证据」、Enter 打开面板、Esc 关闭并把焦点还回去
- EvidencePanel:宽屏侧边、窄屏底部抽屉、360px 画布右栏里栏内展开;显示指标步骤、代入式、复算结果、
封存状态。正文不是封存的那份报告时明确说出来,不拿别的报告的封存画绿
- 出具横幅多一行「N/N 数字有出处 · 无证据 M」和「定位下一处」;没有 _evidence 的旧回答渲染一字不差
- 画布认得报告撰写节点;Copilot 手册补上口径卡、报告节点、出具契约的写法;新增模板「⑨ 可追溯周报」
验证(沙箱):tsc 干净,生产构建通过,pytest 1601 passed,check-all 16 项检查全绿(新增 check-evidence)。
484 lines
20 KiB
Python
484 lines
20 KiB
Python
from __future__ import annotations
|
||
|
||
import ast
|
||
import json
|
||
import operator
|
||
import re
|
||
from typing import Any
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 变量插值: {{ input.query }} / {{ nodes.n1.text }} / {{ vars.items | json }}
|
||
# --------------------------------------------------------------------------
|
||
|
||
_TEMPLATE_RE = re.compile(r"\{\{(.*?)\}\}", re.DOTALL)
|
||
|
||
|
||
def resolve_path(ctx: dict[str, Any], path: str) -> Any:
|
||
"""按点号路径取值,支持 a.b[0].c。取不到返回 None 而不是抛错 —— 编排里
|
||
半成品状态很常见,让它渲染成空字符串比中断整个 run 有用。"""
|
||
cur: Any = ctx
|
||
for raw in path.split("."):
|
||
raw = raw.strip()
|
||
if not raw:
|
||
continue
|
||
# 拆出 name[0][1] 形式的下标
|
||
m = re.match(r"^([^\[\]]*)((?:\[[^\[\]]+\])*)$", raw)
|
||
if not m:
|
||
return None
|
||
name, idx_part = m.group(1), m.group(2)
|
||
if name:
|
||
if isinstance(cur, dict):
|
||
cur = cur.get(name)
|
||
else:
|
||
cur = getattr(cur, name, None)
|
||
if cur is None:
|
||
return None
|
||
for idx in re.findall(r"\[([^\[\]]+)\]", idx_part):
|
||
idx = idx.strip().strip("'\"")
|
||
try:
|
||
if isinstance(cur, (list, tuple, str)):
|
||
cur = cur[int(idx)]
|
||
elif isinstance(cur, dict):
|
||
cur = cur.get(idx)
|
||
else:
|
||
return None
|
||
except (ValueError, IndexError, KeyError, TypeError):
|
||
return None
|
||
return cur
|
||
|
||
|
||
_FILTERS = {
|
||
"json": lambda v: json.dumps(v, ensure_ascii=False, indent=2, default=str),
|
||
"compact": lambda v: json.dumps(v, ensure_ascii=False, separators=(",", ":"), default=str),
|
||
"upper": lambda v: str(v).upper(),
|
||
"lower": lambda v: str(v).lower(),
|
||
"trim": lambda v: str(v).strip(),
|
||
"length": lambda v: len(v) if hasattr(v, "__len__") else 0,
|
||
"first": lambda v: v[0] if isinstance(v, (list, tuple)) and v else None,
|
||
"last": lambda v: v[-1] if isinstance(v, (list, tuple)) and v else None,
|
||
}
|
||
|
||
|
||
def _stringify(value: Any) -> str:
|
||
if value is None:
|
||
return ""
|
||
if isinstance(value, str):
|
||
return value
|
||
if isinstance(value, (dict, list, tuple)):
|
||
return json.dumps(value, ensure_ascii=False, default=str)
|
||
return str(value)
|
||
|
||
|
||
def render_template(text: str, ctx: dict[str, Any]) -> str:
|
||
"""把字符串里的 {{ ... }} 全部替换掉。支持 `路径 | 过滤器` 语法。"""
|
||
if not text or "{{" not in text:
|
||
return text or ""
|
||
|
||
def _sub(match: re.Match[str]) -> str:
|
||
expr = match.group(1).strip()
|
||
if not expr:
|
||
return ""
|
||
parts = [p.strip() for p in expr.split("|")]
|
||
value = resolve_path(ctx, parts[0])
|
||
for filt in parts[1:]:
|
||
fn = _FILTERS.get(filt)
|
||
if fn:
|
||
try:
|
||
value = fn(value)
|
||
except Exception: # noqa: BLE001 - 过滤器不该让 run 挂掉
|
||
value = None
|
||
return _stringify(value)
|
||
|
||
return _TEMPLATE_RE.sub(_sub, text)
|
||
|
||
|
||
def render_deep(value: Any, ctx: dict[str, Any]) -> Any:
|
||
"""递归渲染嵌套结构里的所有模板字符串。"""
|
||
if isinstance(value, str):
|
||
return render_template(value, ctx)
|
||
if isinstance(value, dict):
|
||
return {k: render_deep(v, ctx) for k, v in value.items()}
|
||
if isinstance(value, list):
|
||
return [render_deep(v, ctx) for v in value]
|
||
return value
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 安全表达式求值(分支条件用)
|
||
# --------------------------------------------------------------------------
|
||
|
||
# 幂运算的上界。`9**9**9**9` 只有 11 个 AST 节点,轻松过掉节点数护栏,
|
||
# 却会让 CPython 无限期地算一个天文数字的大整数 —— 而求值是在事件循环里
|
||
# 同步执行的(分支条件、transform、口径卡、每个节点的 skip_if 都走这里),
|
||
# 既没有线程池隔离也没有超时,asyncio 的 cancel 打断不了同步 CPU。
|
||
# 一条画布上的分支条件就能把整个后端冻死。
|
||
_MAX_POW_EXPONENT = 1024
|
||
_MAX_POW_BASE = 1e15
|
||
|
||
|
||
def _safe_pow(base: Any, exponent: Any) -> Any:
|
||
"""带上界的幂运算:超界直接报错,而不是让进程算到天荒地老。"""
|
||
try:
|
||
if abs(exponent) > _MAX_POW_EXPONENT:
|
||
raise ExpressionError(f"指数超过上限 {_MAX_POW_EXPONENT}")
|
||
if abs(base) > _MAX_POW_BASE and exponent > 1:
|
||
raise ExpressionError(f"底数超过上限 {_MAX_POW_BASE:g}")
|
||
except TypeError as e: # 非数值类型交给 operator.pow 自己报
|
||
raise ExpressionError(f"幂运算的操作数必须是数值:{e}") from e
|
||
return operator.pow(base, exponent)
|
||
|
||
|
||
_BIN_OPS = {
|
||
ast.Add: operator.add,
|
||
ast.Sub: operator.sub,
|
||
ast.Mult: operator.mul,
|
||
ast.Div: operator.truediv,
|
||
ast.FloorDiv: operator.floordiv,
|
||
ast.Mod: operator.mod,
|
||
ast.Pow: _safe_pow,
|
||
}
|
||
_CMP_OPS = {
|
||
ast.Eq: operator.eq,
|
||
ast.NotEq: operator.ne,
|
||
ast.Lt: operator.lt,
|
||
ast.LtE: operator.le,
|
||
ast.Gt: operator.gt,
|
||
ast.GtE: operator.ge,
|
||
ast.In: lambda a, b: a in b,
|
||
ast.NotIn: lambda a, b: a not in b,
|
||
ast.Is: operator.is_,
|
||
ast.IsNot: operator.is_not,
|
||
}
|
||
_UNARY_OPS = {ast.Not: operator.not_, ast.USub: operator.neg, ast.UAdd: operator.pos}
|
||
|
||
_SAFE_FUNCS: dict[str, Any] = {
|
||
"len": len,
|
||
"str": str,
|
||
"int": int,
|
||
"float": float,
|
||
"bool": bool,
|
||
"abs": abs,
|
||
"min": min,
|
||
"max": max,
|
||
"sum": sum,
|
||
"round": round,
|
||
"sorted": sorted,
|
||
"any": any,
|
||
"all": all,
|
||
"lower": lambda s: str(s).lower(),
|
||
"upper": lambda s: str(s).upper(),
|
||
"contains": lambda hay, needle: needle in hay if hay is not None else False,
|
||
"startswith": lambda s, p: str(s).startswith(p),
|
||
"endswith": lambda s, p: str(s).endswith(p),
|
||
"matches": lambda s, p: bool(re.search(p, str(s))),
|
||
"get": lambda obj, key, default=None: (obj or {}).get(key, default),
|
||
}
|
||
|
||
_MAX_NODES = 200
|
||
|
||
#: 表达式能引用的根名字,就是 state.template_context 的那几个键(有测试钉住两边一致)。
|
||
#: 不在这里、也不是白名单函数或 true/false/null 的名字,运行时一律取到 None——
|
||
#: `gate == "ok"` 这种漏写了 vars. 的条件永远不成立,而且不报错
|
||
EXPRESSION_ROOTS = frozenset(
|
||
{"input", "nodes", "vars", "output", "loops", "usage", "messages", "last_message"}
|
||
)
|
||
_LITERAL_NAMES = frozenset({"true", "True", "false", "False", "null", "None"})
|
||
|
||
_ALLOWED_NODES: tuple[type[ast.AST], ...] = (
|
||
ast.Expression, ast.Constant, ast.Name, ast.Load, ast.Attribute, ast.Subscript,
|
||
ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.And, ast.Or, ast.Compare, ast.IfExp,
|
||
ast.Call, ast.keyword, ast.List, ast.Tuple, ast.Dict,
|
||
*_BIN_OPS, *_UNARY_OPS, *_CMP_OPS,
|
||
)
|
||
_NODE_NAMES = {
|
||
"ListComp": "列表推导式", "SetComp": "集合推导式", "DictComp": "字典推导式",
|
||
"GeneratorExp": "生成器表达式", "Lambda": "lambda", "JoinedStr": "f-string",
|
||
"NamedExpr": ":=", "Slice": "切片 a[i:j]", "Starred": "* 展开", "Await": "await",
|
||
}
|
||
|
||
|
||
class ExpressionError(ValueError):
|
||
pass
|
||
|
||
|
||
class _Unbrace(ast.NodeTransformer):
|
||
"""`{{ vars.x }}` 在 Python 里是"装着一个集合的集合"。表达式不允许集合,所以
|
||
它在表达式里只可能是一种笔误:把模板写法带了进来——模型和人都这么写(开发库
|
||
里四次运行就死在"表达式里不允许出现 Set")。意思毫无歧义,按 vars.x 理解。
|
||
|
||
在语法树上剥,不在文本上剥:字符串字面量里的花括号原样保留。
|
||
"""
|
||
|
||
def __init__(self) -> None:
|
||
self.found: list[str] = []
|
||
|
||
def visit_Set(self, node: ast.Set) -> ast.AST:
|
||
self.generic_visit(node)
|
||
inner = node.elts[0] if len(node.elts) == 1 else None
|
||
if isinstance(inner, ast.Set) and len(inner.elts) == 1:
|
||
self.found.append(ast.unparse(inner.elts[0]))
|
||
return inner.elts[0]
|
||
return node
|
||
|
||
|
||
def _check_static(tree: ast.Expression) -> list[str]:
|
||
"""不求值,只看结构:违规直接抛 ExpressionError,返回不认识的名字(留给提示用)。
|
||
|
||
运行时求值会短路(and/or、三元只走一边),没走到的那一半写错了也发现不了;
|
||
画布校验和 Copilot 自查要的是"整条表达式都能跑",所以得把整棵树走一遍。
|
||
"""
|
||
unknown: list[str] = []
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, ast.BinOp) and type(node.op) not in _BIN_OPS:
|
||
if isinstance(node.op, ast.BitOr):
|
||
raise ExpressionError(
|
||
"表达式里没有 | 过滤器(那是模板的写法):取长度写 len(x),大小写写 upper(x) / lower(x)"
|
||
)
|
||
raise ExpressionError(f"不支持的运算符 {type(node.op).__name__}")
|
||
if not isinstance(node, _ALLOWED_NODES):
|
||
if isinstance(node, ast.Set):
|
||
raise ExpressionError("表达式里不支持集合 {…}:要判断是不是其中之一,用列表 x in ['a', 'b']")
|
||
name = type(node).__name__
|
||
raise ExpressionError(f"表达式里不允许出现 {_NODE_NAMES.get(name, name)}")
|
||
if isinstance(node, ast.Call):
|
||
if not isinstance(node.func, ast.Name) or node.func.id not in _SAFE_FUNCS:
|
||
called = node.func.id if isinstance(node.func, ast.Name) else ast.unparse(node.func)
|
||
raise ExpressionError(f"不认识的函数 {called}(),能用的只有:{'、'.join(_SAFE_FUNCS)}")
|
||
elif isinstance(node, ast.Attribute) and node.attr.startswith("_"):
|
||
raise ExpressionError("不允许访问私有属性")
|
||
elif (isinstance(node, ast.Constant) and isinstance(node.value, str)
|
||
and _TEMPLATE_RE.search(node.value)):
|
||
raise ExpressionError(
|
||
f"字符串 {node.value!r} 里的 {{{{ }}}} 不会被渲染——表达式不过模板,直接写路径,比如 vars.x"
|
||
)
|
||
elif (isinstance(node, ast.Name) and node.id not in EXPRESSION_ROOTS
|
||
and node.id not in _SAFE_FUNCS and node.id not in _LITERAL_NAMES):
|
||
unknown.append(node.id)
|
||
return list(dict.fromkeys(unknown))
|
||
|
||
|
||
def parse_expression(expr: str) -> tuple[ast.Expression, list[str], list[str]]:
|
||
"""解析 + 静态检查:(语法树, 被剥掉的 {{ }}, 不认识的名字)。结构违规抛 ExpressionError。
|
||
|
||
运行时求值、画布校验、Copilot 自查都走这一个入口——三处各写一套规则的话,
|
||
迟早出现"校验说能跑、跑起来报错"。
|
||
"""
|
||
text = (expr or "").strip()
|
||
try:
|
||
tree = ast.parse(text, mode="eval")
|
||
except SyntaxError as e:
|
||
hint = "(判断相等要写 ==)" if re.search(r"(?<![=!<>])=(?!=)", text) else ""
|
||
raise ExpressionError(f"表达式语法错误:{e.msg}{hint}") from e
|
||
unbrace = _Unbrace()
|
||
tree = ast.fix_missing_locations(unbrace.visit(tree))
|
||
if sum(1 for _ in ast.walk(tree)) > _MAX_NODES:
|
||
raise ExpressionError("表达式太复杂")
|
||
unknown = _check_static(tree)
|
||
return tree, unbrace.found, unknown
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 引用与代入:口径卡要说清「这个数是拿哪几个输入算出来的」
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def _chain_root(node: ast.AST) -> str | None:
|
||
"""node 是不是一条从根名字出发的取值链(vars.kpi.gmv、nodes.q.rows[0])。是就返回根。"""
|
||
cur = node
|
||
while isinstance(cur, (ast.Attribute, ast.Subscript)):
|
||
cur = cur.value
|
||
if isinstance(cur, ast.Name) and cur.id in EXPRESSION_ROOTS:
|
||
return cur.id
|
||
return None
|
||
|
||
|
||
def _walk_refs(node: ast.AST, found: list[ast.AST]) -> None:
|
||
if isinstance(node, (ast.Attribute, ast.Subscript, ast.Name)) and _chain_root(node):
|
||
found.append(node)
|
||
# 链本身不再往里拆(vars.kpi 是 vars.kpi.gmv 的一部分),但下标里的表达式是
|
||
# 独立的输入:vars.rows[vars.i] 取哪一格由 vars.i 决定
|
||
cur = node
|
||
while isinstance(cur, (ast.Attribute, ast.Subscript)):
|
||
if isinstance(cur, ast.Subscript):
|
||
_walk_refs(cur.slice, found)
|
||
cur = cur.value
|
||
return
|
||
for child in ast.iter_child_nodes(node):
|
||
_walk_refs(child, found)
|
||
|
||
|
||
def leaf_refs(tree: ast.AST) -> list[str]:
|
||
"""表达式引用了哪些值:每条从根名字出发的最长取值链,按出现顺序去重。
|
||
|
||
parse_expression 只告诉你「有没有不认识的名字」;口径卡要记来源,得知道
|
||
round((vars.kpi.gmv - vars.kpi.gmv_prev) / …) 里用到的是 vars.kpi.gmv 和
|
||
vars.kpi.gmv_prev 这两个值,而不是 vars、kpi 这些零件。
|
||
路径用 ast.unparse 的写法,substitute 按同样的写法认。
|
||
"""
|
||
found: list[ast.AST] = []
|
||
_walk_refs(tree, found)
|
||
return list(dict.fromkeys(ast.unparse(n) for n in found))
|
||
|
||
|
||
_SCALARS = (int, float, str, bool, type(None))
|
||
#: 字符串长过这个数就不代进去:上游模型写的一大段文本抄进代入式(和 metric_set 工件),
|
||
#: 没人看得懂,只是把工件撑大
|
||
_INLINE_STR_MAX = 80
|
||
|
||
|
||
def _inlinable(value: Any) -> bool:
|
||
"""这个值能不能以字面量的样子写进代入式。
|
||
|
||
容器不行;含 {{ 或 }} 的字符串不行——parse_expression 会把整条代入式当成
|
||
「表达式里写了模板」拒掉,复算就成了假的「对不上」;太长的字符串也不代。
|
||
"""
|
||
if not isinstance(value, _SCALARS):
|
||
return False
|
||
if isinstance(value, str):
|
||
return len(value) <= _INLINE_STR_MAX and "{{" not in value and "}}" not in value
|
||
return True
|
||
|
||
|
||
def _literal(value: Any) -> ast.expr:
|
||
"""负数写成一元负号:Constant(-3) 放在幂运算左边会被 unparse 成 -3 ** 2,
|
||
读起来和算起来都是 -(3 ** 2)。一元负号节点 unparse 时会自己加括号。"""
|
||
if isinstance(value, (int, float)) and not isinstance(value, bool) and value < 0:
|
||
return ast.UnaryOp(op=ast.USub(), operand=ast.Constant(-value))
|
||
return ast.Constant(value)
|
||
|
||
|
||
class _Substitute(ast.NodeTransformer):
|
||
def __init__(self, values: dict[str, Any]) -> None:
|
||
self.values = values
|
||
|
||
def _replace(self, node: ast.AST) -> ast.AST:
|
||
if _chain_root(node):
|
||
path = ast.unparse(node)
|
||
if path in self.values and _inlinable(self.values[path]):
|
||
return ast.copy_location(_literal(self.values[path]), node)
|
||
if path in self.values:
|
||
return node # 容器、含 {{ }} 的或太长的字符串留原路径,复算时照样取得到
|
||
return self.generic_visit(node)
|
||
|
||
visit_Attribute = visit_Subscript = visit_Name = _replace
|
||
|
||
|
||
def substitute(tree: ast.AST, values: dict[str, Any]) -> str:
|
||
"""把引用换成它当时的值,得到代入式:round((45678.5 - 42010.0) / 42010.0 * 100, 1)。
|
||
|
||
只代标量(含 {{ }} 或长过 80 字的字符串除外)。代入式本身还是一条合法表达式——拿同一个上下文再求一遍,结果必须和
|
||
原式一样,这是口径卡复算(recompute_ok)的依据。不改动传进来的语法树。
|
||
"""
|
||
import copy
|
||
|
||
replaced = _Substitute(values).visit(copy.deepcopy(tree))
|
||
return ast.unparse(ast.fix_missing_locations(replaced))
|
||
|
||
|
||
def eval_expression(expr: str, ctx: dict[str, Any]) -> Any:
|
||
"""求值一个受限的 Python 表达式。
|
||
|
||
只放行字面量、比较、布尔/算术运算、下标、属性访问和一小撮白名单函数。
|
||
没有 import、没有属性魔法、没有函数定义,所以用户在画布上写条件是安全的。
|
||
"""
|
||
expr = (expr or "").strip()
|
||
if not expr:
|
||
return None
|
||
tree, _, _ = parse_expression(expr)
|
||
|
||
def _eval(node: ast.AST) -> Any:
|
||
if isinstance(node, ast.Expression):
|
||
return _eval(node.body)
|
||
if isinstance(node, ast.Constant):
|
||
return node.value
|
||
if isinstance(node, ast.Name):
|
||
if node.id in ctx:
|
||
return ctx[node.id]
|
||
if node.id in _SAFE_FUNCS:
|
||
return _SAFE_FUNCS[node.id]
|
||
if node.id in ("true", "True"):
|
||
return True
|
||
if node.id in ("false", "False"):
|
||
return False
|
||
if node.id in ("null", "None"):
|
||
return None
|
||
return None
|
||
if isinstance(node, ast.Attribute):
|
||
base = _eval(node.value)
|
||
if isinstance(base, dict):
|
||
return base.get(node.attr)
|
||
if node.attr.startswith("_"):
|
||
raise ExpressionError("不允许访问私有属性")
|
||
return getattr(base, node.attr, None)
|
||
if isinstance(node, ast.Subscript):
|
||
base = _eval(node.value)
|
||
key = _eval(node.slice)
|
||
try:
|
||
return base[key]
|
||
except (KeyError, IndexError, TypeError):
|
||
return None
|
||
if isinstance(node, ast.BinOp):
|
||
op = _BIN_OPS.get(type(node.op))
|
||
if not op:
|
||
raise ExpressionError("不支持的运算符")
|
||
return op(_eval(node.left), _eval(node.right))
|
||
if isinstance(node, ast.UnaryOp):
|
||
op = _UNARY_OPS.get(type(node.op))
|
||
if not op:
|
||
raise ExpressionError("不支持的一元运算符")
|
||
return op(_eval(node.operand))
|
||
if isinstance(node, ast.BoolOp):
|
||
# Python 的 and/or 返回的是操作数本身而不是布尔值,并且短路求值。
|
||
# `vars.x or '默认值'` 是模板里最常见的写法,返回 True 就全错了。
|
||
is_and = isinstance(node.op, ast.And)
|
||
result: Any = None
|
||
for i, operand in enumerate(node.values):
|
||
result = _eval(operand)
|
||
truthy = bool(result)
|
||
if i < len(node.values) - 1 and (truthy is not is_and):
|
||
return result # and 遇假、or 遇真:短路返回该操作数
|
||
return result
|
||
if isinstance(node, ast.Compare):
|
||
left = _eval(node.left)
|
||
for op_node, comparator in zip(node.ops, node.comparators):
|
||
op = _CMP_OPS.get(type(op_node))
|
||
if not op:
|
||
raise ExpressionError("不支持的比较运算符")
|
||
right = _eval(comparator)
|
||
try:
|
||
if not op(left, right):
|
||
return False
|
||
except TypeError:
|
||
return False
|
||
left = right
|
||
return True
|
||
if isinstance(node, ast.IfExp):
|
||
return _eval(node.body) if _eval(node.test) else _eval(node.orelse)
|
||
if isinstance(node, ast.Call):
|
||
if not isinstance(node.func, ast.Name) or node.func.id not in _SAFE_FUNCS:
|
||
raise ExpressionError("只能调用白名单函数")
|
||
args = [_eval(a) for a in node.args]
|
||
kwargs = {kw.arg: _eval(kw.value) for kw in node.keywords if kw.arg}
|
||
return _SAFE_FUNCS[node.func.id](*args, **kwargs)
|
||
if isinstance(node, (ast.List, ast.Tuple)):
|
||
return [_eval(e) for e in node.elts]
|
||
if isinstance(node, ast.Dict):
|
||
return {
|
||
_eval(k): _eval(v)
|
||
for k, v in zip(node.keys, node.values)
|
||
if k is not None
|
||
}
|
||
raise ExpressionError(f"表达式里不允许出现 {type(node).__name__}")
|
||
|
||
return _eval(tree)
|
||
|
||
|
||
def eval_condition(expr: str, ctx: dict[str, Any]) -> bool:
|
||
"""求值成布尔。条件写错时返回 False 而不是炸掉整个 run。"""
|
||
try:
|
||
return bool(eval_expression(expr, ctx))
|
||
except ExpressionError:
|
||
raise
|
||
except Exception: # noqa: BLE001
|
||
return False
|