本文深入分析 Kimi Code CLI 中的 Flow 系统 —— 一个用于编排和执行业务流程的核心组件。它允许通过声明式流程图(D2/Mermaid)定义复杂的交互模式,实现 AI 代理的自动化工作流。
FlowNodeKind = Literal["begin", "end", "task", "decision"]
| 类型 | 说明 | 出边数 |
|---|---|---|
begin | 流程起点 | 1 |
end | 流程终点 | 0 |
task | 普通任务节点 | 1 |
decision | 决策节点 | ≥2 |
@dataclass(frozen=True, slots=True)
class FlowNode:
id: str # 节点唯一标识
label: str | list[ContentPart] # 节点标签(可作为 LLM prompt)
kind: FlowNodeKind # 节点类型
@dataclass(frozen=True, slots=True)
class FlowEdge:
src: str # 源节点 ID
dst: str # 目标节点 ID
label: str|None # 边标签(decision 分支标识)
@dataclass(slots=True)
class Flow:
nodes: dict[str, FlowNode] # 节点集合
outgoing: dict[str, list[FlowEdge]] # 出边邻接表
begin_id: str
end_id: str
Flow 系统通过 validate_flow() 函数确保流程图的完整性:
begin 和一个 endbegin 可达所有节点end 必须可从 begin 到达支持 D2 声明式图表语法:
BEGIN -> R1 -> R2
R1: "执行任务内容"
R2: "检查是否完成?"
R2 -> R2: "CONTINUE"
R2 -> END: "STOP"
特性:
|md Markdown 块标签支持 Mermaid flowchart 语法:
特性:
[文本]、(文本)、{文本} 三种形状|标签| 和 --标签--> 边标签语法async def run(self, soul: KimiSoul, args: str) -> None:
current_id = self._flow.begin_id
while True:
node = self._flow.nodes[current_id]
edges = self._flow.outgoing.get(current_id, [])
if node.kind == "end":
return # 流程结束
next_id, steps = await self._execute_flow_node(soul, node, edges)
current_id = next_id
| 节点类型 | 执行方式 |
|---|---|
task | 执行 label 作为 prompt,完成后自动走唯一出边 |
decision | 执行 label 作为 prompt,等待 LLM 返回 <choice>标签</choice> 选择分支 |
_CHOICE_RE = re.compile(r"<choice>([^<]*)</choice>")
def parse_choice(text: str) -> str | None:
matches = _CHOICE_RE.findall(text or "")
return matches[-1].strip() if matches else None
Ralph Loop 是一种特殊的自动化流程,用于无人值守任务:
流程: BEGIN → R1(task) → R2(decision) --CONTINUE--> R2
\--STOP--> END
使用场景:
R2 节点通过决策判断任务是否完成,未完成则循环回自身继续执行。
Flow 通过 Skill 系统暴露给用户:
# skill.yaml
name: my-flow
type: flow
description: 我的自动化流程
flow:
format: d2 # 或 mermaid
content: |
BEGIN -> task1 -> decision1
task1: "执行任务1"
decision1: "继续吗?"
decision1 -> task1: "YES"
decision1 -> END: "NO"
注册后可通过 /flow:my-flow 命令调用。
src/kimi_cli/skill/flow/__init__.py # 核心数据结构
src/kimi_cli/skill/flow/d2.py # D2 解析器
src/kimi_cli/skill/flow/mermaid.py # Mermaid 解析器
src/kimi_cli/soul/kimisoul.py # FlowRunner 执行引擎
分析基于 kimi-cli 最新源码,使用 sg_sag.php RAG 记忆管理系统辅助检索
还没有人回复