Eino 图编排实战:分支、循环与人机协同中断恢复(Go 实现)
引言:Chain 不够用时,就该上图了
第 6 篇《Eino 入门:构建你的第一个 Chain》里我们学到:Chain 是「一段固定顺序的步骤」,输入输出类型在创建时定死,运行时按顺序执行。但真实业务几乎从不长这样——你可能需要「根据模型返回的路由决定走哪条分支」「失败时重试直到通过」「跑到一半暂停,等人类确认后再继续」。
这三种诉求,Chain 都表达不了,因为它们要么有分支、要么有环、要么要暂停。这正是 Graph 出场的地方:Eino 的 Graph 是一张有向图,节点之间用边连接,还能挂上「分支」(Branch)根据运行时数据动态决定下一步,甚至能形成环做循环。
本篇把 Graph 的三板斧一次性讲透:
| 能力 | 对应机制 | 本文小节 |
|---|---|---|
| 分支 | AddBranch + NewGraphBranch |
第三节 |
| 循环 | 环图 + WithMaxRunSteps 防死循环 |
第四节 |
| 中断恢复 | Interrupt / StatefulInterrupt + Resume |
第五节 |
读完这篇,你就掌握了 Eino 编排层最核心、也最难的那 20%——剩下 80% 的日常需求用 Chain 和普通 Graph 就能覆盖。
一、Graph 与 Chain 的关系:先建立一个心智模型
很多人以为 Graph 和 Chain 是两套东西。其实不是——Chain 就是 Graph 的一个特例:一张只有两个节点、一条边的图。看 Eino 源码 compose/chain.go 里 NewChain 的实现,它内部就是调用 NewGraph 并 AppendChatTemplate().AppendChatModel() 之后 AddEdge 连起来再 Compile。
所以之前学的 NewChain[I, O]() 的泛型思维、Compile 后得到 Runnable、Invoke/Stream 的调用方式,全部平移到 Graph 上,只是把「链式 Append」换成了「显式 AddNode + AddEdge」。
两者的选型原则也很简单:
- 步骤固定、一条道走到黑 → 用
Chain,代码更短。 - 有分支 / 有循环 / 要暂停 / 节点成网 → 用
Graph。
二、环境准备:Graph 的最小骨架
依赖与第 6 篇完全一致,直接复用:
package main
import (
"context"
"fmt"
"os"
"github.com/cloudwego/eino-ext/components/model/openai"
)
func main() {
ctx := context.Background()
chatModel, err := openai.NewChatModel(ctx, &openai.ChatModelConfig{
Model: "gpt-4o-mini", // 换成你服务商可用的模型名
APIKey: os.Getenv("OPENAI_API_KEY"),
})
if err != nil {
panic(err)
}
_ = chatModel
fmt.Println("环境就绪")
}
安装命令(版本号以文末「版本说明」为准):
go get github.com/cloudwego/eino@v0.9.23
go get github.com/cloudwego/eino-ext/components/model/openai@v0.1.13
Graph 的最小骨架长这样,注意和 Chain 的关键区别——节点要先 Add*Node 注册,再 AddEdge 连边:
import "github.com/cloudwego/eino/compose"
// 声明图:输入 string,输出 string
graph := compose.NewGraph[string, string]()
// 注册节点(这里用一个 passthrough 节点占位,实际可换成 ChatModel/Lambda)
graph.AddLambdaNode("node_a", compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
return "A:" + in, nil
}))
graph.AddLambdaNode("node_b", compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
return "B:" + in, nil
}))
// 连边:START -> a -> b -> END
_ = graph.AddEdge(compose.START, "node_a")
_ = graph.AddEdge("node_a", "node_b")
_ = graph.AddEdge("node_b", compose.END)
// 编译成 Runnable
runnable, err := graph.Compile(ctx)
if err != nil {
panic(err)
}
// 运行
out, err := runnable.Invoke(ctx, "hello")
if err != nil {
panic(err)
}
fmt.Println(out) // 输出:B:A:hello
几个要点先记住,后面每一节都会用到:
compose.START/compose.END是内置常量(值分别为"start"/"end"),用来表示图的入口和出口。第一段边从START出发,最后一段边收束到END。- 类型逐跳检查:
AddEdge时上一节点输出类型必须等于下一节点输入类型,对不上会在Compile时报错。上例三个节点都是string -> string,天然对齐。 InvokableLambda把普通函数包装成可调用的 Lambda 节点,签名是func(ctx, in) (out, error)。
三、分支:根据模型输出动态路由
分支(Branch)是 Graph 最常用的能力。典型场景:让模型先判断用户意图,再根据意图走不同处理节点。
AddBranch 的签名是 AddBranch(startNode string, branch *GraphBranch),其中 GraphBranch 用 NewGraphBranch 构造,它的条件函数签名是:
type GraphBranchCondition[T any] func(ctx context.Context, in T) (endNode string, err error)
也就是说:条件函数吃一个输入,吐一个「下一个节点的名字」。完整示例如下,我们把「客服咨询」按情绪路由到「表扬」和「投诉」两条处理支线:
graph := compose.NewGraph[string, string]()
// 分类节点:模拟「判断情绪」,实际可换成 ChatModel
classifier := compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
if contains(in, []string{"烂", "退款", "投诉"}) {
return "negative", nil
}
return "positive", nil
})
// 两条支线的处理节点
praise := compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
return "感谢您的认可!", nil
})
complaint := compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
return "已为您转接人工,稍后专员联系您。", nil
})
graph.AddLambdaNode("classifier", classifier)
graph.AddLambdaNode("praise", praise)
graph.AddLambdaNode("complaint", complaint)
// 关键:分支条件,返回下一步的节点名
branch := compose.NewGraphBranch(func(ctx context.Context, in string) (string, error) {
return in, nil // in 就是 classifier 输出的 "positive"/"negative"
}, map[string]bool{
"praise": true,
"complaint": true,
})
_ = graph.AddEdge(compose.START, "classifier")
_ = graph.AddBranch("classifier", branch) // 分支替代了 classifier 的出边
_ = graph.AddEdge("praise", compose.END)
_ = graph.AddEdge("complaint", compose.END)
runnable, err := graph.Compile(ctx)
// ... 运行 runnable.Invoke(ctx, "这产品真烂,我要退款") 会走 complaint 支线
三个容易踩的坑,务必注意:
endNodesmap 必须声明所有可能的下游节点。上面map[string]bool{"praise": true, "complaint": true}漏一个,运行时条件函数一旦返回了未声明的节点名,会直接报错branch invocation returns unintended end node。- 分支的出边不用再
AddEdge。AddBranch已经隐含了「从 classifier 出去的路由」,再手动AddEdge("classifier", "praise")反而会重复。分支的下游节点(praise/complaint)之间无需连边,它们各自连到END或下一步即可。 NewGraphBranch的条件函数输入类型 = 起点节点的输出类型。classifier 输出string,条件函数就写in string;如果换成 ChatModel 节点,输入就是[]*schema.Message。
如果一次要路由到多个下游节点(扇出),用 compose.NewGraphMultiBranch,条件函数返回 map[string]bool。分支还可用于流式场景(NewStreamGraphBranch),这里不展开。
四、循环:环图 + 重试上限
Graph 支持成环(Eino 称之为 Pregel 运行模式),这就能做「循环重试」:生成节点输出不合格 → 回退到生成节点再来一遍,直到合格或超过上限。
直接看一个「文案生成直到通过校验」的例子:
graph := compose.NewGraph[string, string]()
generator := compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
// 简化:模拟生成结果,实际可换成 ChatModel
return in + "#draft", nil
})
validator := compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
if len(in) > 20 { // 长度够了就算通过
return "PASS", nil
}
return "RETRY", nil
})
graph.AddLambdaNode("generator", generator)
graph.AddLambdaNode("validator", validator)
_ = graph.AddEdge(compose.START, "generator")
_ = graph.AddEdge("generator", "validator")
// 环:validator 不通过时回到 generator
loopBranch := compose.NewGraphBranch(func(ctx context.Context, in string) (string, error) {
if in == "PASS" {
return compose.END, nil
}
return "generator", nil
}, map[string]bool{
"generator": true,
compose.END: true,
})
_ = graph.AddBranch("validator", loopBranch)
// 关键:设置最大步数,防止死循环
runnable, err := graph.Compile(ctx, compose.WithMaxRunSteps(20))
if err != nil {
panic(err)
}
循环图的两个保命要点:
- 必须配
WithMaxRunSteps。带环的图一旦条件永远不满足就会无限跑下去,WithMaxRunSteps(20)会在步数超限时终止并返回错误。源码里对非 DAG 图(即 Pregel 模式)若没设该值,会默认用节点数 + 10,但显式设置更可控、意图更清晰。 - 回边指向已存在的节点。上面
return "generator"之所以合法,是因为generator节点已经注册过——环的本质就是「一条指回上游节点的边」。
补充:Eino 的图默认是 Pregel 模式(
AnyPredecessor触发),支持成环;若你的图严格无环,可显式指定WithNodeTriggerMode(compose.AllPredecessor)走 DAG 模式,后者会做无环校验。日常循环需求用默认模式即可。
五、人机协同:中断、人工介入、恢复
这是 Graph 相比 Chain 最「进阶」的能力,也是 Agent 落地的关键一环:让流程跑到某个节点时暂停,把中间结果交给人类审核,人类确认后再从断点继续。
Eino 提供了完整的「中断—恢复」机制,核心 API 如下(均已随 v0.9.23 源码核对):
| API | 作用 |
|---|---|
compose.Interrupt(ctx, info) |
在自定义节点里主动触发中断,暂停整条图 |
compose.StatefulInterrupt(ctx, info, state) |
同上,但额外把内部状态写入 checkpoint,恢复时能取回 |
compose.WithInterruptBeforeNodes([]string{...}) |
编译选项:在指定节点之前自动中断 |
compose.WithInterruptAfterNodes([]string{...}) |
编译选项:在指定节点之后自动中断 |
compose.Resume(ctx, interruptIDs...) |
基于已保存的 checkpoint 恢复运行 |
compose.ResumeWithData(ctx, interruptID, data) |
恢复时把额外数据(如人工审核结果)注入被中断节点 |
compose.GetResumeContext[T](ctx) |
在被中断节点内读取恢复时注入的数据 |
最常用的业务形态是「审核节点 + 人工确认」:先看一个带状态中断的最小可运行示例。
graph := compose.NewGraph[string, string]()
// 审核节点:把内容存进 checkpoint 后中断,等待人工
reviewNode := compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
// 中断并把待审内容写入状态,恢复时通过 GetInterruptState 取回
return "", compose.StatefulInterrupt(ctx, "需要人工审核", in)
})
graph.AddLambdaNode("review", reviewNode)
graph.AddLambdaNode("publish", compose.InvokableLambda(func(ctx context.Context, in string) (string, error) {
return "已发布:" + in, nil
}))
_ = graph.AddEdge(compose.START, "review")
_ = graph.AddEdge("review", "publish")
_ = graph.AddEdge("publish", compose.END)
runnable, err := graph.Compile(ctx)
if err != nil {
panic(err)
}
// 第一次运行:会在 review 节点中断
_, err = runnable.Invoke(ctx, "一篇待审核的文章")
if err != nil {
// 判断是否为中断错误
if _, ok := compose.ExtractInterruptInfo(err); ok {
fmt.Println("已暂停,等待人工审核")
}
}
中断触发后,图会停在 review 节点,并把 checkpoint(含中断信息)写入 CheckPointStore。要恢复运行,需要两个额外编译选项和一个恢复调用:
// 编译时挂上 checkpoint 存储,并声明哪些节点会中断
runnable, err = graph.Compile(ctx,
compose.WithCheckPointStore(store), // store 需实现 core.CheckPointStore 接口
compose.WithSerializer(&jsonSerializer{}),
compose.WithInterruptBeforeNodes([]string{"review"}),
)
// 人工审核通过后,携带审核结论恢复
ctx2 := compose.Resume(ctx, interruptID) // interruptID 来自中断信息
out, err := runnable.Invoke(ctx2, "一篇待审核的文章")
这套机制的精髓在于:checkpoint 把「图跑到哪、状态是什么」完整落盘,恢复时不用重头再来,从断点继续即可。这在客服工单、内容审核、财务审批等「必须人工把关」的场景里是刚需——也是 Agent 从「全自动」走向「可信可控」的桥梁。
说明:
CheckPointStore与Serializer需要你自行实现或选用社区实现(Eino 内置了内存版inMemoryStore与 JSON 序列化供测试,生产环境建议落盘到 Redis/MySQL)。因篇幅所限,完整的中断恢复端到端代码会放在系列后面的《Agent 记忆与状态持久化》一篇展开,这里先建立「Interrupt 暂停 → checkpoint 落盘 → Resume 恢复」的完整心智模型。
六、速查清单:Chain vs Graph
| 维度 | Chain | Graph |
|---|---|---|
| 结构 | 固定顺序的线性序列 | 任意有向图,可成环 |
| 分支 | 不支持 | AddBranch / NewGraphBranch |
| 循环 | 不支持 | 环图 + WithMaxRunSteps |
| 中断恢复 | 不支持 | Interrupt + Resume + checkpoint |
| 创建 | NewChain[I, O]() 链式 Append |
NewGraph[I, O]() + AddNode + AddEdge |
| 典型场景 | 拼提示词 → 调模型 → 格式化 | 多路由客服、循环生成、人工审核流 |
一句话记忆:能 Chain 就 Chain,要分支/循环/暂停就 Graph。
版本说明
本文代码 API 均于 2026-11-17 逐字核对自官方源码与发布页,安装请以下列版本为准:
| 依赖 | 版本 | 安装命令 |
|---|---|---|
| eino | v0.9.23(2026-11-09 发布,官方 releases 页核实) | go get github.com/cloudwego/eino@v0.9.23 |
| eino-ext OpenAI 组件 | v0.1.13(官方 tags 页核实,components/model/openai/v0.1.13) |
go get github.com/cloudwego/eino-ext/components/model/openai@v0.1.13 |
官方文档:cloudwego.io/docs/eino;源码核对仓库:github.com/cloudwego/eino(compose/generic_graph.go、compose/graph.go、compose/branch.go、compose/interrupt.go、compose/resume.go、compose/state.go、compose/checkpoint.go、compose/graph_compile_options.go)。文中 NewGraph / AddEdge / AddBranch / NewGraphBranch / NewGraphMultiBranch / Compile / WithMaxRunSteps / WithGenLocalState / WithInterruptBeforeNodes / WithInterruptAfterNodes / Interrupt / StatefulInterrupt / Resume / ResumeWithData / GetInterruptState / GetResumeContext / WithCheckPointStore / WithSerializer 等 API 签名均抄录自上述源码,compose.START / compose.END 常量值分别为 "start" / "end"。
本文是「Go AI 应用开发」系列第 7 篇(共 18 篇规划),阶段二「Go AI 框架」第三篇。上一篇:《Eino 入门:构建你的第一个 Chain》;系列前篇:《大模型 API 基础》、《Function Calling 教程》、《Embedding 与语义检索》、《SSE 流式输出教程》、《Go AI 框架选型横评》。下一篇预告:《结构化输出:Go 泛型 + JSON Schema 的类型安全之道》。
- 《Go 程序设计语言》(Go 语言圣经,机械工业出版社) —— Go 官方团队出品,公认入门第一书
- 《Go 语言实战》(异步图书,人民邮电出版社) —— 实战导向,面试前巩固工程手感
- 《Go 语言编程之旅:一起用 Go 做项目》(博文视点,电子工业出版社) —— 项目驱动入门,从零写出完整应用
- Keychron K1Max 矮轴机械键盘(Mac/Win 双系统,QMK/VIA 开源改键) —— 轻薄矮轴 + 开源固件,程序员桌面常客
- 罗技 MX Master 3S 无线鼠标(Flow 跨屏,静音电磁滚轮) —— 人体工学设计,写代码一整天手不酸
以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。
每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。
微信扫码,或搜索「Go2AI之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。