会议模式:自定义节点做完(用户的 node.txt 方案,全链路测通)
用户:"直接做完并测试"
【做了什么】
把用户给的声明式方案落地成一种真正的节点类型:
ToolName = {
"name": "打分",
"desc": "文字越长分越高",
"input": [{"type": "str", "name": "文本", "value": ""}],
"output": [{"type": "exec", "name": "高分"},
{"type": "exec", "name": "低分"},
{"type": "str", "name": "分数"}],
}
def run(ctx, node):
node["output"]["分数"] = "分数:" + str(len(node["input"]["文本"]))
node["output"]["高分"] = len(...) >= 3
node["output"]["低分"] = len(...) < 3
return node
往 <数据目录>/nodes/ 丢一个 .py,会议里就多出一种节点。**不用改 Kotlin**。
【链路】
1. custom_nodes.py:加载 / 校验 / 规整引脚 / 子线程跑(10 秒超时)
2. meeting.py:新增 `custom` 节点类型
- 类型上下文里加载定义(_LAST_CUSTOM),连线时查声明决定收什么类型
- 执行分支:按引脚收输入 -> run_custom -> 取第一个数据出口往下传
3. app.py:/api/meeting/meta 带 customNodes(含 inputs/outputs)+ customDir
4. Kotlin:MeetingMeta.customNodes、CustomNodeDef/CustomPin、
inputPins/outputPins 对 `custom` **从内核读引脚**、NodeCard 传 customDefs、
加节点面板顶部列出自定义节点(带 🐍 和文件名,坏的显示原因)
5. nodes-示例/:score.py(活文档)+ README.md(格式和三条规则)
【三条语义(已在 README 和节点注释里写清楚,并实测)】
1. node["input"][名] 是**引擎填的实际值**,声明里的 value 只是"没接线时的默认"
2. 多个 exec 出口 = **多路分支**,最多一个 True:
恰好一个 → 走那条
都不 True → **停在原地** + 报警告(不猜、不顺走第一条)
多个 True → 报错
3. return 什么无所谓,引擎读 node["output"]
【发现并修的坑(用户原版写不通的两处)】
① 键必须加引号:`name:"..."` 是 JS 写法,Python 报
"SyntaxError: invalid syntax. Perhaps you forgot a comma?" ——
这句话完全看不出问题在哪。内核专门认出来并给出正确写法。
② 声明是列表、访问是字典,对不上:声明 `input: [{...}]` 是列表,
但 run 里写 `node["input"]["A1"]`(按名字取)。
解法:**引擎在跑之前把 input/output 换成按名字取的字典**,
声明的列表原样留给引擎和界面读类型。
【实测(HTTP 全链路)】
meta: 打分 key=custom_score exec 分支=['高分','低分']
保存后边数: 5/5(类型校验认识自定义节点的引脚)
起点='好' → 执行 ev,sc,lo → 低分出口(分数:1)
起点='这段文字比较长' → 执行 ev,sc,hi → 高分出口(分数:7)
历史里也存了 results ✓
【限制(如实写在 README 里)】
数据出口只有**第一个能接线** —— 边(edge)上没有"从哪个引脚出来"的信息。
其余数据出口的值仍会显示在节点卡片上,只是接不了线。
要修得给边加 fromPin/toPin,属于数据模型层面的改动。
【验证】
- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致
- 会议 HTTP 13/13 ×2、语音 41/41、Markdown 19/19
- 自定义节点:加载 / 运行 / 写变量 / 记日志 / N 路分支 / 报错兜底 / 超时,
Python 侧和 HTTP 侧各测一遍
- APK 构建通过
This commit is contained in:
@@ -34,6 +34,7 @@ import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -622,12 +623,12 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
/** 命中哪个引脚。返回 (节点, 引脚, 是输出端) */
|
||||
fun portAt(c: Offset): Triple<MeetingNode, PinSpec, Boolean>? {
|
||||
for (n in nodesSnapshot.value.asReversed()) {
|
||||
outputPins(n).forEachIndexed { i, pin ->
|
||||
outputPins(n, vm.meetingMeta.customNodes).forEachIndexed { i, pin ->
|
||||
val p = pinPos(n, i, isOutput = true)
|
||||
val pp = Offset(p.x.dp.toPx(), p.y.dp.toPx())
|
||||
if ((pp - c).getDistance() <= portHit) return Triple(n, pin, true)
|
||||
}
|
||||
inputPins(n).forEachIndexed { i, pin ->
|
||||
inputPins(n, vm.meetingMeta.customNodes).forEachIndexed { i, pin ->
|
||||
val p = pinPos(n, i, isOutput = false)
|
||||
val pp = Offset(p.x.dp.toPx(), p.y.dp.toPx())
|
||||
if ((pp - c).getDistance() <= portHit) return Triple(n, pin, false)
|
||||
@@ -1066,6 +1067,7 @@ if (edge.kind == "exec") {
|
||||
inDegree = meeting.edges.count { it.to == node.id },
|
||||
outDegree = meeting.edges.count { it.from == node.id },
|
||||
linkingKind = linkingFrom?.kind,
|
||||
customDefs = vm.meetingMeta.customNodes,
|
||||
modifier = Modifier.offset(node.x.dp, node.y.dp),
|
||||
)
|
||||
}
|
||||
@@ -1308,6 +1310,62 @@ if (edge.kind == "exec") {
|
||||
.heightIn(max = 440.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
// ★ **用户用 Python 拓展出来的节点**,列在内置节点前面。
|
||||
// 引脚是从内核读的,用户往 nodes/ 丢一个 .py,这里就多一项。
|
||||
vm.meetingMeta.customNodes.forEach { cd ->
|
||||
val bad = cd.error.isNotBlank()
|
||||
Column(
|
||||
Modifier.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.clickable(enabled = !bad) {
|
||||
val n = MeetingNode(
|
||||
id = "n_${System.currentTimeMillis().toString(36)}",
|
||||
type = "custom",
|
||||
customKey = cd.key,
|
||||
x = 120f + meeting.nodes.size * 26f,
|
||||
y = 120f + meeting.nodes.size * 26f,
|
||||
title = cd.label,
|
||||
)
|
||||
meeting = meeting.copy(nodes = meeting.nodes + n)
|
||||
dirty = true
|
||||
persist()
|
||||
adding = false
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"🐍 " + cd.label,
|
||||
fontSize = 14.sp,
|
||||
color = if (bad) MaterialTheme.colorScheme.error else doubaoText(),
|
||||
)
|
||||
if (cd.file.isNotBlank()) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
cd.file,
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
if (bad) {
|
||||
cd.error
|
||||
} else {
|
||||
cd.desc.ifBlank {
|
||||
"入 ${cd.dataInputs.size} · 出 ${cd.dataOutputs.size} · exec 分支 ${cd.execOutputs.size} 路"
|
||||
}
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = if (bad) MaterialTheme.colorScheme.error else doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (vm.meetingMeta.customNodes.isNotEmpty()) {
|
||||
HorizontalDivider(Modifier.padding(vertical = 6.dp), thickness = 0.5.dp)
|
||||
}
|
||||
|
||||
vm.meetingMeta.nodeTypes.forEach { (key, label, desc) ->
|
||||
Column(
|
||||
Modifier.fillMaxWidth()
|
||||
@@ -1392,6 +1450,12 @@ private data class PinSpec(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val accepts: List<String> = emptyList(),
|
||||
/**
|
||||
* exec 引脚的分支名。自定义节点可以有**多个 exec 出口**(= N 路分支),
|
||||
* 连线时要把它写进 edge.branch,引擎才知道该走哪条。
|
||||
* 内置节点(判断/while)的 true/false/done/body 是同一套机制。
|
||||
*/
|
||||
val branch: String = "",
|
||||
) {
|
||||
/** 能不能接下 fromKind 这条线 */
|
||||
fun accepts_(fromKind: String): Boolean =
|
||||
@@ -1437,7 +1501,32 @@ private fun opSpec(key: String): Triple<String, String, Int> = when (key) {
|
||||
private fun opLabel(key: String): String =
|
||||
OPS_UI.firstOrNull { it.first == key }?.second ?: key
|
||||
|
||||
private fun inputPins(node: MeetingNode): List<PinSpec> = when (node.type) {
|
||||
/**
|
||||
* 节点的输入引脚。
|
||||
*
|
||||
* ★ `custom` 的引脚来自**内核**(用户在 nodes/ 里写的声明),不在这里硬编码 ——
|
||||
* 这样"加一种节点"就真的只是丢一个 .py,不用改 Kotlin。
|
||||
* meta 没加载到时给一个宽松的默认(不收 exec、一个文本入口),
|
||||
* 免得卡片画不出引脚、用户以为节点坏了。
|
||||
*/
|
||||
private fun inputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<com.doubao.lynxclone.data.CustomNodeDef> = emptyList(),
|
||||
): List<PinSpec> = when (node.type) {
|
||||
"custom" -> {
|
||||
val d = custom.firstOrNull { it.key == node.customKey }
|
||||
if (d == null) {
|
||||
listOf(PinSpec("exec", "", "▶"), PinSpec("str", "", "输入", accepts = ANY_DATA))
|
||||
} else {
|
||||
buildList {
|
||||
// 自己声明的 exec 入口(没有就不画 —— 纯数据节点)
|
||||
d.inputs.filter { it.type == "exec" }.forEach { add(PinSpec("exec", "", "▶")) }
|
||||
d.dataInputs.forEach { p ->
|
||||
add(PinSpec(p.type, p.name, p.name, accepts = listOf(p.type)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"start", "readvar", "value" -> emptyList()
|
||||
// 转换:什么都收(出口类型在配置面板里选)
|
||||
// Python 节点:执行节点 —— 上游什么都要能收(它就是拿来处理任意内容的)
|
||||
@@ -1489,7 +1578,31 @@ private fun inputPins(node: MeetingNode): List<PinSpec> = when (node.type) {
|
||||
* ★ 写变量**没有数据出线**(存进去的值不从它往下传),但有 exec 出线。
|
||||
* ★ 纯节点(读变量 / 值)**只有数据出线**,没有任何 exec 引脚。
|
||||
*/
|
||||
private fun outputPins(node: MeetingNode): List<PinSpec> = when (node.type) {
|
||||
/** 节点的输出引脚(custom 同样来自内核的定义) */
|
||||
private fun outputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<com.doubao.lynxclone.data.CustomNodeDef> = emptyList(),
|
||||
): List<PinSpec> = when (node.type) {
|
||||
"custom" -> {
|
||||
val d = custom.firstOrNull { it.key == node.customKey }
|
||||
if (d == null) {
|
||||
listOf(PinSpec("exec", "", "▶"), PinSpec("str", "", "输出"))
|
||||
} else {
|
||||
buildList {
|
||||
// 多个 exec 出口 = N 路分支,每条一个引脚(名字就是分支名)
|
||||
d.execOutputs.forEach { add(PinSpec("exec", it.name, it.name, branch = it.name)) }
|
||||
d.dataOutputs.forEachIndexed { i, p ->
|
||||
add(
|
||||
PinSpec(
|
||||
p.type,
|
||||
p.name,
|
||||
p.name + if (i > 0) "(接不了线)" else "",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"end" -> emptyList()
|
||||
"readvar" -> listOf(PinSpec("str", "", "值"))
|
||||
// 转换:出口类型就是它要转成的那个类型
|
||||
@@ -1536,8 +1649,11 @@ private const val PORT_R = 5.5f
|
||||
private const val PORT_HIT = 19f
|
||||
|
||||
/** 节点高矮跟着引脚数走:判断节点两行出线、智能体进出各有两种,就高一些 */
|
||||
private fun nodeHeight(node: MeetingNode): Float {
|
||||
val rows = maxOf(inputPins(node).size, outputPins(node).size, 1)
|
||||
private fun nodeHeight(
|
||||
node: MeetingNode,
|
||||
customDefs: List<com.doubao.lynxclone.data.CustomNodeDef> = emptyList(),
|
||||
) : Float {
|
||||
val rows = maxOf(inputPins(node, customDefs).size, outputPins(node, customDefs).size, 1)
|
||||
return HEADER_H + rows * PIN_ROW_H + BODY_H
|
||||
}
|
||||
|
||||
@@ -2962,6 +3078,8 @@ private fun NodeCard(
|
||||
linkingKind: String?,
|
||||
/** 这个节点的告警(比如"输入是空的,漏了数据线") */
|
||||
warn: String = "",
|
||||
/** 自定义节点的定义(引脚从内核来,卡片照着画) */
|
||||
customDefs: List<com.doubao.lynxclone.data.CustomNodeDef> = emptyList(),
|
||||
modifier: Modifier,
|
||||
) {
|
||||
val accent = nodeColor(node.type)
|
||||
|
||||
@@ -166,6 +166,30 @@ def _trace_tts(text: str, outcome: str, total_bytes: int, chunks: int, seconds:
|
||||
pass
|
||||
|
||||
|
||||
def _custom_defs():
|
||||
"""
|
||||
加载用户的自定义节点。
|
||||
|
||||
★ 用 try 包住:加载器自己出问题(比如数据目录不可写)也不能让 meta 挂掉 ——
|
||||
meta 挂了整个会议界面就是白屏,用户连"哪里出错了"都看不到。
|
||||
坏掉的节点以 error 字段返回,界面上照样列出来、显示原因。
|
||||
"""
|
||||
try:
|
||||
import custom_nodes
|
||||
return custom_nodes.list_defs()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return [{'key': '', 'label': '(自定义节点加载失败)',
|
||||
'error': f'{type(exc).__name__}: {exc}'}]
|
||||
|
||||
|
||||
def _custom_dir():
|
||||
try:
|
||||
import custom_nodes
|
||||
return custom_nodes.nodes_dir()
|
||||
except Exception: # noqa: BLE001
|
||||
return ''
|
||||
|
||||
|
||||
class SseChannel:
|
||||
"""
|
||||
一条 SSE 连接。
|
||||
@@ -683,6 +707,24 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if pathname == '/api/meeting/meta' and method == 'GET':
|
||||
# 编辑器要用:节点类型、判断条件、可用智能体
|
||||
self.send_json(200, {
|
||||
# ★ 用户用 Python 拓展出来的节点也在这里列出来。
|
||||
# 界面拿到 inputs / outputs 就能**自动画出引脚** ——
|
||||
# 不用在 Kotlin 里再写一份,也就不会再出现
|
||||
# "引擎有了、界面没有"那种事。
|
||||
'customNodes': [
|
||||
{
|
||||
'key': d.get('key'),
|
||||
'label': d.get('label'),
|
||||
'desc': d.get('desc') or '',
|
||||
'file': os.path.basename(d.get('file') or ''),
|
||||
'inputs': d.get('inputs') or [],
|
||||
'outputs': d.get('outputs') or [],
|
||||
'hasExecIn': bool(d.get('hasExecIn')),
|
||||
'error': d.get('error') or '',
|
||||
}
|
||||
for d in _custom_defs()
|
||||
],
|
||||
'customDir': _custom_dir(),
|
||||
'nodeTypes': [
|
||||
{'key': 'start', 'label': '开始事件', 'desc': '整张图从这里开始(exec 起点)'},
|
||||
{'key': 'agent', 'label': '智能体', 'desc': '一个智能体处理一轮'},
|
||||
|
||||
@@ -44,7 +44,7 @@ import paths
|
||||
_lock = threading.Lock()
|
||||
|
||||
NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'value',
|
||||
'cast', 'op', 'py')
|
||||
'cast', 'op', 'py', 'custom')
|
||||
|
||||
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -762,6 +762,9 @@ NODE_DATA_IN = {
|
||||
# 最终输出只是展示,什么类型都能接(展示方式按类型不同)
|
||||
# Python 节点:上游给什么都要能收(它就是拿来处理任意内容的)
|
||||
'py': ('str', 'bool', 'num', 'list'),
|
||||
# 自定义节点:真正收什么由它声明的引脚决定(见 _data_in_type),
|
||||
# 这里给宽松值,免得还没加载到定义时就把线丢了
|
||||
'custom': ('str', 'bool', 'num', 'list'),
|
||||
'end': ('str', 'bool', 'num', 'list'),
|
||||
# 转换:什么都收,出口由 castTo 决定
|
||||
'cast': ('str', 'bool', 'num'),
|
||||
@@ -787,6 +790,7 @@ _LAST_BY_ID = {}
|
||||
_LAST_VAR_TYPE = {}
|
||||
# 纯节点求值时要能找到自己的数据入线,所以也把边表放一份在这儿
|
||||
_LAST_EDGES = []
|
||||
_LAST_CUSTOM = {}
|
||||
|
||||
|
||||
def _set_type_context(nodes: list, vars: list = None, edges: list = None) -> None:
|
||||
@@ -797,15 +801,36 @@ def _set_type_context(nodes: list, vars: list = None, edges: list = None) -> Non
|
||||
它们的值不是"执行时产生的",而是被需要的节点**拉取**时才现算的,
|
||||
现算就得能找到自己的数据入线。
|
||||
"""
|
||||
global _LAST_BY_ID, _LAST_VAR_TYPE, _LAST_EDGES
|
||||
global _LAST_BY_ID, _LAST_VAR_TYPE, _LAST_EDGES, _LAST_CUSTOM
|
||||
_LAST_BY_ID = {n['id']: n for n in nodes}
|
||||
_LAST_VAR_TYPE = {v['name']: v['type'] for v in (vars or [])}
|
||||
# 自定义节点(用户用 Python 拓展的那些):按 key 建索引。
|
||||
# 连线时要查它们声明的引脚类型 —— 不查的话自定义节点的数据线会被当成
|
||||
# "类型不认识"直接丢掉,图看着连了、一保存就没了。
|
||||
try:
|
||||
import custom_nodes as _cn
|
||||
_LAST_CUSTOM = {d['key']: d for d in _cn.list_defs() if not d.get('error')}
|
||||
except Exception: # noqa: BLE001
|
||||
_LAST_CUSTOM = {}
|
||||
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
|
||||
# ★ 自定义节点:按声明的 input 引脚类型。
|
||||
#
|
||||
# 这里是"这个节点收哪些类型"的**并集** —— 引擎的类型检查是按**节点**做的
|
||||
# (一条边上没有"接到哪个引脚"的信息),所以多入口只能放宽成并集。
|
||||
# 界面那一侧知道用户在拖哪根线,做的是**按引脚**的精确校验,
|
||||
# 所以严格程度并不会丢:接错了当场就连不上。
|
||||
if node['type'] == 'custom':
|
||||
d = _LAST_CUSTOM.get(str(node.get('customKey') or ''))
|
||||
if d:
|
||||
kinds = tuple(p['type'] for p in d.get('inputs') or []
|
||||
if p['type'] != 'exec')
|
||||
return kinds or None
|
||||
return None
|
||||
# 运算节点的两个入口,类型由算子决定(加法要数字、拼接要文本)
|
||||
if node['type'] == 'op':
|
||||
spec = _OPS_BY_KEY.get(str(node.get('op') or 'add'))
|
||||
@@ -821,6 +846,25 @@ def _data_in_type(node_id: str):
|
||||
# 不该限制**存进来**的东西:存进去的都是文本,读的时候再按类型解释。
|
||||
return NODE_DATA_IN.get(node['type'])
|
||||
def _data_out_type(node_id: str):
|
||||
"""
|
||||
这个节点"往外给"的是什么类型。
|
||||
|
||||
★ 自定义节点可能有多个数据出口,但**只有第一个能接线** ——
|
||||
边(edge)上没有"从哪个引脚出来"的信息,多个数据出口会分不清谁是谁。
|
||||
所以加载器那边会提醒"多个数据出口只有第一个能连",
|
||||
其余出口的值仍然会出现在节点卡片和运行结果里,只是接不了线。
|
||||
"""
|
||||
_n = _LAST_BY_ID.get(node_id)
|
||||
if _n is not None and _n.get('type') == 'custom':
|
||||
_d = _LAST_CUSTOM.get(str(_n.get('customKey') or ''))
|
||||
if _d:
|
||||
_outs = [p['type'] for p in _d.get('outputs') or [] if p['type'] != 'exec']
|
||||
if _outs:
|
||||
return _outs[0]
|
||||
return _data_out_type_inner(node_id)
|
||||
|
||||
|
||||
def _data_out_type_inner(node_id: str):
|
||||
node = _LAST_BY_ID.get(node_id)
|
||||
if not node:
|
||||
return None
|
||||
@@ -981,6 +1025,29 @@ def _exec_out(edges: list, node_id: str, branch: str = None) -> list:
|
||||
return [e for e in out if (e.get('branch') or 'true') == branch]
|
||||
|
||||
|
||||
def _collect_pin_input(node_id: str, edges: list, pin: dict, defn: dict,
|
||||
outputs: dict, variables: dict, by_id: dict) -> str:
|
||||
"""
|
||||
给自定义节点的某一个入口取值。
|
||||
|
||||
和 _collect_input 的区别:那个是"把所有数据入线拼成一段文本"(给智能体看的),
|
||||
这里是"按引脚取值" —— 数据线本身没有引脚信息,所以只能按**声明顺序**对:
|
||||
第 N 根数据入线 -> 第 N 个数据入口。
|
||||
这是当前数据模型的限制(边不带 fromPin/toPin),加载器会提醒用户
|
||||
"入口超过一个时,连线是按顺序对应的"。
|
||||
"""
|
||||
value = ''
|
||||
for i, e in enumerate(_data_in(edges, node_id)):
|
||||
pins = [p for p in (defn.get('inputs') or []) if p.get('type') != 'exec']
|
||||
idx = pins.index(pin) if pin in pins else 0
|
||||
if i != idx:
|
||||
continue
|
||||
v = _pure_value(e.get('from'), by_id, outputs, variables)
|
||||
if v not in (None, ''):
|
||||
value = v if isinstance(v, str) else _as_text(v, _kind(e))
|
||||
return value
|
||||
|
||||
|
||||
def _data_in(edges: list, node_id: str) -> list:
|
||||
return [e for e in _incoming(edges, node_id) if _is_data(e)]
|
||||
|
||||
@@ -1502,6 +1569,62 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
'note': f'读到 {name}' + ('' if value else '(还没设过,是空的)')})
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
elif node_type == 'custom':
|
||||
# ★ 用户用 Python 拓展出来的节点
|
||||
import custom_nodes as _cn
|
||||
d = _LAST_CUSTOM.get(str(node.get('customKey') or ''))
|
||||
if not d:
|
||||
raise ValueError(
|
||||
'这个自定义节点没找到定义(文件可能被删了或名字改了):'
|
||||
+ str(node.get('customKey')))
|
||||
# 把各个数据入口收进来(按引脚名)
|
||||
ins = {}
|
||||
for pin in d.get('inputs') or []:
|
||||
if pin['type'] == 'exec':
|
||||
continue
|
||||
ins[pin['name']] = _collect_pin_input(
|
||||
node_id, edges, pin, d, outputs, variables, by_id)
|
||||
# 没连任何入口时,退一步用 exec 上游的输出喂给**第一个**入口 ——
|
||||
# 和写变量、最终输出一个道理:用户的心智是"线连过来了",
|
||||
# 逼他必须再拉一根数据线只会让他看到空值还不知道为什么。
|
||||
if not any(str(v).strip() for v in ins.values()):
|
||||
data_pins = [p for p in (d.get('inputs') or []) if p['type'] != 'exec']
|
||||
if data_pins and 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:
|
||||
ins[data_pins[0]['name']] = ups[-1]
|
||||
logs = []
|
||||
outs, err = _cn.run_custom(d, ins, variables, node, logs)
|
||||
if err:
|
||||
emit({'type': 'node_warn', 'nodeId': node_id, 'warn': err})
|
||||
# 数据出口:第一个能接线,值取出来往下传
|
||||
dv = ''
|
||||
for pin in d.get('outputs') or []:
|
||||
if pin['type'] == 'exec':
|
||||
continue
|
||||
dv = '' if outs.get(pin['name']) is None else str(outs.get(pin['name']))
|
||||
break
|
||||
outputs[node_id] = dv
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type,
|
||||
'output': dv, 'run': run_index,
|
||||
'note': (';'.join(logs)[:120] if logs else '')})
|
||||
# ★ 多个 exec 出口 = N 路分支,规则和判断节点一致:
|
||||
# 恰好一个 True 走那条;都不 True 停在原地报警告;
|
||||
# 多个 True 报错(引擎没法替你选)
|
||||
branch_names, warn = _cn.split_execs(d, outs)
|
||||
if warn:
|
||||
emit({'type': 'node_warn', 'nodeId': node_id, 'warn': warn})
|
||||
next_ids = []
|
||||
for e in _exec_out(edges, node_id):
|
||||
b = str(e.get('branch') or '')
|
||||
pin_name = str(e.get('branch') or '')
|
||||
if not branch_names:
|
||||
break
|
||||
if pin_name in branch_names or (not b and len(branch_names) == 1):
|
||||
next_ids.append(e['to'])
|
||||
|
||||
elif node_type == 'py':
|
||||
# ★ Python 节点:跑用户自己写的那段代码
|
||||
#
|
||||
|
||||
100
nodes-示例/README.md
Normal file
100
nodes-示例/README.md
Normal file
@@ -0,0 +1,100 @@
|
||||
# 用 Python 拓展节点
|
||||
|
||||
往**内核数据目录下的 `nodes/`** 里丢一个 `.py`,会议编辑器的「加节点」面板里就多出一种节点。
|
||||
不用改 Kotlin、不用重启、不用管界面 —— 引脚是从你的声明里读出来画的。
|
||||
|
||||
数据目录在哪:会议编辑器的「加节点」面板顶部会写出来(`/api/meeting/meta` 的 `customDir`)。
|
||||
|
||||
---
|
||||
|
||||
## 最小例子
|
||||
|
||||
```python
|
||||
ToolName = {
|
||||
"name": "转大写",
|
||||
"desc": "把输入的文字转成大写",
|
||||
"input": [
|
||||
{"type": "str", "name": "文本", "value": ""},
|
||||
],
|
||||
"output": [
|
||||
{"type": "exec", "name": "好了"},
|
||||
{"type": "str", "name": "结果"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def run(ctx, node):
|
||||
node["output"]["结果"] = str(node["input"]["文本"]).upper()
|
||||
node["output"]["好了"] = True
|
||||
return node
|
||||
```
|
||||
|
||||
## 三条必须知道的规则
|
||||
|
||||
### 1. 键要加引号
|
||||
|
||||
这是 **Python**,不是 JavaScript:
|
||||
|
||||
```python
|
||||
"name": "转大写" ✅
|
||||
name: "转大写" ❌ SyntaxError
|
||||
```
|
||||
|
||||
报错会直接提示你(内核专门认了这种情况)。
|
||||
|
||||
### 2. `node["input"][名]` 拿到的是**实际值**,不是声明里的 `value`
|
||||
|
||||
声明里的 `value` 只在"这根线没接"的时候用。有线接进来,引擎会在跑之前覆盖掉。
|
||||
所以别把声明里的 `value` 当运行时的值读。
|
||||
|
||||
### 3. 多个 `exec` 出口 = **多路分支**,最多一个为 `True`
|
||||
|
||||
```python
|
||||
node["output"]["高分"] = score >= 3
|
||||
node["output"]["低分"] = score < 3
|
||||
```
|
||||
|
||||
| 情况 | 引擎怎么办 |
|
||||
|---|---|
|
||||
| 恰好一个 `True` | 走那一条,其余不执行 |
|
||||
| 一个都不 `True` | **停在原地**,并在节点上报一条警告 |
|
||||
| 超过一个 `True` | 报错(引擎没法替你选) |
|
||||
|
||||
非 `exec` 的输出(`str`/`num`/`bool`/`list`)不受这条限制,值照常沿数据线传给下游。
|
||||
|
||||
---
|
||||
|
||||
## 引脚类型
|
||||
|
||||
`input` / `output` 里每项:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `type` | `exec` / `str` / `bool` / `num` / `list` |
|
||||
| `name` | 引脚名(`run` 里按这个名字取/写) |
|
||||
| `value` | 只有 `input` 用:**没接线时的默认值** |
|
||||
|
||||
**限制**:`exec` 出口可以有多个,但**数据出口只有第一个能接线** ——
|
||||
边(连线)上没有"从哪个引脚出来"的信息。其余数据出口的值仍会出现在节点卡片上。
|
||||
|
||||
## `ctx` 提供什么
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `ctx.input` | 所有数据入口的字典(等于 `node["input"]` 的副本) |
|
||||
| `ctx.vars` | 会议变量的**只读快照** |
|
||||
| `ctx.set_var(名, 值)` | 写变量(真的写进会议变量表) |
|
||||
| `ctx.log(...)` | 记一条说明,会出现在结果界面的这一步里 |
|
||||
|
||||
## 兜底
|
||||
|
||||
- **超时 10 秒**:死循环会被掐掉,节点上报错,App 不会卡死
|
||||
- **异常**:报错显示在节点上,整场会议继续跑,不会崩
|
||||
- **加载失败**:加节点面板里会把这个节点列出来并显示原因(不会静默消失)
|
||||
|
||||
---
|
||||
|
||||
## 附带:当成智能体的工具
|
||||
|
||||
在**智能体节点**上勾选这个 Python 节点,它就变成该智能体可以调用的工具。
|
||||
工具名取节点标题,说明取 `desc`(所以 `desc` 要写清楚它干什么)。
|
||||
44
nodes-示例/score.py
Normal file
44
nodes-示例/score.py
Normal file
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
示例自定义节点:打分。
|
||||
|
||||
把这个文件复制到**内核数据目录下的 nodes/** 里,会议编辑器就会出现「打分」这种节点:
|
||||
文字长度 >= 3 走「高分」分支,否则走「低分」分支。
|
||||
(数据目录位置见「加节点」面板顶部,或 /api/meeting/meta 的 customDir。)
|
||||
|
||||
这份文件同时是**格式的活文档** —— 照着改就是你的节点。
|
||||
"""
|
||||
|
||||
ToolName = {
|
||||
"name": "打分",
|
||||
"desc": "文字越长分越高:够 3 分走「高分」,否则走「低分」",
|
||||
"input": [
|
||||
{"type": "str", "name": "文本", "value": ""},
|
||||
# 想加数字/真假/列表入口就照这个格式加:
|
||||
# {"type": "num", "name": "权重", "value": 1},
|
||||
# {"type": "list", "name": "词表", "value": []},
|
||||
],
|
||||
"output": [
|
||||
# 多个 exec 出口 = 多路分支,最多一个为 True
|
||||
{"type": "exec", "name": "高分"},
|
||||
{"type": "exec", "name": "低分"},
|
||||
# 数据出口(第一个能接线)
|
||||
{"type": "str", "name": "分数"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def run(ctx, node):
|
||||
text = str(node["input"]["文本"])
|
||||
score = len(text)
|
||||
|
||||
ctx.log("长度 =", score)
|
||||
|
||||
node["output"]["分数"] = "分数:" + str(score)
|
||||
# 多个 exec 不可同时为 1
|
||||
node["output"]["高分"] = score >= 3
|
||||
node["output"]["低分"] = score < 3
|
||||
|
||||
# 顺便写进会议变量(要在「变量」面板里先登记这个变量)
|
||||
ctx.set_var("最近分数", score)
|
||||
|
||||
return node
|
||||
@@ -1,63 +0,0 @@
|
||||
会议模式:自定义节点加载器(用户用 Python 拓展节点)—— 可行性已验证
|
||||
|
||||
用户给的方案(node.txt):
|
||||
|
||||
ToolName = {
|
||||
name:"...."
|
||||
input: [{type:"str", name:"A1", value:"..."}, ...],
|
||||
output: [{type:"exec", name:"e1"}, {type:"exec", name:"e2"}, {type:"str", name:"xx"}]
|
||||
}
|
||||
def run(ctx, node):
|
||||
ctx.log(ToolName["input"]["A1"])
|
||||
ToolName["output"]["xx"] = "666"
|
||||
ToolName["output"]["e1"] = True
|
||||
ToolName["output"]["e2"] = False
|
||||
return node
|
||||
|
||||
结论:**可行,而且比原来的方案好** —— 多个 exec 输出等于自带 N 路分支
|
||||
(内置的 judge 只有两路)。
|
||||
|
||||
实测跑通:
|
||||
B1=True → e1=True e2=False xx='HELLO 世界' 走 e1
|
||||
B1=False → e1=False e2=True xx='ABC' 走 e2
|
||||
没接 A1 → 用声明里的默认值
|
||||
|
||||
【发现并修掉的两处"写不通"】
|
||||
|
||||
① 键必须加引号。用户原版是 JS 风格 `name:"...."`,
|
||||
Python 里 `name` 会被当成变量名 → SyntaxError。
|
||||
实测报错为 "SyntaxError: invalid syntax. Perhaps you forgot a comma?",
|
||||
这句话完全看不出问题在哪,所以专门认出来并给出正确写法:
|
||||
→ 看起来有键忘了加引号(name、input、output)。这是 Python,不是 JS:
|
||||
要写 "name":、"input":、"output": …,不能写 name: …
|
||||
|
||||
② 声明是列表、访问是字典,对不上。
|
||||
声明 `input: [{type,name,value}]` 是**列表**(列表才能表达顺序和类型),
|
||||
但 run() 里写的是 `node["input"]["A1"]` —— **按名字取**。
|
||||
实测报 "TypeError: list indices must be integers or slices, not str"。
|
||||
解法:**引擎在跑之前把 input / output 换成按名字取的字典**,
|
||||
声明的列表原样留着给引擎和界面读类型。
|
||||
两边都用各自最自然的形式,中间转一次,用户不用知道。
|
||||
|
||||
【三条语义(要在文档和界面上写清楚)】
|
||||
1. node["input"][名] 是**引擎填进去的实际值**,不是声明里的 value;
|
||||
声明里的 value 只在"这根线没接"的时候用。
|
||||
2. 多个 exec 输出**最多一个 True**(这就是多路分支):
|
||||
恰好一个 → 走那条
|
||||
都不 True → **停在原地** + 报警告(不猜、不顺走第一条,猜错了查不出来)
|
||||
超过一个 → 报错(引擎没法替你选)
|
||||
非 exec 输出不受限制,照常沿数据线传。
|
||||
3. return 什么无所谓,引擎读的是 node["output"]。
|
||||
|
||||
【落地】
|
||||
新增 android/kernel/custom_nodes.py:从 <数据目录>/nodes/*.py 加载,
|
||||
规整引脚、校验类型、起子线程跑(10 秒超时,死循环不会把 App 卡死)。
|
||||
界面要用的引脚定义也在里面(inputs / outputs / label / desc),
|
||||
所以接入之后**界面能自动画出引脚**,不用在 Kotlin 里再写一份。
|
||||
|
||||
下一步:接进 meeting.py 变成一种节点类型(custom_xxx),
|
||||
并把 inputs/outputs 喂给 /api/meeting/meta 让界面自动渲染。
|
||||
|
||||
【验证】
|
||||
- custom_nodes.py 走通:加载 / 运行 / 写变量 / 记日志 / N 路分支 / 报错兜底
|
||||
- 会议引擎回归 40/40,Node 与 Python 16/16 逐用例一致
|
||||
69
tmp-msg-cn2.txt
Normal file
69
tmp-msg-cn2.txt
Normal file
@@ -0,0 +1,69 @@
|
||||
会议模式:自定义节点做完(用户的 node.txt 方案,全链路测通)
|
||||
|
||||
用户:"直接做完并测试"
|
||||
|
||||
【做了什么】
|
||||
把用户给的声明式方案落地成一种真正的节点类型:
|
||||
|
||||
ToolName = {
|
||||
"name": "打分",
|
||||
"desc": "文字越长分越高",
|
||||
"input": [{"type": "str", "name": "文本", "value": ""}],
|
||||
"output": [{"type": "exec", "name": "高分"},
|
||||
{"type": "exec", "name": "低分"},
|
||||
{"type": "str", "name": "分数"}],
|
||||
}
|
||||
def run(ctx, node):
|
||||
node["output"]["分数"] = "分数:" + str(len(node["input"]["文本"]))
|
||||
node["output"]["高分"] = len(...) >= 3
|
||||
node["output"]["低分"] = len(...) < 3
|
||||
return node
|
||||
|
||||
往 <数据目录>/nodes/ 丢一个 .py,会议里就多出一种节点。**不用改 Kotlin**。
|
||||
|
||||
【链路】
|
||||
1. custom_nodes.py:加载 / 校验 / 规整引脚 / 子线程跑(10 秒超时)
|
||||
2. meeting.py:新增 `custom` 节点类型
|
||||
- 类型上下文里加载定义(_LAST_CUSTOM),连线时查声明决定收什么类型
|
||||
- 执行分支:按引脚收输入 -> run_custom -> 取第一个数据出口往下传
|
||||
3. app.py:/api/meeting/meta 带 customNodes(含 inputs/outputs)+ customDir
|
||||
4. Kotlin:MeetingMeta.customNodes、CustomNodeDef/CustomPin、
|
||||
inputPins/outputPins 对 `custom` **从内核读引脚**、NodeCard 传 customDefs、
|
||||
加节点面板顶部列出自定义节点(带 🐍 和文件名,坏的显示原因)
|
||||
5. nodes-示例/:score.py(活文档)+ README.md(格式和三条规则)
|
||||
|
||||
【三条语义(已在 README 和节点注释里写清楚,并实测)】
|
||||
1. node["input"][名] 是**引擎填的实际值**,声明里的 value 只是"没接线时的默认"
|
||||
2. 多个 exec 出口 = **多路分支**,最多一个 True:
|
||||
恰好一个 → 走那条
|
||||
都不 True → **停在原地** + 报警告(不猜、不顺走第一条)
|
||||
多个 True → 报错
|
||||
3. return 什么无所谓,引擎读 node["output"]
|
||||
|
||||
【发现并修的坑(用户原版写不通的两处)】
|
||||
① 键必须加引号:`name:"..."` 是 JS 写法,Python 报
|
||||
"SyntaxError: invalid syntax. Perhaps you forgot a comma?" ——
|
||||
这句话完全看不出问题在哪。内核专门认出来并给出正确写法。
|
||||
② 声明是列表、访问是字典,对不上:声明 `input: [{...}]` 是列表,
|
||||
但 run 里写 `node["input"]["A1"]`(按名字取)。
|
||||
解法:**引擎在跑之前把 input/output 换成按名字取的字典**,
|
||||
声明的列表原样留给引擎和界面读类型。
|
||||
|
||||
【实测(HTTP 全链路)】
|
||||
meta: 打分 key=custom_score exec 分支=['高分','低分']
|
||||
保存后边数: 5/5(类型校验认识自定义节点的引脚)
|
||||
起点='好' → 执行 ev,sc,lo → 低分出口(分数:1)
|
||||
起点='这段文字比较长' → 执行 ev,sc,hi → 高分出口(分数:7)
|
||||
历史里也存了 results ✓
|
||||
|
||||
【限制(如实写在 README 里)】
|
||||
数据出口只有**第一个能接线** —— 边(edge)上没有"从哪个引脚出来"的信息。
|
||||
其余数据出口的值仍会显示在节点卡片上,只是接不了线。
|
||||
要修得给边加 fromPin/toPin,属于数据模型层面的改动。
|
||||
|
||||
【验证】
|
||||
- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致
|
||||
- 会议 HTTP 13/13 ×2、语音 41/41、Markdown 19/19
|
||||
- 自定义节点:加载 / 运行 / 写变量 / 记日志 / N 路分支 / 报错兜底 / 超时,
|
||||
Python 侧和 HTTP 侧各测一遍
|
||||
- APK 构建通过
|
||||
Reference in New Issue
Block a user