【1. 类型校验恢复 + 转换 / 运算节点】
上一版我把类型"一律放开什么都能接",那是错的 —— 它把问题藏到运行时
(以"数字算出了 NaN"这种形式爆出来),更难查。现在恢复严格校验。
那"接不上怎么办"?用两个**显式**节点解决:
转换 cast:str / bool / num 互转
转文本 原样;
转真假 0 / 空 / false / no → 假,其他 → 真(**和 while 的判断同一套规则**,
用户不用记两遍);
转数字 能解析就取数,不能解析就 0(并报出来)。
运算 op:加 + / 减 − / 乘 × / 除 ÷ / 取余 % / 拼接 / 等于 / 不等于 / 大于 / 小于 /
取反(负号)/ 逻辑非
两个都是**纯节点**(蓝图里 + 号和类型转换就是纯节点):没有 exec 引脚,
值被需要的节点**拉取**时才递归现算 —— 所以可以层层嵌套(读变量 → 加 → 转文本 → 最终输出)。
除零、把文字当数字算:**不抛异常**,记下来继续跑,用户能从结果界面看到哪一步出的问题。
★ **图灵完备**:while(无界循环)+ 变量 + 运算 + 判断,这套组合等价于图灵机。
实测:n 从 5 递减到 0,每轮拼接一个字符,最后 acc = '*****',while 判断了 11 次。
【2. 画布不再封顶】
以前画布写死 900×800,**拖到头就拖不动了**,想在图右边再接一段只能先把节点挪开。
现在按"所有节点的包围盒 + 一圈余量(900dp)"算:节点拖到哪,画布就跟着长到哪,
永远还有地方继续接。拖节点也不再钳到固定边界。
【3. 拖动灵敏度可调】
节点移动量 = 屏幕位移 ÷ 缩放 × 系数。除缩放是必须的(不然放大后节点跑得比手指快);
剩下的手感(跟手还是稳一点)跟屏幕尺寸、手指习惯都有关,做成滑块(0.3× ~ 2×)。
放在编辑器标题栏的 ⋮ 里 —— 工具栏已经有变量/加节点/运行/结果,再塞滑块只会更挤。
【4. 会议可导出】
⋮ 菜单里「复制会议 JSON」:节点 / 连线 / 变量全在里面,缩进好的 JSON,
可以直接粘去备份、发给别人。
【踩的坑(记一下)】
用 PowerShell 按行号拼接改 Kotlin 文件,把几行挪进了别的函数作用域,
编译报了一堆"Unresolved reference"(PrimaryButton / LinkFrom)。
还原文件、改用 edit 工具逐处改才好。**大文件不要按行号拼**。
【验证】
- 引擎回归 40/40,Node 与 Python 16/16 逐用例一致
- 会议 HTTP 13/13 ×2、语音 41/41、Markdown 19/19
- 类型化实测:15/15 条边全保住(含 num→加→写变量→转文本→最终输出 的整条链)
1398 lines
63 KiB
Python
1398 lines
63 KiB
Python
"""会议模式:用「节点 + 连线」把多个智能体串成一条流水线。
|
||
|
||
和普通对话的区别:
|
||
普通对话是"一个智能体回答一个问题";
|
||
会议模式是一张有向图 —— 初始输入进去,经过若干智能体节点各自加工,
|
||
中间可以按条件分叉,最后汇到最终输出节点。
|
||
|
||
为什么放在内核而不是界面上:
|
||
执行要走模型、要调工具、要按智能体各自的模型和音色去请求 ——
|
||
这些能力都已经在内核里了。界面只负责画图和收事件。
|
||
|
||
和 Node 版 server/src/meeting.mjs 是镜像实现,字段和事件名必须逐字一致
|
||
(两边不一致的话,同一个会议在手机和电脑上跑出来不一样)。
|
||
|
||
--------------------------------------------------------------------------
|
||
节点类型
|
||
--------------------------------------------------------------------------
|
||
start 初始输入:整个图的入口。文本可以写死,也可以留空表示"用用户发的那句"。
|
||
agent 智能体:带一个 agentId,外加**本节点专属**的附加提示词和输出控制。
|
||
这是"每个智能体都是一个节点、都能控制输出内容"的落点。
|
||
judge 判断:按条件把流分到 true / false 两条出边。
|
||
end 最终输出:汇总上游内容作为结果。
|
||
|
||
--------------------------------------------------------------------------
|
||
关于判断节点的"规则"模式为什么不用 eval
|
||
--------------------------------------------------------------------------
|
||
判断节点要支持"上游输出里有没有某个词""长度是否超过 N"这类条件。
|
||
最省事的做法是让用户写一段 Python 表达式然后 eval —— **绝对不行**:
|
||
配置能被任意改写(界面上可编辑、文件可手改),eval 就等于把任意代码
|
||
执行权交出去。所以这里用**结构化规则**(kind + value),
|
||
能表达的就那几种,多一种就多一个分支,而不是多一分风险。
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import threading
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
|
||
import paths
|
||
|
||
_lock = threading.Lock()
|
||
|
||
NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'value',
|
||
'cast', 'op')
|
||
|
||
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
|
||
# --------------------------------------------------------------------------- #
|
||
# 转换 / 运算
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 类型校验是认真的(连错类型接不上),所以必须有**显式**的办法把类型变过来、
|
||
# 把值算出来。就这两个节点:
|
||
#
|
||
# 转换 cast:把 str / bool / num 互相转
|
||
# 运算 op :+ - × ÷ % 拼接 取反 逻辑非 比较
|
||
#
|
||
# 为什么不干脆让引擎偷偷转:转换是有代价、有语义的 ——
|
||
# "12abc" 转数字该是多少?空串转 bool 是真还是假?这些必须由用户明确决定,
|
||
# 藏在引擎里就成了"跑起来才发现数字是 NaN",更难查。
|
||
|
||
CAST_KINDS = (
|
||
('str', '转成文本'),
|
||
('bool', '转成真假'),
|
||
('num', '转成数字'),
|
||
)
|
||
|
||
# (键, 名字, 输入类型, 输出类型, 要几个输入)
|
||
OPS = (
|
||
('add', '加 +', 'num', 'num', 2),
|
||
('sub', '减 −', 'num', 'num', 2),
|
||
('mul', '乘 ×', 'num', 'num', 2),
|
||
('div', '除 ÷', 'num', 'num', 2),
|
||
('mod', '取余 %', 'num', 'num', 2),
|
||
('concat', '拼接', 'str', 'str', 2),
|
||
('eq', '等于 =', 'str', 'bool', 2),
|
||
('ne', '不等于 ≠', 'str', 'bool', 2),
|
||
('gt', '大于 >', 'num', 'bool', 2),
|
||
('lt', '小于 <', 'num', 'bool', 2),
|
||
('neg', '取反(负号)', 'num', 'num', 1),
|
||
('not', '逻辑非 !', 'bool', 'bool', 1),
|
||
)
|
||
|
||
_OPS_BY_KEY = {o[0]: o for o in OPS}
|
||
|
||
|
||
def _cast_to(node: dict) -> str:
|
||
raw = str(node.get('castTo') or 'str')
|
||
return raw if raw in PIN_TYPES else 'str'
|
||
|
||
|
||
def cast_value(value, target: str) -> str:
|
||
"""
|
||
把值转成目标类型(返回的仍是文本,但**语义**上已经是那个类型)。
|
||
|
||
转换规则(和 while 的真假判断保持一致,用户不用记两套):
|
||
→ str :原样文本
|
||
→ bool:0 / 空 / false / no / off → 'false',其他 → 'true'
|
||
→ num :能解析就取数(去掉多余小数位),不能解析就 0
|
||
"""
|
||
if target == 'bool':
|
||
return 'true' if truthy(value) else 'false'
|
||
if target == 'num':
|
||
try:
|
||
num = float(str(value).strip())
|
||
except (TypeError, ValueError):
|
||
return '0'
|
||
return str(int(num)) if num == int(num) else str(num)
|
||
return str(value)
|
||
|
||
|
||
def apply_op(op_key: str, a, b=None):
|
||
"""
|
||
算一个运算。返回 (结果文本, 出错说明)。
|
||
|
||
**出错不抛异常**:除零、把文字当数字算,都不该让整场会议停摆 ——
|
||
记下来继续跑,用户能从结果界面看到哪一步出了问题。
|
||
"""
|
||
spec = _OPS_BY_KEY.get(op_key)
|
||
if not spec:
|
||
return '', f'不认识的运算:{op_key}'
|
||
_, _, _, out_type, arity = spec
|
||
|
||
def as_num(v):
|
||
try:
|
||
return float(str(v).strip()), None
|
||
except (TypeError, ValueError):
|
||
return 0.0, f'「{str(v)[:20]}」不是数字'
|
||
|
||
if arity == 1:
|
||
if op_key == 'neg':
|
||
n, err = as_num(a)
|
||
if err:
|
||
return '0', err
|
||
return cast_value(-n, 'num'), ''
|
||
if op_key == 'not':
|
||
return ('false' if truthy(a) else 'true'), ''
|
||
return '', f'不认识的运算:{op_key}'
|
||
|
||
if op_key == 'concat':
|
||
return str(a) + str(b), ''
|
||
if op_key in ('eq', 'ne'):
|
||
same = str(a) == str(b)
|
||
return cast_value(same if op_key == 'eq' else not same, 'bool'), ''
|
||
|
||
x, e1 = as_num(a)
|
||
y, e2 = as_num(b)
|
||
if e1 or e2:
|
||
return cast_value(0, out_type), (e1 or e2)
|
||
if op_key == 'add':
|
||
return cast_value(x + y, out_type), ''
|
||
if op_key == 'sub':
|
||
return cast_value(x - y, out_type), ''
|
||
if op_key == 'mul':
|
||
return cast_value(x * y, out_type), ''
|
||
if op_key == 'div':
|
||
if y == 0:
|
||
return cast_value(0, out_type), '除数是 0'
|
||
return cast_value(x / y, out_type), ''
|
||
if op_key == 'mod':
|
||
if y == 0:
|
||
return cast_value(0, out_type), '除数是 0'
|
||
return cast_value(x % y, out_type), ''
|
||
if op_key == 'gt':
|
||
return cast_value(x > y, out_type), ''
|
||
if op_key == 'lt':
|
||
return cast_value(x < y, out_type), ''
|
||
return '', f'不认识的运算:{op_key}'
|
||
|
||
|
||
JUDGE_KINDS = (
|
||
('contains', '包含关键词'),
|
||
('not_contains', '不包含关键词'),
|
||
('longer_than', '字数多于'),
|
||
('shorter_than', '字数少于'),
|
||
('empty', '为空'),
|
||
('not_empty', '不为空'),
|
||
('ai', '让模型判断'),
|
||
)
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# while 循环
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 和 C 的 while 一样:**先判断、再执行循环体**,条件为假就跳出。
|
||
# exec 入 ▶ 进入循环
|
||
# data 入 条件 bool,每轮重新求值(所以条件一般来自"读变量")
|
||
# exec 出 循环体 条件为真时走这条
|
||
# exec 出 结束 条件为假时走这条
|
||
# data 出 无
|
||
#
|
||
# 为什么不能靠"循环体连回 while"来实现:那样每轮都要用户多画一根回边,
|
||
# 而且"从上面进来"和"从循环体回来"分不开,很容易连成死循环。
|
||
# 这里由**引擎**负责"循环体跑完自动回来重新判断"(UE 蓝图的 While Loop
|
||
# 也是这么做的,body 出线是特殊的 deferred 引脚)。
|
||
|
||
# 单次运行里,一个 while 节点最多转多少轮。
|
||
# 不是"限制用户",是防止条件永远为真把额度和时间烧光 ——
|
||
# 正常写循环根本碰不到这个数。
|
||
MAX_LOOP_ITERS = 200
|
||
|
||
|
||
class _Aborted(Exception):
|
||
"""用户点了停止 / 客户端断开。用异常从嵌套的 walk 里一次性跳出来。"""
|
||
|
||
# 条件为真怎么判:接受 bool、'true'/'1'/'yes'/非空字符串
|
||
TRUE_WORDS = ('true', '1', 'yes', 'y', 'on', '是', '真')
|
||
|
||
|
||
def truthy(value) -> bool:
|
||
"""
|
||
按"真/假"解释一个值。**bool 转换的规则就在这里**:
|
||
|
||
数字 0 / 空串 / 'false' / 'no' / 'off' / 空数组对象 → False
|
||
其他任何非空的东西 → True
|
||
|
||
也就是用户要的:`var == 0` 是假、`var != 0` 是真。
|
||
while 的条件和判断节点都走这里,保证两边对同一个值判断一致。
|
||
"""
|
||
if isinstance(value, bool):
|
||
return value
|
||
if value is None:
|
||
return False
|
||
if isinstance(value, (int, float)):
|
||
return value != 0
|
||
text = str(value).strip().lower()
|
||
if not text:
|
||
return False
|
||
# 空数组/对象那种字符串也当假
|
||
if text in ('false', '0', 'no', 'n', 'off', '否', '假', 'none', 'null', '[]', '{}'):
|
||
return False
|
||
return True
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 变量
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 为什么需要:会议是"多轮、多节点"的,前面的结论要带到后面去。
|
||
# 只靠连线传的话,到分叉再汇合就乱了(一个节点只能拿到直接上游)。
|
||
# 变量是**全局的**,任何节点都能读,所以要"记住一件事供后面用"时用它。
|
||
#
|
||
# 用 [[SET 名字=值]] 这种显式标记让智能体写变量,而不是让它自由发挥:
|
||
# 自由发挥没法可靠解析,最后就是"有时能改有时改不了"这种最难查的问题。
|
||
|
||
# 整行匹配。^...$ 保证不会误伤正文里出现的方括号。
|
||
SET_RE = re.compile(r'^[ \t]*\[\[SET[ \t]+([^\]=\r\n]+?)[ \t]*=[ \t]*(.*?)\]\][ \t]*$', re.MULTILINE)
|
||
|
||
|
||
def apply_sets(text: str, variables: dict, allowed) -> tuple:
|
||
"""
|
||
从模型输出里抽出 [[SET 名字=值]],写进变量表,并把这些行从正文里去掉。
|
||
|
||
返回 (剥干净的正文, {改动的变量})。
|
||
|
||
allowed 是"这个节点有权限写哪些变量"。没授权的**原样留在正文里**,
|
||
而不是悄悄丢掉 —— 用户能看见"它想写但没权限",比默默失败好查得多。
|
||
"""
|
||
changed = {}
|
||
allow = set(allowed or [])
|
||
|
||
def repl(match):
|
||
name = match.group(1).strip()
|
||
value = match.group(2).strip()
|
||
if allow and name not in allow:
|
||
return match.group(0)
|
||
variables[name] = value
|
||
changed[name] = value
|
||
return ''
|
||
|
||
cleaned = SET_RE.sub(repl, text or '')
|
||
# 去掉被 SET 行留出来的多余空行
|
||
cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip()
|
||
return cleaned, changed
|
||
|
||
|
||
def variables_prompt(variables: dict, read_names, write_names) -> str:
|
||
"""
|
||
给智能体拼一段"你能看到哪些变量、能改哪些"的说明。
|
||
|
||
只读的不列写法说明,只写的不列当前值 —— 权限边界写清楚,
|
||
模型才不会去猜"我能不能改这个"。
|
||
"""
|
||
reads = [n for n in (read_names or []) if n]
|
||
writes = [n for n in (write_names or []) if n]
|
||
if not reads and not writes:
|
||
return ''
|
||
parts = []
|
||
if reads:
|
||
lines = [f'- {n} = {variables.get(n, "(还没设过)")}' for n in reads]
|
||
parts.append('【你可以看到的变量】\n' + '\n'.join(lines))
|
||
if writes:
|
||
parts.append(
|
||
'【你可以修改的变量】' + '、'.join(writes) + '\n'
|
||
'要修改变量时,在回答的**最后**单独起一行写:\n'
|
||
'[[SET 变量名=新值]]\n'
|
||
'这一行不会显示给用户,会被系统取走并写入变量。'
|
||
'不需要修改就不要写这一行。'
|
||
)
|
||
return '\n\n'.join(parts)
|
||
|
||
|
||
def _ts36() -> str:
|
||
num = int(datetime.now(timezone.utc).timestamp() * 1000)
|
||
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
|
||
out = ''
|
||
while num:
|
||
num, rem = divmod(num, 36)
|
||
out = digits[rem] + out
|
||
return out or '0'
|
||
|
||
|
||
def _rid(prefix: str) -> str:
|
||
return f'{prefix}_{_ts36()}_{uuid.uuid4().hex[:4]}'
|
||
|
||
|
||
def now_iso() -> str:
|
||
return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 默认会议:一个能直接跑的最小图(初始输入 → 智能体 → 最终输出)
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def new_meeting(name: str = '新会议') -> dict:
|
||
"""
|
||
给一张能直接跑的初始图,而不是空白画布。
|
||
|
||
空白画布对着干瞪眼是最差的新手体验;放一个"输入 → 一个智能体 → 输出"
|
||
的最小闭环,用户改改就能用,也能一眼看懂节点和连线是怎么连的。
|
||
|
||
★ 坐标要**一屏放得下**:x 按 120 递增、节点宽 116,所以 12→132→252,
|
||
最右边 252+116=368。手机竖屏大约 360dp 宽,会稍微超一点点,
|
||
但主体都在视野里;早先按 60/300/540 摆,默认图直接摊到两屏外,
|
||
用户一进来看到的是空画布加一个孤零零的节点,以为坏了。
|
||
"""
|
||
return {
|
||
'id': _rid('m'),
|
||
'name': name,
|
||
'nodes': [
|
||
{'id': 'n_start', 'type': 'start', 'x': 12, 'y': 120,
|
||
'title': '初始输入', 'text': ''},
|
||
{'id': 'n_agent1', 'type': 'agent', 'x': 132, 'y': 120,
|
||
'title': '智能体', 'agentId': '', 'extraPrompt': '', 'outputControl': ''},
|
||
{'id': 'n_end', 'type': 'end', 'x': 252, 'y': 120,
|
||
'title': '最终输出', 'text': ''},
|
||
],
|
||
'edges': [
|
||
{'from': 'n_start', 'to': 'n_agent1', 'branch': ''},
|
||
{'from': 'n_agent1', 'to': 'n_end', 'branch': ''},
|
||
],
|
||
'createdAt': now_iso(),
|
||
'updatedAt': now_iso(),
|
||
}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 存取
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _file() -> str:
|
||
return os.path.join(paths.get().data_dir, 'meetings.json')
|
||
|
||
|
||
def _read() -> list:
|
||
file_path = _file()
|
||
if not os.path.isfile(file_path):
|
||
return []
|
||
try:
|
||
with open(file_path, encoding='utf-8') as fh:
|
||
data = json.load(fh)
|
||
except (OSError, ValueError) as exc:
|
||
print(f'[meeting] meetings.json 读不了:{exc}', file=sys.stderr)
|
||
return []
|
||
items = data.get('meetings') if isinstance(data, dict) else None
|
||
return items if isinstance(items, list) else []
|
||
|
||
|
||
def _write(items: list) -> None:
|
||
os.makedirs(paths.get().data_dir, exist_ok=True)
|
||
with open(_file(), 'w', encoding='utf-8') as fh:
|
||
json.dump({'meetings': items}, fh, ensure_ascii=False, indent=2)
|
||
|
||
|
||
def list_meetings() -> list:
|
||
"""列表只给摘要:节点连线可能很大,列表页用不上"""
|
||
return [
|
||
{
|
||
'id': m.get('id'),
|
||
'name': m.get('name') or '未命名会议',
|
||
'nodeCount': len(m.get('nodes') or []),
|
||
'edgeCount': len(m.get('edges') or []),
|
||
'updatedAt': m.get('updatedAt'),
|
||
}
|
||
for m in _read()
|
||
]
|
||
|
||
|
||
def get_meeting(meeting_id: str):
|
||
return next((m for m in _read() if m.get('id') == meeting_id), None)
|
||
|
||
|
||
def create_meeting(payload: dict) -> dict:
|
||
payload = payload or {}
|
||
item = new_meeting(str(payload.get('name') or '新会议')[:40])
|
||
with _lock:
|
||
items = _read()
|
||
items.append(item)
|
||
_write(items)
|
||
return item
|
||
|
||
|
||
def save_meeting(meeting_id: str, payload: dict):
|
||
"""整份覆盖。图这种东西局部改很容易改出坏结构(悬空连线、重复 id)。"""
|
||
payload = payload or {}
|
||
with _lock:
|
||
items = _read()
|
||
for i, item in enumerate(items):
|
||
if item.get('id') != meeting_id:
|
||
continue
|
||
merged = {**item, **payload, 'id': meeting_id, 'updatedAt': now_iso()}
|
||
merged['nodes'] = _sanitize_nodes(merged.get('nodes') or [])
|
||
merged['vars'] = _sanitize_vars(merged.get('vars') or [])
|
||
_set_type_context(merged['nodes'], merged['vars'])
|
||
merged['edges'] = _sanitize_edges(merged.get('edges') or [], merged['nodes'])
|
||
items[i] = merged
|
||
_write(items)
|
||
return merged
|
||
return None
|
||
|
||
|
||
def delete_meeting(meeting_id: str) -> bool:
|
||
with _lock:
|
||
items = _read()
|
||
left = [m for m in items if m.get('id') != meeting_id]
|
||
if len(left) == len(items):
|
||
return False
|
||
_write(left)
|
||
# 会议删了,它的运行历史也一并清掉 —— 留着就是永远读不到的垃圾
|
||
runs = _read_runs()
|
||
runs.pop(meeting_id, None)
|
||
_write_runs(runs)
|
||
return True
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 运行历史
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
# 每场会议最多留多少条历史。会议可能是无限循环、一次跑几十轮,
|
||
# 不设上限的话这个文件会一直涨。
|
||
RUN_HISTORY_LIMIT = 20
|
||
|
||
|
||
def _runs_file() -> str:
|
||
return os.path.join(paths.get().data_dir, 'meeting-runs.json')
|
||
|
||
|
||
def _read_runs() -> dict:
|
||
file_path = _runs_file()
|
||
if not os.path.isfile(file_path):
|
||
return {}
|
||
try:
|
||
with open(file_path, encoding='utf-8') as fh:
|
||
data = json.load(fh)
|
||
except (OSError, ValueError) as exc:
|
||
print(f'[meeting] meeting-runs.json 读不了:{exc}', file=sys.stderr)
|
||
return {}
|
||
items = data.get('runs') if isinstance(data, dict) else None
|
||
return items if isinstance(items, dict) else {}
|
||
|
||
|
||
def _write_runs(runs: dict) -> None:
|
||
os.makedirs(paths.get().data_dir, exist_ok=True)
|
||
with open(_runs_file(), 'w', encoding='utf-8') as fh:
|
||
json.dump({'runs': runs}, fh, ensure_ascii=False, indent=2)
|
||
|
||
|
||
def list_runs(meeting_id: str) -> list:
|
||
"""某场会议的历史运行记录,**最新的在前**"""
|
||
return list(reversed(_read_runs().get(meeting_id) or []))
|
||
|
||
|
||
def append_run(meeting_id: str, record: dict) -> dict:
|
||
with _lock:
|
||
runs = _read_runs()
|
||
items = runs.get(meeting_id) or []
|
||
items.append(record)
|
||
# 只留最近 RUN_HISTORY_LIMIT 条
|
||
runs[meeting_id] = items[-RUN_HISTORY_LIMIT:]
|
||
_write_runs(runs)
|
||
return record
|
||
|
||
|
||
def clear_runs(meeting_id: str) -> bool:
|
||
with _lock:
|
||
runs = _read_runs()
|
||
if meeting_id not in runs:
|
||
return False
|
||
runs.pop(meeting_id, None)
|
||
_write_runs(runs)
|
||
return True
|
||
|
||
|
||
def _sanitize_nodes(nodes: list) -> list:
|
||
"""丢掉类型不认识、或者 id 重复的节点 —— 坏节点会让整张图跑不起来"""
|
||
out = []
|
||
seen = set()
|
||
for n in nodes:
|
||
if not isinstance(n, dict):
|
||
continue
|
||
nid = str(n.get('id') or '')
|
||
ntype = str(n.get('type') or '')
|
||
if not nid or nid in seen or ntype not in NODE_TYPES:
|
||
continue
|
||
seen.add(nid)
|
||
try:
|
||
max_runs = int(n.get('maxRuns')) if n.get('maxRuns') is not None else 1
|
||
except (TypeError, ValueError):
|
||
max_runs = 1
|
||
out.append({
|
||
**n,
|
||
'id': nid,
|
||
'type': ntype,
|
||
'x': float(n.get('x') or 0),
|
||
'y': float(n.get('y') or 0),
|
||
# 夹在 0~20:**0 = 无限循环**(两个智能体互相点评那种用法),
|
||
# 1~20 是有限次。负数或大于 20 的值都不认,退回 1 ——
|
||
# 不然用户手改文件写成 99999 会一直烧额度。
|
||
'maxRuns': 0 if max_runs <= 0 else min(max_runs, 20),
|
||
})
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 引脚类型表(引擎侧)
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 界面上的引脚定义要和这里一致,否则会出现"界面上能连、保存时被丢掉"
|
||
# 这种说不清的问题。两边都从同一个规则来:按节点类型查数据引脚的类型。
|
||
#
|
||
# 节点 数据入 数据出
|
||
# start —— str(用户发的那句 / 写死的文本)
|
||
# value —— 节点上选(str / bool / num)
|
||
# agent str str
|
||
# judge str bool(判断结果,可以直接喂给 while)
|
||
# var str ——(存进去的值不从它往下传)
|
||
# readvar —— str(变量的当前值)
|
||
# while bool ——
|
||
# end str ——
|
||
|
||
# ★ 值是**一个元组**:这个数据入口接受哪些类型。
|
||
#
|
||
# while 要同时收 bool 和 str:它的条件语义是"真/假",bool 最自然,
|
||
# 但**变量永远是字符串** —— 而循环条件几乎总是来自变量(不然没法每轮变化)。
|
||
# 只收 bool 的话 while 连不上任何动态条件,等于没法用
|
||
# (真踩过:界面上连了,保存时按类型不符被丢掉,图看着连上就是不跑)。
|
||
# 字符串按 truthy 解释:非空且不是 'false'/'0'/'no' 就算真。
|
||
# ★ **类型校验是认真的**:连错类型接不上。
|
||
#
|
||
# 那"接不上怎么办"?—— 用「转换」节点显式转一下,用「运算」节点算出想要的类型。
|
||
# 这比让引擎偷偷替你转要好:转换是有代价、有语义的("12abc" 转数字该是多少?),
|
||
# 显式摆一个节点出来,用户看得见、也能控制。
|
||
#
|
||
# 我一度把类型"一律放开什么都能接",那是错的:它把问题藏到运行时,
|
||
# 以"数字算出了 NaN"这种形式爆出来,更难查。
|
||
NODE_DATA_IN = {
|
||
'agent': ('str',),
|
||
'judge': ('str',),
|
||
# 写变量是汇:什么都能存(存进去的都是文本,读的时候按变量类型解释)
|
||
'var': ('str', 'bool', 'num'),
|
||
'while': ('bool',),
|
||
'end': ('str',),
|
||
# 转换:什么都收,出口由 castTo 决定
|
||
'cast': ('str', 'bool', 'num'),
|
||
# 运算:入口类型由运算本身决定(见 _data_in_type)
|
||
'op': ('str', 'bool', 'num'),
|
||
}
|
||
|
||
NODE_DATA_OUT = {
|
||
'start': 'str',
|
||
'agent': 'str',
|
||
'judge': 'bool',
|
||
'readvar': 'str',
|
||
}
|
||
|
||
# _sanitize_edges 只收 nodes 列表,而类型查询要按 id 查节点。
|
||
# 用一个模块级的临时表把它传进去 —— 比给一串辅助函数都加一个参数干净。
|
||
_LAST_BY_ID = {}
|
||
|
||
# 变量登记表:名字 -> 类型。
|
||
# ★ **类型是变量的属性,不是节点的属性** —— 写变量和读变量两处不会各写一个类型打架。
|
||
_LAST_VAR_TYPE = {}
|
||
# 纯节点求值时要能找到自己的数据入线,所以也把边表放一份在这儿
|
||
_LAST_EDGES = []
|
||
|
||
|
||
def _set_type_context(nodes: list, vars: list = None, edges: list = None) -> None:
|
||
"""
|
||
设好"当前这张图"的上下文。
|
||
|
||
★ 连 edges 也要设:**转换 / 运算也是纯节点**(蓝图里的 + 号和类型转换都是纯节点)——
|
||
它们的值不是"执行时产生的",而是被需要的节点**拉取**时才现算的,
|
||
现算就得能找到自己的数据入线。
|
||
"""
|
||
global _LAST_BY_ID, _LAST_VAR_TYPE, _LAST_EDGES
|
||
_LAST_BY_ID = {n['id']: n for n in nodes}
|
||
_LAST_VAR_TYPE = {v['name']: v['type'] for v in (vars or [])}
|
||
if edges is not None:
|
||
_LAST_EDGES = edges
|
||
def _data_in_type(node_id: str):
|
||
node = _LAST_BY_ID.get(node_id)
|
||
if not node:
|
||
return None
|
||
# 运算节点的两个入口,类型由算子决定(加法要数字、拼接要文本)
|
||
if node['type'] == 'op':
|
||
spec = _OPS_BY_KEY.get(str(node.get('op') or 'add'))
|
||
return (spec[2],) if spec else ('num',)
|
||
# ★ 写变量是**汇**:什么类型都能存。
|
||
#
|
||
# 这里原来按**变量登记表**卡类型(变量声明成 num 就只收 num)。
|
||
# 后果:智能体输出的是 str → 类型不符 → 引擎保存时把数据线丢掉。
|
||
# 界面上明明连上了,一保存就没了 —— 用户的原话是"是链接不了",
|
||
# 而且完全不知道为什么(界面上连的那一下是成功的)。
|
||
#
|
||
# 变量的类型只该决定**读出去**能接到哪(readvar 的出口类型),
|
||
# 不该限制**存进来**的东西:存进去的都是文本,读的时候再按类型解释。
|
||
return NODE_DATA_IN.get(node['type'])
|
||
def _data_out_type(node_id: str):
|
||
node = _LAST_BY_ID.get(node_id)
|
||
if not node:
|
||
return None
|
||
if node['type'] == 'value':
|
||
# 值节点的类型由它自己选(这个常量本身是什么类型)
|
||
raw = str(node.get('valueType') or 'str')
|
||
return raw if raw in PIN_TYPES else 'str'
|
||
if node['type'] == 'readvar':
|
||
# ★ 读变量的类型**从变量登记表来** —— 这样同一个变量在哪读都是同一个类型。
|
||
# 登记表里没有它时退回节点上写的(老数据容错)。
|
||
name = str(node.get('varName') or '').strip()
|
||
if name in _LAST_VAR_TYPE:
|
||
return _LAST_VAR_TYPE[name]
|
||
raw = str(node.get('valueType') or 'str')
|
||
return raw if raw in PIN_TYPES else 'str'
|
||
if node['type'] == 'cast':
|
||
return _cast_to(node)
|
||
if node['type'] == 'op':
|
||
spec = _OPS_BY_KEY.get(str(node.get('op') or 'add'))
|
||
return spec[3] if spec else 'num'
|
||
return NODE_DATA_OUT.get(node['type'])
|
||
|
||
|
||
def _sanitize_vars(vars: list) -> list:
|
||
"""
|
||
变量登记表消毒。
|
||
名字必须有、不能重复;类型**必选**(认不出来就当 str)。
|
||
"""
|
||
out = []
|
||
seen = set()
|
||
for v in vars or []:
|
||
if not isinstance(v, dict):
|
||
continue
|
||
name = str(v.get('name') or '').strip()
|
||
if not name or name in seen:
|
||
continue
|
||
seen.add(name)
|
||
vtype = str(v.get('type') or 'str')
|
||
out.append({
|
||
'name': name,
|
||
'type': vtype if vtype in PIN_TYPES else 'str',
|
||
'initial': str(v.get('initial') or ''),
|
||
'note': str(v.get('note') or ''),
|
||
})
|
||
return out
|
||
|
||
|
||
def _sanitize_edges(edges: list, nodes: list) -> list:
|
||
"""
|
||
丢掉指向不存在节点的连线,以及**接到没有那个端口的节点上的连线**。
|
||
|
||
端口语义是硬约束:写变量只有输入、读变量只有输出。
|
||
连线文件是可以手改的,也可能来自旧版本的会议,
|
||
留着"接到不存在端口上的边"会在运行时变成一个永远不触发的节点 ——
|
||
这种问题最难查(图看着连了,就是不跑)。
|
||
"""
|
||
by_id = {n['id']: n for n in nodes}
|
||
out = []
|
||
for e in edges:
|
||
if not isinstance(e, dict):
|
||
continue
|
||
src, dst = str(e.get('from') or ''), str(e.get('to') or '')
|
||
if src not in by_id or dst not in by_id or src == dst:
|
||
continue
|
||
# 源必须有输出端口,目标必须有输入端口
|
||
if by_id[src]['type'] in ('end', 'var'):
|
||
# end / var 没有**数据**出线;但它们有 exec 出线(比如 Set 节点
|
||
# 存完继续往下走),所以这里只挡数据线
|
||
if str(e.get('kind') or '') == DATA:
|
||
continue
|
||
# 纯节点(读变量 / 值)没有输入端口,不该被连进来
|
||
if by_id[dst]['type'] in ('start', 'readvar', 'value'):
|
||
continue
|
||
|
||
kind = _kind(e)
|
||
# 老边(没有 kind)当 exec。exec 现在只排顺序、不传数据,
|
||
# 所以老图想传值得补一根数据线 —— 这是类型化之后必然的取舍。
|
||
|
||
# ★ 端口类型校验:exec 只能接 exec,数据只能接**同类型**的数据。
|
||
# 蓝图里连错类型会直接拒绝并提示,这里在保存时把不合法的边丢掉。
|
||
# 不校验的话,把 bool 接到文本输入上会得到一个字符串 "true",
|
||
# 然后模型就懵了 —— 这种错最难查(图看着连对了)。
|
||
if kind != EXEC:
|
||
# ★ 这里**不要**再调 _set_type_context(nodes):它只传 nodes,
|
||
# 会把 _LAST_VAR_TYPE(变量登记表)清空 —— 于是按登记表查类型的
|
||
# readvar / var 全查不到,数据线一保存就被丢掉。
|
||
# 上下文由调用方(save_meeting)设好,这里直接用。
|
||
want = _data_in_type(dst)
|
||
give = _data_out_type(src)
|
||
if want is None or give is None or give not in want:
|
||
continue
|
||
|
||
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or ''), 'kind': kind})
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 执行引擎
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _incoming(edges: list, node_id: str) -> list:
|
||
return [e for e in edges if e.get('to') == node_id]
|
||
|
||
|
||
def _outgoing(edges: list, node_id: str) -> list:
|
||
return [e for e in edges if e.get('from') == node_id]
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 两种连线(照 UE 蓝图的语义)
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 蓝图里引脚分两类,作用完全不同:
|
||
# 执行引脚(exec)白色:**决定执行顺序**。激活输入 → 节点执行 → 激活输出继续往下。
|
||
# 数据引脚(data)彩色:传值。谁把它们连起来,谁在执行时就能拿到对方的值。
|
||
#
|
||
# 我一开始只把节点画成蓝图的样子、引擎还是"谁连着谁就按拓扑序跑",
|
||
# 那是**只学了长相没学语义**。真正的蓝图里:
|
||
# - 顺序完全由 exec 链决定,数据线不决定顺序;
|
||
# - 读变量这种"纯节点"(Get)**没有 exec 引脚**,它的值是被需要的人
|
||
# **拉取**的,自己不在执行链上 —— 这正是"读变量只有输出"的真正原因。
|
||
#
|
||
# 兼容:老会议里没有 kind 字段的边,当成 exec 处理,并且"没有数据入边时
|
||
# 就用 exec 上游的输出"当输入 —— 这样以前那种"一根线连到底"的图行为不变。
|
||
|
||
EXEC = 'exec'
|
||
DATA = 'data'
|
||
|
||
# 数据引脚的类型。和蓝图一样是**强类型**的:连错类型直接接不上。
|
||
PIN_TYPES = ('str', 'bool', 'num')
|
||
|
||
# 老会议里没有 kind 的边当 exec —— 它们仍然负责"跑的顺序",
|
||
# 但**不再顺带传数据**。想传值就得画数据线(界面上现在很好画了)。
|
||
_DATA_KINDS = set(PIN_TYPES)
|
||
|
||
|
||
def _kind(edge: dict) -> str:
|
||
"""边的种类:exec,或某种数据类型(str/bool/num)。认不出来的一律当 exec。"""
|
||
raw = str(edge.get('kind') or '')
|
||
if raw == DATA:
|
||
# 只写了 'data' 没写具体类型的旧数据:当 str(最常见的那种)
|
||
return 'str'
|
||
return raw if raw in _DATA_KINDS else EXEC
|
||
|
||
|
||
def _is_data(edge: dict) -> bool:
|
||
return _kind(edge) in _DATA_KINDS
|
||
|
||
|
||
def _exec_in(edges: list, node_id: str) -> list:
|
||
return [e for e in _incoming(edges, node_id) if _kind(e) == EXEC]
|
||
|
||
|
||
def _exec_out(edges: list, node_id: str, branch: str = None) -> list:
|
||
out = [e for e in _outgoing(edges, node_id) if _kind(e) == EXEC]
|
||
if branch is None:
|
||
return out
|
||
return [e for e in out if (e.get('branch') or 'true') == branch]
|
||
|
||
|
||
def _data_in(edges: list, node_id: str) -> list:
|
||
return [e for e in _incoming(edges, node_id) if _is_data(e)]
|
||
|
||
|
||
def _data_out(edges: list, node_id: str) -> list:
|
||
return [e for e in _outgoing(edges, node_id) if _is_data(e)]
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 纯节点(蓝图里的 Get / 常量)
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 纯节点**没有 exec 引脚**,不在执行链上:它的值是被需要的节点在运行时
|
||
# **拉取**的。所以它们的值不能从 outputs 里找(它们可能根本没被执行链走到过),
|
||
# 得在这里按节点类型现算。
|
||
#
|
||
# 现在有两种:
|
||
# readvar 读变量 —— 谁需要谁拿变量的当前值
|
||
# value 值/常量 —— 谁需要谁拿它自己写死的那个值
|
||
#
|
||
def _pure_value(node_id: str, by_id: dict, outputs: dict, variables: dict):
|
||
"""
|
||
取一个上游节点的值。**纯节点现算**,普通节点取它执行时的输出。
|
||
|
||
★ 哪些是纯节点(蓝图里的纯节点就是没有 exec 引脚的那些):
|
||
读变量 取变量当前值
|
||
值 写死的常量
|
||
转换 把上游的值转成目标类型
|
||
运算 + − × ÷ % 拼接 取反 逻辑非 比较
|
||
|
||
纯节点的值不是"执行时产生的",而是被需要的节点**拉取**时才现算 ——
|
||
所以这里要**递归地往上拉**,而不是去 outputs 里找:
|
||
它们可能压根没被执行链走到过(正因为它们不在执行链上)。
|
||
"""
|
||
node = by_id.get(node_id)
|
||
if not node:
|
||
return outputs.get(node_id, '')
|
||
kind = node['type']
|
||
if kind == 'readvar':
|
||
return variables.get(str(node.get('varName') or '').strip(), '')
|
||
if kind == 'value':
|
||
return node.get('text') or ''
|
||
if kind in ('cast', 'op'):
|
||
# 把自己的数据入线拉一遍 —— 操作数也是这么来的,所以可以层层嵌套
|
||
vals = [_pure_value(e.get('from'), by_id, outputs, variables)
|
||
for e in _data_in(_LAST_EDGES, node_id)]
|
||
if kind == 'cast':
|
||
return cast_value(vals[0] if vals else '', _cast_to(node))
|
||
op_key = str(node.get('op') or 'add')
|
||
spec = _OPS_BY_KEY.get(op_key)
|
||
if not spec:
|
||
return ''
|
||
a = vals[0] if len(vals) > 0 else ''
|
||
b = vals[1] if len(vals) > 1 else ''
|
||
out, _err = apply_op(op_key, a) if spec[4] == 1 else apply_op(op_key, a, b)
|
||
return out
|
||
return outputs.get(node_id, '')
|
||
|
||
def _reachable_exec(edges: list, seeds: list, stop: str = None) -> set:
|
||
"""
|
||
从 seeds 出发、只沿 **exec** 边走,能走到的所有节点。
|
||
|
||
stop 是循环头:走到它就停,不要把它算进去 —— 循环体是"回到循环头之前"
|
||
的那一段,把循环头自己算进来会把它的执行计数也清掉。
|
||
"""
|
||
seen = set()
|
||
stack = list(seeds)
|
||
while stack:
|
||
nid = stack.pop()
|
||
if nid in seen or (stop is not None and nid == stop):
|
||
continue
|
||
seen.add(nid)
|
||
stack.extend(e['to'] for e in _exec_out(edges, nid))
|
||
return seen
|
||
|
||
|
||
def _collect_data_only(node_id: str, edges: list, outputs: dict, variables: dict,
|
||
by_id: dict) -> str:
|
||
"""
|
||
只取**数据入线**的值,不回退到 exec 上游。
|
||
|
||
而循环体上一轮的输出往往是非空文本 —— 那条件就永远为真,直接变成死循环。
|
||
条件拿不到就当空串(= 假),跳出循环,这是最安全的默认。
|
||
"""
|
||
parts = []
|
||
for e in _data_in(edges, node_id):
|
||
value = _pure_value(e.get('from'), by_id, outputs, variables)
|
||
if value:
|
||
parts.append(str(value))
|
||
return '\n\n'.join(parts).strip()
|
||
|
||
|
||
def _collect_input(node_id: str, edges: list, outputs: dict, variables: dict,
|
||
by_id: dict) -> str:
|
||
"""
|
||
算出这个节点的输入文本。
|
||
|
||
★ **只认数据线**。以前这里还留了个"没有数据入边就用 exec 上游的输出"的回退,
|
||
那等于让 exec 偷偷传数据 —— 于是"接一根 exec 线"和"接一根数据线"效果一样,
|
||
类型也没法校验。用户明确说了"exec 执行链不传递数据",所以回退删掉了。
|
||
|
||
代价是老会议里那些"一根线连到底"的图不再自动传值,得补一根数据线。
|
||
但这是对的:顺序和取值本来就不该是同一件事。
|
||
"""
|
||
parts = []
|
||
for e in _data_in(edges, node_id):
|
||
# 纯节点(读变量 / 值)现取现值,普通节点取它执行时的输出
|
||
value = _pure_value(e.get('from'), by_id, outputs, variables)
|
||
if value not in (None, ''):
|
||
parts.append(_as_text(value, _kind(e)))
|
||
return '\n\n'.join(parts).strip()
|
||
|
||
|
||
def _as_text(value, kind: str) -> str:
|
||
"""
|
||
把引脚上的值转成文本。
|
||
|
||
类型信息主要用在**连接校验**和**界面显示**上;真正送进模型/提示词的时候
|
||
终归是文本。所以这里做一次规整:
|
||
bool 统一成 'true'/'false'(模型对这两个词最不容易理解错)
|
||
num 去掉多余小数位
|
||
"""
|
||
if kind == 'bool':
|
||
return 'true' if truthy(value) else 'false'
|
||
if kind == 'num':
|
||
try:
|
||
num = float(value)
|
||
return str(int(num)) if num == int(num) else str(num)
|
||
except (TypeError, ValueError):
|
||
return str(value)
|
||
return str(value)
|
||
|
||
|
||
def _judge_rule(node: dict, text: str) -> bool:
|
||
"""结构化条件判断(不用 eval,理由见文件头)"""
|
||
kind = str(node.get('judgeKind') or 'not_empty')
|
||
value = str(node.get('judgeValue') or '')
|
||
if kind == 'contains':
|
||
return value in text
|
||
if kind == 'not_contains':
|
||
return value not in text
|
||
if kind == 'longer_than':
|
||
try:
|
||
return len(text) > int(value or 0)
|
||
except ValueError:
|
||
return False
|
||
if kind == 'shorter_than':
|
||
try:
|
||
return len(text) < int(value or 0)
|
||
except ValueError:
|
||
return False
|
||
if kind == 'empty':
|
||
return not text.strip()
|
||
if kind == 'not_empty':
|
||
return bool(text.strip())
|
||
return True
|
||
|
||
|
||
def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||
emit, run_agent_fn, should_stop=None) -> dict:
|
||
"""
|
||
跑完一整张图。
|
||
|
||
meeting 会议的节点与连线
|
||
settings 全局设置(智能体没配的模型/语音从这里继承)
|
||
user_input 用户在会议页发的那句话(start 节点文本为空时用它)
|
||
emit 事件回调,直接往 SSE 里写
|
||
run_agent_fn 实际调用模型的那个函数(由 app.py 注入,避免这里 import 一堆东西)
|
||
|
||
事件:
|
||
{'type':'meeting_start', 'nodes': n, 'edges': n}
|
||
{'type':'node_start', 'nodeId', 'nodeType', 'title'}
|
||
{'type':'node_delta', 'nodeId', 'text'} ← 流式增量
|
||
{'type':'node_done', 'nodeId', 'output'}
|
||
{'type':'node_error', 'nodeId', 'error'}
|
||
{'type':'meeting_done', 'output'}
|
||
|
||
为什么用拓扑序 + 访问计数而不是递归:图里可能有环(用户画错了),
|
||
递归会直接爆栈。这里每个节点最多跑一次、总步数有上限,
|
||
画错了也只是"少跑几个节点",不会把 App 拖死。
|
||
"""
|
||
nodes = meeting.get('nodes') or []
|
||
edges = meeting.get('edges') or []
|
||
by_id = {n['id']: n for n in nodes}
|
||
outputs = {}
|
||
# 纯节点(读变量/值/转换/运算)求值时要能找到自己的数据入线
|
||
_set_type_context(nodes, meeting.get('vars') or [], edges)
|
||
|
||
emit({'type': 'meeting_start', 'nodes': len(nodes), 'edges': len(edges)})
|
||
|
||
# 入口:优先 start 节点;没有就从"没有 exec 入边"的节点开始。
|
||
#
|
||
# ★ 读变量是**纯节点**(蓝图里的 Get),不在执行链上 —— 它的值是被
|
||
# 需要的节点在运行时"拉"过去的,所以不能当入口,也不进队列。
|
||
starts = [n for n in nodes if n['type'] == 'start']
|
||
if not starts:
|
||
starts = [n for n in nodes
|
||
if n['type'] not in ('readvar', 'value') and not _exec_in(edges, n['id'])]
|
||
if not starts:
|
||
emit({'type': 'meeting_done', 'output': '', 'error': '这张图没有入口节点'})
|
||
return {'output': '', 'error': '这张图没有入口节点'}
|
||
|
||
queue = [n['id'] for n in starts]
|
||
|
||
# ★ 每个节点跑了几次(不是"跑没跑过")。
|
||
#
|
||
# 用户要的是"n1 → n2 → n1 只有一轮,但**能重复**":
|
||
# 默认每节点 1 次(= 不重复,和以前一样),把节点上的「最多执行次数」
|
||
# 调大就能来回跑 —— 比如两个节点都设 3,就是 n1/n2 各跑三轮。
|
||
#
|
||
# 以前用的是 visited 集合(跑过就不再跑),环永远只转一圈,没法重复。
|
||
runs = {}
|
||
steps = 0
|
||
|
||
# 变量表:整场会议共享。var / readvar 节点和授权过的智能体都能读写它。
|
||
#
|
||
# ★ 先按**变量登记表**初始化:这样读变量第一轮就能读到东西,
|
||
# 不用非得先有个写变量节点跑过一遍。
|
||
# 用户要的"配置变量的初始化"就是这个。
|
||
variables = {}
|
||
for _v in (meeting.get('vars') or []):
|
||
_name = str(_v.get('name') or '').strip()
|
||
if _name:
|
||
variables[_name] = str(_v.get('initial') or '')
|
||
|
||
def limit_of(node: dict) -> int:
|
||
"""
|
||
节点的执行次数上限。**0 表示无限**。
|
||
|
||
为什么要支持无限:两个智能体互相点评(甲评乙、乙再评甲)是常见用法,
|
||
用户希望一直怼下去,自己觉得够了再按停止。
|
||
|
||
为什么敢开无限:引擎每一轮都会检查 should_stop(客户端断开或用户点了停止),
|
||
所以"无限"实际是"跑到你喊停为止",不是真的停不下来。
|
||
另外还兜了一个很大的硬上限 MAX_STEPS_HARD,防止用户忘了停、
|
||
或者客户端异常断开时把额度烧光。
|
||
"""
|
||
raw = node.get('maxRuns')
|
||
try:
|
||
value = int(raw) if raw is not None else 1
|
||
except (TypeError, ValueError):
|
||
value = 1
|
||
return 0 if value <= 0 else min(value, 20)
|
||
|
||
budget = sum((limit_of(n) or 200) for n in nodes)
|
||
# 硬上限:无限循环时预算按每节点 200 次估,再乘 2 留余量。
|
||
# 这不是"限制用户",是**防止客户端异常断开时把额度烧光** ——
|
||
# 正常用停止按钮就能收尾,根本碰不到这个数。
|
||
max_steps = max(20, budget * 2 + len(nodes))
|
||
|
||
final_output = ''
|
||
|
||
def can_run(node_id: str) -> bool:
|
||
node = by_id.get(node_id)
|
||
if not node:
|
||
return False
|
||
# ★ while 节点**不受 maxRuns 管**:它每一轮都要重新判断条件,
|
||
# 循环几次是**条件**说了算,不是"最多执行次数"说了算。
|
||
# 不豁免的话第二轮就被挡掉,循环只转一圈就没了
|
||
# (踩过:执行序列 s,w0,wh,a,w1 之后直接结束)。
|
||
if node['type'] == 'while':
|
||
return True
|
||
limit = limit_of(node)
|
||
# 0 = 无限:永远还能再跑一次
|
||
return limit == 0 or runs.get(node_id, 0) < limit
|
||
|
||
def wake_readers(var_name: str) -> None:
|
||
"""
|
||
变量被写入后要做的事。
|
||
|
||
★ 蓝图里"读变量"是**纯节点**(Get):它不在执行链上,值是被需要的
|
||
节点在运行时拉取的(见 _collect_input)。所以这里**不需要**叫醒谁 ——
|
||
留着这个函数是为了集中说明这件事,免得以后有人又加回"唤醒"逻辑,
|
||
那会和"拉取"重复执行一遍。
|
||
"""
|
||
return
|
||
|
||
# 每个 while 节点转了多少轮。单次运行里超过 MAX_LOOP_ITERS 就强制跳出 ——
|
||
# 条件永远为真时不至于把额度烧光,而且会给一条明确的事件说明为什么停。
|
||
iters = {}
|
||
|
||
def walk(seed: list, depth: int = 0, stop_at: str = None) -> bool:
|
||
"""
|
||
跑一串执行链,直到走不下去。
|
||
|
||
★ 为什么做成可递归的:while 节点的语义是"**循环体整段跑完**再回到判断"。
|
||
用一个平铺的队列做不到这件事 —— 队列是先进先出,循环体第一个节点刚入队,
|
||
while 自己就又被弹出来了,判断会在循环体还没跑的时候就重来一遍。
|
||
所以循环体在这里是一次**嵌套的 walk**,跑干净了才回到 while。
|
||
|
||
深度上限兜底:嵌套只可能来自 while 套 while,正常用不了几层。
|
||
"""
|
||
nonlocal steps, final_output
|
||
queue = list(seed)
|
||
while queue and steps < max_steps:
|
||
if should_stop and should_stop():
|
||
raise _Aborted()
|
||
|
||
node_id = queue.pop(0)
|
||
steps += 1
|
||
if not can_run(node_id):
|
||
continue
|
||
|
||
node = by_id.get(node_id)
|
||
if not node:
|
||
continue
|
||
|
||
run_index = runs.get(node_id, 0) + 1
|
||
runs[node_id] = run_index
|
||
node_type = node['type']
|
||
title = node.get('title') or {'start': '初始输入', 'agent': '智能体', 'judge': '判断',
|
||
'end': '最终输出', 'var': '写变量',
|
||
'readvar': '读变量', 'while': 'while 循环'}.get(node_type, node_type)
|
||
emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type,
|
||
'title': title, 'run': run_index, 'maxRuns': limit_of(node)})
|
||
|
||
incoming = _collect_input(node_id, edges, outputs, variables, by_id)
|
||
|
||
# ★ 输入是空的、但 exec 上游明明有内容 → **大声报出来**。
|
||
#
|
||
# 这是最容易踩、也最难查的一个坑:exec 线只排顺序、不传值,
|
||
# 所以"一根线连到底"的图里下游拿到的是空串。
|
||
# 判断节点拿到空串时,"为空"当然为真 —— 用户看到的是
|
||
# "明明有值却判断为真",怎么查都查不出规则哪里错了(规则本身没错)。
|
||
#
|
||
# 与其让它悄悄判错,不如直接说"你漏画了一根数据线"。
|
||
if not _data_in(edges, node_id):
|
||
ups = [(e.get('from'), outputs.get(e.get('from')))
|
||
for e in _exec_in(edges, node_id)]
|
||
ups = [(nid, t) for nid, t in ups if t]
|
||
if ups:
|
||
who = by_id.get(ups[0][0], {}).get('title') or ups[0][0]
|
||
emit({
|
||
'type': 'node_warn',
|
||
'nodeId': node_id,
|
||
'warn': f'输入是空的:上游「{who}」有内容,但你没连**数据线**。'
|
||
f'exec 线只排顺序、不传值 —— 要传值得再连一根彩色数据线。',
|
||
})
|
||
|
||
try:
|
||
if node_type == 'start':
|
||
# 第二轮开始,"初始输入"要把**自己上一轮的输出**当输入,
|
||
# 否则循环回来的内容会被起点覆盖掉,重复就没意义了
|
||
text = incoming or (node.get('text') or '').strip() or (user_input or '')
|
||
outputs[node_id] = text
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type, 'output': text,
|
||
'run': run_index, 'note': '用的初始输入'})
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
|
||
elif node_type == 'while':
|
||
# ★ 和 C 的 while 一样:**先判断、再执行循环体**,假就跳出。
|
||
#
|
||
# 条件从**数据入线**拉(一般是"读变量"),所以循环体改了变量之后
|
||
# 下一轮判断就能看到新值 —— 这是循环能收敛的唯一途径。
|
||
cond_text = _collect_data_only(node_id, edges, outputs, variables, by_id)
|
||
keep = truthy(cond_text)
|
||
used = iters.get(node_id, 0)
|
||
forced = False
|
||
if keep and used >= MAX_LOOP_ITERS:
|
||
# 转够了就强制跳出,并说清楚是为什么 ——
|
||
# 静默停会让用户以为"条件写对了但没生效"
|
||
forced = True
|
||
keep = False
|
||
|
||
outputs[node_id] = cond_text
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type, 'output': cond_text,
|
||
'run': run_index, 'verdict': keep,
|
||
'branch': 'body' if keep else 'done',
|
||
'note': (f'第 {used + 1} 轮:条件={cond_text[:30]!r} → '
|
||
+ ('继续循环' if keep else '结束循环'))
|
||
+ (f'(已达上限 {MAX_LOOP_ITERS} 轮,强制结束)' if forced else '')})
|
||
|
||
outs = _exec_out(edges, node_id)
|
||
if keep:
|
||
iters[node_id] = used + 1
|
||
body = [e['to'] for e in outs if (e.get('branch') or 'body') == 'body']
|
||
if body:
|
||
# ★ 每轮开始前,把**循环体里能走到的节点**的执行计数清掉。
|
||
#
|
||
# 不清的话,循环体里的节点第二轮就被 maxRuns(默认 1)
|
||
# 挡在门外 —— 循环只转一圈,等于没用
|
||
# (踩过:序列 s,w0,wh,a,w1,wh 之后第二轮 body 直接空转)。
|
||
#
|
||
# 语义上也讲得通:maxRuns 管的是"这个节点在这次运行里
|
||
# 最多被走到几次",而 while 的每一轮是**一次新的执行**,
|
||
# 该重新计数。循环次数由 while 的条件和轮次上限管。
|
||
for nid in _reachable_exec(edges, body, stop=node_id):
|
||
runs.pop(nid, None)
|
||
|
||
# ★ **循环体跑完就自动回到判断**,不管它有没有连回来。
|
||
#
|
||
# 蓝图里 While Loop 的「循环体」是特殊的 deferred 引脚:
|
||
# body 那段执行完,控制流**自动**回到 While 节点重新判断。
|
||
# 用户不需要(也不应该)画一根回边。
|
||
#
|
||
# 我之前要求"循环体最后必须连回 while"才继续,
|
||
# 于是没画回边的图只转一圈就停了 —— 用户报的
|
||
# "while 只能运行一次"就是这个。
|
||
#
|
||
# stop_at 只用来让"画了回边"的图**早停**
|
||
# (不然会顺着回边多跑一圈 while)。两种情况都回到判断。
|
||
walk(body, depth + 1, stop_at=node_id)
|
||
queue.insert(0, node_id)
|
||
else:
|
||
done = [e['to'] for e in outs if (e.get('branch') or 'body') == 'done']
|
||
next_ids = done
|
||
# ★ 和判断节点同一个道理:**不在"结束"上就连"循环体"**,
|
||
# 那是要走错路的 —— 条件已经为假了还去跑循环体,
|
||
# 要么空转要么死循环,而且看不出为什么。
|
||
# 停下 + 说清楚该补哪根线。
|
||
if not done and outs:
|
||
emit({
|
||
'type': 'node_warn',
|
||
'nodeId': node_id,
|
||
'warn': '循环条件是「假」、该走「结束」那条出线,'
|
||
'但你只连了「循环体」—— 执行链在这里停了。'
|
||
'把「结束」连到循环后面的节点上。',
|
||
})
|
||
if keep:
|
||
continue
|
||
|
||
elif node_type == 'agent':
|
||
raw = run_agent_fn(node, incoming, settings, emit, node_id, variables)
|
||
# ★ 把 [[SET 名字=值]] 抽出来写进变量,正文里不留那些行。
|
||
#
|
||
# 这件事放在**引擎**里而不是"调用引擎的那一层":
|
||
# 它是节点语义的一部分("这个智能体能写哪些变量"是节点配置),
|
||
# 放在外面的话 —— 换个调用方就忘了做,而且引擎自己的测试
|
||
# 压根覆盖不到(真发生过:引擎测试全绿,一上 HTTP 就漏出 [[SET]])。
|
||
cleaned, changed = apply_sets(raw, variables, node.get('writeVars'))
|
||
outputs[node_id] = cleaned
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type, 'output': cleaned, 'run': run_index})
|
||
if changed:
|
||
# 改了哪些变量要让用户看见,不然就是"背地里改了我的东西"
|
||
emit({'type': 'node_vars', 'nodeId': node_id, 'vars': changed,
|
||
'note': '、'.join(f'{k} = {str(v)[:30]}' for k, v in changed.items())})
|
||
|
||
# ★ 智能体是"多路"的:输出一边照常往下游走,一边**同时**存进变量。
|
||
# 用户的原话是"既可以把输出给下一个智能体的同时也可以保存到变量"——
|
||
# 所以做成节点上的一个字段,而不是再拉一根线到「写变量」节点:
|
||
# 光为了存个值就得摆两个节点、连一根线,太重了。
|
||
#
|
||
# 两条路互不影响:下游拿到的是**剥掉 [[SET]] 之后**的正文,
|
||
# 存进变量的也是同一份(不然变量里会混进控制行)。
|
||
save_to = str(node.get('saveToVar') or '').strip()
|
||
if save_to:
|
||
variables[save_to] = cleaned
|
||
emit({'type': 'node_vars', 'nodeId': node_id, 'vars': {save_to: cleaned},
|
||
'note': f'输出已存到 {save_to}'})
|
||
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
|
||
elif node_type == 'var':
|
||
# 写变量节点:有写死的值就用它,否则用上游
|
||
name = str(node.get('varName') or '').strip()
|
||
if not name:
|
||
raise ValueError('变量节点没填变量名')
|
||
|
||
value = (node.get('varValue') or '').strip()
|
||
note = ''
|
||
if not value:
|
||
value = incoming
|
||
# ★ **没连数据线时,退一步用 exec 上游的输出。**
|
||
#
|
||
# "exec 不传递数据"这条规则是对的,但对**写变量**太苛刻:
|
||
# 用户的心智模型就是"这根线连过来了,所以把刚才产生的东西存进去"。
|
||
# 逼他们必须再拉一根数据线,结果就是反复踩同一个坑
|
||
# (这个问题被反馈了三次)。
|
||
#
|
||
# 所以做一个**有交代的例外**:没数据线就用 exec 上游的输出,
|
||
# 并且在节点上明确写出来"用了上游的输出" ——
|
||
# 不是悄悄猜,用户一眼能看到引擎替他做了什么。
|
||
if not _data_in(edges, node_id):
|
||
ups = [outputs.get(e.get('from'))
|
||
for e in _exec_in(edges, node_id)]
|
||
ups = [t for t in ups if t]
|
||
if ups:
|
||
value = ups[-1]
|
||
note = '(没连数据线,用了 exec 上游的输出)'
|
||
variables[name] = value
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type,
|
||
'output': value, 'run': run_index,
|
||
'note': (name + ' = ' + str(value)[:40] + note).strip()})
|
||
# ★ 写变量**有 exec 出线**(蓝图里 Set 节点就是 exec 进 → exec 出),
|
||
# 只是没有**数据**出线 —— 存进去的值不从它这里往下传。
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
elif node_type == 'readvar':
|
||
# ★ 读变量是**纯节点**(蓝图里的 Get),正常情况下不该被执行链走到 ——
|
||
# 它的值由 _collect_input 在需要的那一刻直接拉取。
|
||
name = str(node.get('varName') or '').strip()
|
||
if not name:
|
||
raise ValueError('读变量节点没填变量名')
|
||
value = variables.get(name, '')
|
||
outputs[node_id] = value
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type, 'output': value, 'run': run_index,
|
||
'note': f'读到 {name}' + ('' if value else '(还没设过,是空的)')})
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
|
||
elif node_type == 'cast':
|
||
# 转换节点:把输入转成 castTo 指定的类型
|
||
target = _cast_to(node)
|
||
out = cast_value(incoming, target)
|
||
outputs[node_id] = out
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type,
|
||
'output': out, 'run': run_index,
|
||
'note': f'{str(incoming)[:20]} → {target}({out})'})
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
|
||
elif node_type == 'op':
|
||
# 运算节点:两个入口(单目只用 A),结果从数据出口往下传
|
||
op_key = str(node.get('op') or 'add')
|
||
spec = _OPS_BY_KEY.get(op_key)
|
||
if not spec:
|
||
raise ValueError(f'不认识的运算:{op_key}')
|
||
arity = spec[4]
|
||
# 两个操作数从**两根数据入线**分别取(按连线顺序)
|
||
vals = [_pure_value(e.get('from'), by_id, outputs, variables)
|
||
for e in _data_in(edges, node_id)]
|
||
a = vals[0] if len(vals) > 0 else incoming
|
||
b = vals[1] if len(vals) > 1 else ''
|
||
if arity == 1:
|
||
out, err = apply_op(op_key, a)
|
||
else:
|
||
out, err = apply_op(op_key, a, b)
|
||
outputs[node_id] = out
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type,
|
||
'output': out, 'run': run_index,
|
||
'note': f'{spec[1]}:{str(a)[:16]} / {str(b)[:16]} → {out}'
|
||
+ (f'({err})' if err else '')})
|
||
if err:
|
||
emit({'type': 'node_warn', 'nodeId': node_id, 'warn': err})
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
|
||
elif node_type == 'judge':
|
||
kind = str(node.get('judgeKind') or 'not_empty')
|
||
if kind == 'ai':
|
||
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id, variables)
|
||
passed = 'YES' in verdict.upper()[:40] or '是' in verdict[:20]
|
||
else:
|
||
passed = _judge_rule(node, incoming)
|
||
# ★ 判断节点必须**透传上游内容**,不能把自己的输出改成 "true"/"false"。
|
||
# 否则下游智能体收到的输入就变成字符串 "true" 了,完全没法用 ——
|
||
# 这个错误是验证脚本抓到的(输出是"真 收到[true]")。
|
||
# 判断结论走 verdict 字段,不占 output。
|
||
outputs[node_id] = incoming
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type,
|
||
'output': incoming,
|
||
'run': run_index,
|
||
'verdict': passed,
|
||
'branch': 'true' if passed else 'false',
|
||
'note': f'判断结果:{passed}'})
|
||
# 判断节点走 true / false 两条 **exec** 出边;
|
||
# 没标分支的那条当默认(true)
|
||
outs = _exec_out(edges, node_id)
|
||
want = 'true' if passed else 'false'
|
||
next_ids = [e['to'] for e in outs if (e.get('branch') or 'true') == want]
|
||
# ★ 判成的那条分支没连线 → **就在这儿停**,不要顺走另一条。
|
||
#
|
||
# 原来这里有个"兜底":没连就走第一条。结果判成「假」而用户只连了
|
||
# 「真」时,执行流会**悄悄拐进真分支** —— 用户看到的是
|
||
# "判断为假为啥要写变量?",图上明明是绿的(真)却按假的结果跑,
|
||
# 而且引擎不报错、链也没断,怎么查都查不出来。
|
||
#
|
||
# 走错路比停下糟糕得多。停下 + 说清楚,用户一眼知道该补哪根线。
|
||
if not next_ids and outs:
|
||
emit({
|
||
'type': 'node_warn',
|
||
'nodeId': node_id,
|
||
'warn': '判断结果是「' + ('真' if passed else '假')
|
||
+ '」,但你没连' + ('真' if passed else '假')
|
||
+ '分支的线 —— 执行链在这里停了。'
|
||
'要么补上那根线,要么改用另一条分支。',
|
||
})
|
||
|
||
elif node_type == 'end':
|
||
outputs[node_id] = (node.get('text') or '').strip() or incoming
|
||
final_output = outputs[node_id]
|
||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type, 'output': final_output, 'run': run_index})
|
||
next_ids = []
|
||
|
||
else:
|
||
emit({'type': 'node_error', 'nodeId': node_id, 'nodeType': node_type, 'error': f'不认识的节点类型:{node_type}'})
|
||
next_ids = []
|
||
|
||
except Exception as exc: # noqa: BLE001
|
||
# 单个节点出错不该让整场会议停摆:记下来,继续跑下游
|
||
emit({'type': 'node_error', 'nodeId': node_id, 'nodeType': node_type, 'error': str(exc), 'run': run_index})
|
||
outputs[node_id] = ''
|
||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||
|
||
# ★ 只有"还能再跑"的节点才重新入队。
|
||
# 这就是"重复"的开关:maxRuns=1(默认)时,跑过的节点不会再进来,
|
||
# 环也只转一圈;把它调大,环就会来回转到次数用完为止。
|
||
#
|
||
# while 节点例外:它的重复靠自己的轮次计数(iters),不受 maxRuns 管 ——
|
||
# 否则用户还得为"要循环几次"再去设一个和循环无关的数字。
|
||
for nid in next_ids:
|
||
if by_id.get(nid, {}).get('type') == 'while' or can_run(nid):
|
||
queue.append(nid)
|
||
|
||
try:
|
||
walk(queue)
|
||
except _Aborted:
|
||
emit({'type': 'meeting_done', 'output': final_output, 'aborted': True})
|
||
return {'output': final_output, 'aborted': True}
|
||
|
||
emit({'type': 'meeting_done', 'output': final_output})
|
||
return {'output': final_output}
|