GenFlow 智能体架构
大模型驱动产品,确定的 API 变成概率的返回,这将是产品演化的趋势
# AI 产品概述
# 熵增
ToC 产品和技术是两回事,既不割裂也不强相关,好的技术不一定产出好的产品,好的产品也不一定依赖绝对好的技术,技术达标 + 用户体验 = 好的产品
相应的,如果用户体验不行,这个产品总是不能称之为好,除非有垄断的技术领先
以 toC 的文档服务为例,传统的文库,无非提供存储、下载、搜索等服务,然后通过“卖文档”实现盈利,这之中有两个关键问题
- 搜索质量:用户是否需要动用大量精力才能搜到想要的内容
- 文档质量:用户找到的文档是否值得花钱购买
这类产品的核心竞争力,说白了就是用户能否从你的文档库获到值得付费的文档内容
但在 AI 时代,搜索的门槛被拉的很低,只需要用一个文本框,一个 query,大模型就能给出一大堆回答,这里不得不考虑一个问题,用户是否还会为“人工搜索、手动筛查、付费下载”这套逻辑买单? —— 2025 百度的广告收益下降 16 个点
如何立足于“存储”发扬 AI 功能,是 PSIG 是否能存活并增长的核心,这里有两个发展方向,一个是依靠存储发展个性化的 AI(例如提供个体 AI 如 OpenClaw 的记忆服务),一个是依靠存储发展 toB 的 AI 服务(类似于 Saas,但这一套似乎并不奏效),随着智能体的发展,用户 PC 端的使用量显著上升,甚至超过疫情时期的下载量,这充分说明当前 AI 对用户使用习惯的改变,显然电脑更适合与 AI 交互,以将算力转化为可以看得见的生产力,依据云存储提供个性化的 AI 记忆服务是一个很好的点子
耦合 AI 底座和业务逻辑
- 通过 MCP 将复杂的业务处理能力提供给智能体,智能体通过策略分发找到对应的 MCP 工具,实现一次处理并返回用户,这里是一个嵌套的功能,业务逻辑需要 AI 功能来实现,上层的智能体调用 MCP 获取业务逻辑,实现 AI - Service - AI 的架构
- 也就是说,现在与用户交互的不再是死板的接口,而是一个个智能体,智能体通过预设的 prompt 调用相应的 MCP 获取具体的业务操作,并返回给用户;也可以理解为,从前的 routes 路由实现的业务分发,被智能体调用 MCP 的方式取代了,当然,调用智能体仍然使用某一接口如 /chat 触发
# 自我进化
Robin 看来,「AI能做事只是第一步;能不能判断自己有没有把事情做好,才是效率真正被打开的关键」,如果 AI 验证没做好的话,AI 就会重新迭代、优化,这就形成了一个闭环。这个闭环中如果几乎没有人干预,效率就会很高。目前,已经有伐谋这类工具,基于这个“闭环”的思路帮助许多企业提效,但在更多的场景下,由于目前的工具还不足够成熟,仍然需要依赖人脑来构建这样的闭环,并想办法让 AI 能够验证自己的工作做得好还是不好
再次重申,上次提过的「希望业务不要训模型,业务训模型是一个熵增的过程」,原因首先是资源层面的。训练模型本身非常耗费算力,而当前行业整体算力依然紧张,卡资源十分珍贵。如果各条业务线都分散去训练自己的模型,不仅投入巨大,也会削弱整体竞争力。而且模型的评估是个很难很复杂的事儿,业务团队往往并不擅长对模型做全面、准确和长期有效的评估。有可能自己训了一个模型短期看效果不错,但实际上再过一个月就会发现效果并没有那么好
更关键的是,这样被训出来的模型,极易被基础模型的升级能力所覆盖。这样的结果,就是团队陷入“训一轮、追一轮、再训一轮”的恶性循环,最后做了很多无用功。相比之下,业务更应把精力投入到产品和应用层面,把模型能力真正转化为用户价值和业务结果
2B、2C 和 2P,这次他又做了一轮澄清
- 2B 是企业付费
- 2C 单指靠广告赚钱的模式
- 2P 指的是个人付费
Robin 还跟大家传递了一个理念,希望「用 coding 解决所有的问题」。目前普遍的做法还是“机做人审” —— 让 AI 去做事,人来把关、做一些必要环节的 check;再往后的趋势,很可能就是“不允许人 coding”了,这个观点虽然现在听起来比较激进,但如果类比很多其他领域,就会发现在很多事儿机器来做更加精确,并不是人的长项
# Genflow 产品架构
# GF 三层架构
模型驱动三层架构
- Genflow:与用户直接交互,实现工作流编排
- MCP:为 Genflow 提供具体业务能力
- Strategy:提供例如转码、存储和 AI 等策略接口
文库、橙篇、自由画布场景下 AI 助手对话流程
- 用户输入指令
- 意图识别、风控
- 策略分发
- 业务逻辑
- 返回 SSE 流
以 Genflow 根据用户文档生成 PPT 流程为例,GF 的一次调用过程如下
用户输入
↓
调用 /convertparsesubmit 和 /convertparsesubmit 上传并解析文件 bdjson 至 BOS
↓
调用 /filecreate 拿取 BOS 文件并绑定本次对话 queryID 和 chatID
↓
调用 /chat 接口,分析用户请求,打向统一的 MCP 调度服务,由该服务返回需要使用到的工具 toolName,而后再去找 function 模块,请求对应的 MCP 服务
↓
具体的 MCP 工具实现依赖于下层的策略服务,也就是说,MCP 服务的核心功能是依靠打下层策略实现的,而后同步返回 Genflow
↓
策略接口
2
3
4
5
6
7
8
9
10
11
整个链路中,真正的业务逻辑在 function 层实现,GenFlow 上游进行意图识别,下游策略为 function 提供真正的业务能力,同时在状态流转时插入风控、商业化等前置 / 后置服务,构成完整的生 PPT 链路
在整个 GenFlow 架构下,后端被分为三层
- 基础:提供底层转码、AI 对话流、文档解析等服务
- 业务:负责组装基础的服务,实现真正的业务逻辑
- 策略:复制工作流设计、策略分发、业务调用等
# MCP Function
function 库,为 GenFlow 提供内置的 MCP 工具,作为实际业务的承担层
GenFlow 上层收到用户请求后,会经过网盘那边的意图识别和策略分发,打到 MCP 模块,即 function 库中的内容,很有意思的链路,MCP 数据通过 Json 协议传输
PPT 相关工具
| 工具文件 | 功能描述 |
|---|---|
pptagent.go | 处理 HTML PPT 生成流程 |
agentppt.go | Agent PPT 生成工具 |
agentpptbase.go | Agent PPT 基础功能 |
agentpptoutline.go | Agent PPT 大纲生成 |
makeppt.go | 传统 PPT 生成工具 |
makepptoutline.go | 传统 PPT 大纲生成工具 |
makehtmlppt.go | HTML 格式 PPT 生成 |
ppteditor.go | PPT 编辑功能 |
pptgenappbuilder.go | 应用构建器 PPT 生成 |
pptgenmultiquery.go | 多查询 PPT 生成 |
Word 文档工具
| 工具文件 | 功能描述 |
|---|---|
wordgen.go | Word 文档生成工具(已废弃) |
wordgenv2.go | Word 生成工具 V2 版本 |
wordedit.go | Word 文档编辑工具 |
wordoutline.go | Word 大纲生成工具(已废弃) |
wordoutlinev2.go | Word 大纲生成 V2 版本 |
Excel 表格工具
| 工具文件 | 功能描述 |
|---|---|
excelagentv2.go | Excel Agent V2 工具,支持表格生成和编辑 |
exceledit.go | Excel 编辑工具 |
图片生成工具
| 工具文件 | 功能描述 |
|---|---|
imagegen.go | 图片生成工具 |
multiimagegen.go | 多图片生成工具 |
imggenwp.go | 文链文生图工具 |
imgunderstand.go | 图片理解/识别工具 |
generateposter.go | 海报生成工具 |
generateposterlist.go | 海报列表生成工具 |
generatehandcopy.go | 手抄报生成工具 |
搜索工具
| 工具文件 | 功能描述 |
|---|---|
websearch.go | 网络搜索工具 |
browsesearch.go | 浏览器搜索工具 |
getsearch.go | 搜索获取工具 |
xueshusearch.go | 学术搜索工具 |
knowledgesearch.go | 知识库搜索工具 |
knowledgedata.go | 知识库数据获取工具 |
wangpansearch.go | 网盘搜索工具 |
fileretrieval.go | 文件检索工具 |
searchfile.go | 文件搜索工具 |
文档处理工具
| 工具文件 | 功能描述 |
|---|---|
basedoc.go | 基础文档处理 |
getfileinfo.go | 获取文件信息 |
parse.go | 文档解析工具 |
convert.go | 文档转换工具 |
makedoc.go | 文档创建工具 |
研报生成工具
| 工具文件 | 功能描述 |
|---|---|
reportgen.go | 研报生成工具 |
report_generate.go | 研报生成(新版本) |
reportgenoutline.go | 研报大纲生成工具 |
report_h5.go | 研报 H5 页面生成 |
图表绘制工具
| 工具文件 | 功能描述 |
|---|---|
make_frame_chart.go | 框架图/流程图生成 |
make_mindmap_chart.go | 思维导图生成 |
datachart.go | 数据图表生成 |
多媒体工具
| 工具文件 | 功能描述 |
|---|---|
videogen.go | 视频生成工具 |
podcastgen.go | 播客生成工具 |
storymediagenerate.go | 故事媒体生成工具 |
storymediaoutline.go | 故事媒体大纲生成 |
其他工具
| 工具文件 | 功能描述 |
|---|---|
uploadfile.go | 文件上传工具 |
memorysearch.go | 记忆搜索工具 |
memoryrecord.go | 记忆记录工具 |
cronjob.go | 定时任务工具 |
codegen.go | 代码生成工具 |
接口入口
| 工具文件 | 功能描述 |
|---|---|
base.go | MCP 基础服务,定义接口、常量、通用方法 |
这些工具涵盖了内容生成(PPT、Word、Excel、研报)、搜索检索、图片视频生成、文档处理等多个领域,为 GenFlow 提供一个完整的 AIGC 工具生态链
LLM 的文档处理本质上是还是在处理文本,通过转码倒推生成文档
# GenFlow 状态机
通过事件驱动状态机实现 PPT 生成流程,这是 makeppt 的上层 genflow 的“管控”工作,利用 Golang 库 FSM 实现 PPT 状态流转的有向无环图
- looplab/fsm: Finite State Machine for Go (opens new window)
- fsm package - github.com/looplab/fsm - Go Packages (opens new window)
- Go 每日一库之 134:fsm 基有限状态机库 (opens new window)
在状态机模型内,我们不需要在业务代理判断状态,而只定义规则,关注点完全在
- 源状态(source)
- 事件(event)
- 目标状态(target)
不符合规则状态转移路径由状态机引擎自动拦截
fsm.go
# 定义状态和事件
const (
StatePauseToolAck = "tool_ack" //工具确认
maxRound = 20 // 最多执行20轮调用
)
const (
FsmStateInit = "init" // 初始化阶段
FsmStateQueue = "queue" // 队列中
FsmStateModleChoice = "model_choice" // 模式选择
FsmStateReason = "reason" // 推理模型
FsmStateRoundDispatch = "round_dispatch" // 轮数调度状态
FsmStateExecute = "execute" // 调度模型
FsmStateChat = "chat" // 对话模型输出
FsmStatePause = "pause" // 暂停模型
FsmStateResume = "resume" // 状态恢复
FsmStateCancel = "cancel" // 状态取消
FsmStateError = "error" // 出现异常
FsmStateTimeout = "timeout" // timeout
FsmStateSingleMessage = "single_message" // 单意图模式输出message
FsmStateCompleted = "completed"
)
const (
FsmEventInit = "init" // 初始化事件
FsmEventSimpleJudge = "simple_judge" // 工具判断
FsmEventModelChoice = "model_choice" // 选择模式
FsmEventReason = "reason" // 推理模型事件
FsmEventRoundDispatch = "round_dispatch" // 对话调度
FsmEventExecute = "execute" // 调度事件
FsmEventCancel = "cancel" // 任务取消
FsmEventChat = "chat" // 对话事件
FsmEventPause = "pause" // 暂停事件
FsmEventError = "error" // 出现异常
FsmEventTimeout = "timeout" // timeout
FsmEventCompleted = "completed" // 结束
FsmEventSingleMessage = "single_message" // 单意图模式输出message
)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 状态机流转与回调
初始化状态机,定义状态机调度流转逻辑
// 初始化状态机
func (g *genflow) initFsm() {
g.fsmClient = fsm.NewFSM(
FsmStateInit,
fsm.Events{
{Name: FsmEventInit, Src: []string{FsmStateInit}, Dst: FsmStateQueue}, // 初始化阶段
{Name: FsmEventModelChoice, Src: []string{FsmStateQueue, FsmStateExecute, FsmStateReason, FsmStateRoundDispatch}, Dst: FsmStateModleChoice}, // 选择工具事件
{Name: FsmEventReason, Src: []string{FsmStateModleChoice}, Dst: FsmStateReason}, // 执行思考模型事件
{Name: FsmEventRoundDispatch, Src: []string{FsmStateReason, FsmStateExecute, FsmStatePause}, Dst: FsmStateRoundDispatch}, // 工具调度
{Name: FsmEventExecute, Src: []string{FsmStateReason, FsmStateModleChoice, FsmStateRoundDispatch}, Dst: FsmStateExecute}, // 调度事件
{Name: FsmEventSingleMessage, Src: []string{FsmStateExecute, FsmStatePause}, Dst: FsmStateSingleMessage}, // 单意图输出message
{Name: FsmEventChat, Src: []string{FsmStateModleChoice, FsmStateExecute, FsmStateRoundDispatch, FsmStatePause}, Dst: FsmStateChat}, // 对话事件
{Name: FsmEventCancel, Src: []string{
FsmStateExecute,
FsmStateModleChoice,
FsmStateReason,
FsmStateChat,
FsmStateRoundDispatch,
}, Dst: FsmStateCancel}, // 取消事件
{Name: FsmEventTimeout, Src: []string{
FsmStateExecute,
FsmStateModleChoice,
FsmStateReason,
FsmStateChat,
FsmStateRoundDispatch,
}, Dst: FsmStateTimeout}, // 超时事件
{Name: FsmEventCompleted, Src: []string{FsmEventInit, FsmEventCancel, FsmStateChat, FsmStateExecute, FsmStateSingleMessage}, Dst: FsmStateCompleted}, // 完成事件
{Name: FsmEventError, Src: []string{FsmStateExecute,
FsmStateModleChoice,
FsmStateReason,
FsmStateChat,
FsmStateRoundDispatch,
FsmStateSingleMessage},
Dst: FsmStateError,
},
},
fsm.Callbacks{
// 进入queue状态
fmt.Sprintf("enter_%s", FsmStateQueue): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
g.queued()
<-g.initCompleteCh
go safely.RunVoidContext(g.ctx, func() {
g.SaveLongTermMemory(g.ctx)
})
},
fmt.Sprintf("before_%s", FsmStateInit): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
// 先判断是否存在临时记忆,如果存在,则从临时记忆输出
// useTempMemory := false // todo 控制是否使用临时记忆
// if !useTempMemory {
// return
// }
g.hasMemory = g.OutputFromRedis()
if g.hasMemory { // 直接返回
g.memoryEnd <- true
// _ = g.fsmClient.Event(g.ctx, FsmEventCompleted)
} else {
// 风控处理
go safely.RunVoidContext(g.ctx, g.risk)
// 初始化取消逻辑
go g.judgeHitCancel()
go safely.RunVoidContext(g.ctx, func() {
g.pauseMonitor(g.ctx)
})
}
},
fmt.Sprintf("after_%s", FsmEventInit): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
// 进入选择工具的事件
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventModelChoice)
},
"leave_state": func(ctx context.Context, event *fsm.Event) {
// resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
resource.LoggerService().Notice(ctx, "leave_state", logit.AutoField("event", event))
// fmt.Printf("leave_state: %s, %s", event.Src, event.Dst)
},
// 进行工具选择状态
fmt.Sprintf("enter_%s", FsmStateModleChoice): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
// 选择工具
var streategyInfo genflowtypes.ToolChoicesResponse
// 添加中间预处理的逻辑
hasPreProcess := g.preProcess()
if hasPreProcess {
streategyInfo.ModelType = g.information.Base.ModelType
} else {
streategyInfo = g.modelToolChoices()
}
g.businessDetection(g.ctx, []openai.ChatCompletionMessageToolCall{}, "chat")
if g.isPauseFlag {
select {
case <-ctx.Done():
resource.LoggerService().Notice(ctx, "fsm continue signal ctx done")
break
case <-g.continueSignalCh:
resource.LoggerService().Notice(ctx, "get continue signal")
time.Sleep(100 * time.Millisecond)
break
case <-g.continueWithChoiceCh:
resource.LoggerService().Notice(ctx, "cancel_end_flag")
time.Sleep(100 * time.Millisecond)
return
case <-g.continueWithDispatCh:
resource.LoggerService().Notice(ctx, "cancel_end_flag")
time.Sleep(100 * time.Millisecond)
return
}
}
if streategyInfo.ModelType == 0 {
if err := util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventError, gerror.ErrorCodeModelError, "model_choice error"); err != nil {
resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
}
return
}
if g.information.Base.IsSimple {
// if err := g.fsmClient.Event(g.ctx, FsmEventChat); err != nil {
// resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
// }
//fsm panic处理
if err := util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventChat); err != nil {
resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
}
} else if g.information.Base.ModelType == modelTypeSingle {
// g.toolChoiceResponse.Scene = ScenePcSearch
if g.hitsFullSingleOutput() {
g.outputThoughts(openai.ChatCompletionMessage{Content: ""}, EventThoughtsReason, 1, 0)
// 输出前端
outinfo := g.initOutputBase(StatusPlanning, EventToolPlanning, "planning tools")
outinfo.Details = &outputDetails{
Type: EventToolPlanning,
RunObject: map[string]any{},
}
g.send(outinfo)
}
// if err := g.fsmClient.Event(g.ctx, FsmEventExecute); err != nil {
// resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
// }
if err := util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventExecute); err != nil {
resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
}
} else {
// if err := g.fsmClient.Event(g.ctx, FsmEventReason, streategyInfo); err != nil {
// resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
// }
if err := util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventReason, streategyInfo); err != nil {
resource.LoggerService().Warning(g.ctx, "fsm error", logit.Error("err", err))
}
}
// 进入模式判断的事件
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventSimpleJudge)
},
fmt.Sprintf("enter_%s", FsmStateReason): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
if len(event.Args) == 0 {
resource.LoggerService().Warning(ctx, "param not found")
// 没有找到工具,进行工具选择事件
//_ = g.fsmClient.Event(g.ctx, FsmEventModelChoice)
//fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventModelChoice)
}
strategyInfo := event.Args[0].(genflowtypes.ToolChoicesResponse)
g.modelReason(strategyInfo)
if g.isPauseFlag {
select {
case <-ctx.Done():
resource.LoggerService().Notice(ctx, "fsm continue signal ctx done")
break
case <-g.continueSignalCh:
resource.LoggerService().Notice(ctx, "get continue signal")
time.Sleep(100 * time.Millisecond)
break
case <-g.continueWithChoiceCh:
resource.LoggerService().Notice(g.ctx, "modelReason cancel continueCancelCallCh", logit.AutoField("event", event))
resource.LoggerService().Notice(ctx, "get cancel signal")
time.Sleep(100 * time.Millisecond)
return
case <-g.continueWithDispatCh:
// go event.Cancel()
// resource.LoggerService().Notice(g.ctx, "modelReason cancel continueCancelCallCh", logit.AutoField("event", event))
// resource.LoggerService().Notice(ctx, "get cancel signal")
time.Sleep(100 * time.Millisecond)
break
}
}
if g.information.State.State == FsmStateReason {
// 判断轮数
// _ = g.fsmClient.Event(g.ctx, FsmEventRoundDispatch)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventRoundDispatch)
}
},
// 工具轮数调度
fmt.Sprintf("enter_%s", FsmStateRoundDispatch): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
// fmt.Println("进行工具调度信息")
toolRound := g.information.GetCurrentStep()
resource.LoggerService().Notice(ctx, "fsm:工具调度判断", logit.AutoField("round", toolRound))
// 相等时,表示已经执行完成所有的轮数,进入正文输出的状态
if g.information.GetCurrentStep() >= maxRound {
resource.LoggerService().Notice(ctx, "达到最大执行轮数,停止调度")
//_ = g.fsmClient.Event(g.ctx, FsmEventChat)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventChat)
return
}
// 按轮数进行调度处理
// _ = g.fsmClient.Event(g.ctx, FsmEventExecute)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventExecute)
},
// 模型调度
fmt.Sprintf("enter_%s", FsmStateExecute): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
if g.information.GetCurrentStep() > 0 {
workflowinfo := g.information.ToolCallRound[g.information.GetCurrentStep()-1].WorkflowInfo
// 判断是否为workflow的逻辑,是的话,直接执行workflow
if workflowinfo.IsWorkflow && workflowinfo.CurrentRound < workflowinfo.TotalRound {
g.ModelExecuteWorkFlowRound()
return
}
}
g.ModelExecute()
},
fmt.Sprintf("after_%s", FsmEventExecute): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
if g.isPauseFlag {
select {
case <-ctx.Done():
resource.LoggerService().Notice(ctx, "fsm continue signal ctx done")
return
case <-g.continueSignalCh: // 继续的逻辑
resource.LoggerService().Notice(ctx, "get continue signal")
time.Sleep(100 * time.Millisecond)
break
case <-g.continueWithChoiceCh: // 追问,会发新的信号
resource.LoggerService().Notice(g.ctx, "continue with choice")
time.Sleep(100 * time.Millisecond)
return
case <-g.continueWithDispatCh: // 工具调度,下一步还是走到工具调度的逻辑
resource.LoggerService().Notice(g.ctx, "modelReason cancel continueCancelCallCh", logit.AutoField("event", event))
time.Sleep(100 * time.Millisecond)
break
}
}
if g.information.GetCurrentStep() > 0 {
workflowinfo := g.information.ToolCallRound[g.information.GetCurrentStep()-1].WorkflowInfo
// 判断是否为workflow的逻辑,是的话,直接执行workflow
if !(workflowinfo.IsWorkflow && workflowinfo.CurrentRound < workflowinfo.TotalRound) && g.information.Base.ModelType == modelTypeSingle {
// 保存roundinfo信息
g.information.SaveCurrentRoundInfo(g.ctx)
//_ = g.fsmClient.Event(g.ctx, FsmEventSingleMessage)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventSingleMessage)
return
}
}
resource.LoggerService().Notice(ctx, "leave_state", logit.AutoField("event", event))
// fmt.Printf("leave_state: %s, %s", event.Src, event.Dst)
if g.information.State.State == FsmStateExecute {
//_ = g.fsmClient.Event(g.ctx, FsmEventRoundDispatch)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventRoundDispatch)
}
},
// 进入总结输出
fmt.Sprintf("enter_%s", FsmStateChat): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
g.information.SetState(g.ctx, FsmEventChat)
g.ModelChat()
},
// 总结输出状态
fmt.Sprintf("after_%s", FsmEventChat): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
//_ = g.fsmClient.Event(g.ctx, FsmEventCompleted)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventCompleted)
},
// 单工具总结输出状态
fmt.Sprintf("enter_%s", FsmEventSingleMessage): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
g.information.SetState(g.ctx, FsmEventChat)
g.modelChatSignle()
//_ = g.fsmClient.Event(g.ctx, FsmEventCompleted)
// fsm panic处理
_ = util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventCompleted)
},
// 结束输出
fmt.Sprintf("enter_%s", FsmEventCompleted): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
resource.LoggerService().Notice(ctx, "completed")
if g.hasMemory {
return
}
g.information.SetState(g.ctx, FsmStateCompleted)
g.sendCompleted(FsmStateCompleted)
// 调用长期记忆并写入历史记录
g.SaveLongTermMemory(ctx)
// 打点日志
protocol.ChatStageMonitor(g.ctx, protocol.StageData{
Channel: g.information.Base.Channel,
Stage: protocol.StageComplete,
Cost: int(time.Since(g.startTime).Milliseconds()),
ChatID: g.information.Base.ChatID,
QueryID: g.information.Base.QueryID,
UID: g.information.Base.UID,
ErrNo: "0",
RoundNum: g.information.GetCurrentStep(),
})
if g.needCache {
cacheData := genflowtypes.CacheData{
ChatID: g.information.Base.ChatID,
QueryID: g.information.Base.QueryID,
CreateTime: int(time.Now().Unix()),
BosURL: g.GetBucketObject(g.ctx),
}
// 加强数据验证,防止出现异常,导致写入redis失败后,预刷逻辑失败
if g.information.Base.ChatID != 0 && g.information.Base.QueryID != 0 {
key := g.getCacheKey(g.information.ChatMessage.Query)
_cachedata, _ := json.Marshal(cacheData)
if err := resource.Redis().Genflow.Set(g.ctx, key, _cachedata, time.Hour*24*7).Err(); err != nil {
resource.LoggerService().Warning(g.ctx, "save query cache fail", logit.Error("err", err))
}
} else {
resource.LoggerService().Warning(g.ctx, "save cache idalloc is fail")
}
}
g.memoryEnd <- true
},
fmt.Sprintf("enter_%s", FsmStatePause): func(ctx context.Context, event *fsm.Event) {
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
// g.waitPauseContinue(event.Args[0].(message.PauseInfo))
},
fmt.Sprintf("enter_%s", FsmStateCancel): func(ctx context.Context, event *fsm.Event) {
// _ = g.fsmClient.Event(g.ctx, FsmEventCompleted)
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
g.information.SetState(g.ctx, FsmStateCancel)
g.sendCompleted("cancelled")
// 调用长期记忆并写入历史记录
g.SaveLongTermMemory(ctx)
// TODO 取消后,消息内容输出提示
// fmt.Println("cancelled ")
// 如果事件类型为完成事件
// 打点日志
protocol.ChatStageMonitor(g.ctx, protocol.StageData{
Channel: g.information.Base.Channel,
Stage: protocol.StageCancel,
Cost: int(time.Since(g.startTime).Milliseconds()),
ChatID: g.information.Base.ChatID,
QueryID: g.information.Base.QueryID,
UID: g.information.Base.UID,
ErrNo: "0",
RoundNum: g.information.GetCurrentStep(),
})
g.memoryEnd <- true
},
fmt.Sprintf("enter_%s", FsmStateTimeout): func(ctx context.Context, event *fsm.Event) {
// _ = g.fsmClient.Event(g.ctx, FsmEventCompleted)
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
g.information.SetState(g.ctx, FsmStateTimeout)
g.sendCompleted(FsmStateError)
// 调用长期记忆并写入历史记录
_ = g.SaveLongTermMemory(ctx)
// TODO 取消后,消息内容输出提示
// fmt.Println("cancelled ")
// 如果事件类型为完成事件
// 打点日志
protocol.ChatStageMonitor(g.ctx, protocol.StageData{
Channel: g.information.Base.Channel,
Stage: protocol.StageTimeout,
Cost: int(time.Since(g.startTime).Milliseconds()),
ChatID: g.information.Base.ChatID,
QueryID: g.information.Base.QueryID,
UID: g.information.Base.UID,
ErrNo: "0",
RoundNum: g.information.GetCurrentStep(),
})
g.memoryEnd <- true
},
fmt.Sprintf("enter_%s", FsmStateError): func(ctx context.Context, event *fsm.Event) {
// _ = g.fsmClient.Event(g.ctx, FsmEventCompleted)
resource.LoggerService().Notice(ctx, "fsm statusChange", logit.AutoField("fsm", event))
g.information.SetState(g.ctx, FsmStateError)
err := -1
errMsg := "程序异常"
if len(event.Args) > 1 {
err = event.Args[0].(int)
errMsg = event.Args[1].(string)
}
g.sendError(FsmStateCompleted, err, errMsg)
// 调用长期记忆并写入历史记录
_ = g.SaveLongTermMemory(ctx)
// TODO 取消后,消息内容输出提示
// fmt.Println("cancelled ")
// 如果事件类型为完成事件
// 打点日志
protocol.ChatStageMonitor(g.ctx, protocol.StageData{
Channel: g.information.Base.Channel,
Stage: protocol.StageError,
Cost: int(time.Since(g.startTime).Milliseconds()),
ChatID: g.information.Base.ChatID,
QueryID: g.information.Base.QueryID,
UID: g.information.Base.UID,
ErrNo: "0",
RoundNum: g.information.GetCurrentStep(),
})
g.memoryEnd <- true
},
},
)
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
状态流转路径
init → queue → model_choice
↓
┌──────┴──────┐
↓ ↓
reason chat(简单模式)
↓ ↓
round_dispatch completed
↓
execute <─────────┘
↓
round_dispatch (循环,最多20轮)
↓
chat → completed
2
3
4
5
6
7
8
9
10
11
12
13
# 状态机启动
状态机一经初始化,就会自动执行到终止节点,所谓自动状态机的含义就是如此,在以下代码中,首先初始化了状态机,而后通过 util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventInit) 触发状态机的第一个事件,于是开启自动化流程
main.go
// Run 执行生成流处理任务
//
// 该方法初始化用户请求信息,设置30分钟超时上下文,并异步执行主处理逻辑。
// 返回一个事件通道用于接收处理过程中的状态和结果。
//
// 参数:
// ctx - 上游上下文,用于传递请求上下文信息
// req - 运行请求参数,包含对话消息、频道信息、用户ID等
// httpReq - HTTP请求对象,包含原始HTTP请求信息
//
// 返回: chan resource.Event - 事件通道,异步返回处理过程中的各种事件
func (g *genflow) Run(ctx context.Context, req genflowtypes.RunReq, httpReq ghttp.Request) chan resource.Event {
// 初始化用户请求信息
g.req = req
g.wpURIParamsExtra(ctx, httpReq, req)
g.ctx, g.ctxCancelFunc = context.WithTimeout(logit.CopyAllFields(context.Background(), ctx), time.Minute*30)
// 29min55S 会超时
g.backendTimeoutTimer = time.NewTimer(time.Minute*29 + time.Second*55)
g.upstreamCtx = ctx
g.httpReq = httpReq
// 执行一系列初始化,包括状态机的初始化
g.init()
// 异步执行任务
go safely.RunVoidContext1(g.ctx, g.run)
return g.outch
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
在 g.init() 里执行了状态机的初始化 initFSM()
func (g *genflow) init() {
g.outch = make(chan resource.Event, 100000)
g.sendCh = make(chan outputMessage, 100000) // 为防止发送缓冲区满,导致数据丢失,设置一个较大的缓冲区
g.closeChan = make(chan any)
g.inputRiskCh = make(chan bool)
g.pauseSignalCh = make(chan any, 10) // 暂停信号
g.fsmSignalCh = make(chan string) // 状态机信号变更
g.continueSignalCh = make(chan any)
g.continueCancelCallCh = make(chan any)
g.continueWithChoiceCh = make(chan any)
g.continueWithDispatCh = make(chan any)
g.sendToRedisCh = make(chan MemoryOutStruct, 10000) // 发送到redis的临时数据
g.initCompleteCh = make(chan any, 10) // 初始化完成信号的channel
g.panRiskCh = make(chan string, 100000) // 网盘风控检测
g.startTime = time.Now()
// continueWithDispatCh chan any // 下一步是dispatch的信号
// continueWithChoiceCh chan any // 下一步是choice工具的信号
g.sendCacheLock = sync.RWMutex{} // 发送缓存数据帧的锁
g.keepaliveTimer = time.NewTimer(KeepaliveTimer)
// 输出通道
go safely.RunVoidContext(g.ctx, g.sendToOutCh)
go g.sendToRedis()
go safely.RunVoid(func() {
g.initChatUserInfo()
})
g.strategyClient = strategy.NewStrategySvc()
// 设置基础信息
g.information.SetBase(g.ctx, g.req)
// 设置对话信息
g.information.SetInitChatInfo(g.ctx, g.req)
if cache, ok := g.information.Base.ExtraMapInfo[genflowtypes.ExtraIsCache]; ok {
g.needCache = cache.(bool)
key := g.getCacheKey(g.information.ChatMessage.Query)
if resource.Redis().Genflow.Exists(g.ctx, key).Val() > 0 {
g.iscached = true
}
// 临时先写死
g.forceModelType = 3
}
if modeltype, ok := g.information.Base.ExtraMapInfo[genflowtypes.ExtraForceModelType]; ok {
if modelTypefloat, ok := modeltype.(float64); ok {
g.forceModelType = int(modelTypefloat)
}
}
if !g.iscached {
// 异步初始化mcp
g.newAsyncClient()
go func() {
wg := sync.WaitGroup{}
// 初始化mcp client
wg.Add(1)
go func() {
defer wg.Done()
//g.initMcpClients(g.ctx)
//// 初始化mcp tools工具信息
//g.getMcpTools(g.ctx)
// 从缓存中获取mcp工具,减少耗时
tools, err := g.getMcpToolsCache(g.ctx)
// 缓存中没有数据,则通过mcp client同步获取
if err != nil || len(tools) == 0 {
tools = g.getMcpToolsWait(g.ctx)
resource.LoggerService().Warning(g.ctx, "getMcpToolsCache failed",
logit.AutoField("tools_count", len(tools)))
}
skipToolMap := g.toolSmallFlow()
for _, tool := range tools {
if len(skipToolMap) > 0 {
if _, ok := skipToolMap[tool.McpToolName]; ok {
continue
}
}
g.information.AllMcpTools = append(g.information.AllMcpTools, tool)
}
g.filterMcpToolsByExtra()
}()
//resource.LoggerService().Notice(g.ctx, "init mcp client success", logit.AutoField("clients", g.mcpClient))
/// 拉取工具配置
wg.Add(1)
go func() {
defer wg.Done()
g.getToolConf()
}()
// 初始化tooltips配置,amis,id:214
wg.Add(1)
go func() {
defer wg.Done()
g.initToolTipsConf(g.ctx)
}()
wg.Wait()
g.initCompleteCh <- "ok"
}()
}
// 拉取flag配置
g.getFlagConf()
// 初始化状态机
g.initFsm()
// 初始化临时记忆相关
g.initTempMemory()
go g.panGetRiskContent()
protocol.ChatStageMonitor(g.ctx, protocol.StageData{
Channel: g.information.Base.Channel,
Stage: protocol.StageInit,
Cost: int(time.Since(g.startTime).Milliseconds()),
ChatID: g.information.Base.ChatID,
QueryID: g.information.Base.QueryID,
UID: g.information.Base.UID,
ErrNo: "0",
})
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
在 g.run 中执行主流程,通过 SafeFSMEvent 触发 FSM 第一个事件,启动状态机
// 执行主进程
func (g *genflow) run(ctx context.Context) {
defer func() {
resource.LoggerService().Notice(ctx, "background run end")
g.close()
}()
if templateInfo, isHitTemplate := isPremakeTemplate(ctx, g.req); isHitTemplate && templateInfo != nil {
// 预刷返回
go safely.RunVoidContext(g.ctx, func() {
g.sendTemplate(ctx, *templateInfo)
})
} else if g.iscached {
go safely.RunVoidContext(g.ctx, func() { g.sendCache(ctx) })
} else {
// 异步执行任务
go safely.RunVoidContext(g.ctx, func() {
// err := g.fsmClient.Event(g.ctx, FsmEventInit)
// fsm panic处理
err := util.SafeFSMEvent(g.ctx, g.fsmClient, FsmEventInit)
resource.LoggerService().Notice(g.ctx, "event run end", logit.AutoField("err", err))
})
}
// 等待退出的信息
<-g.closeChan
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# GenFlow 流程控制
pause 和 message 接口在基础侧,通过特殊的 ping 数据帧实现 GenFlow 生成的暂停(持续输出 Ping 帧而不是数据帧),在业务侧标记暂停状态并告知前端停止输出,但是他这个暂停只是传输暂停(提供 ping 帧),但是后台模型其实还在跑任务
# 暂停 pause
业务层面的暂停:先检查是否有暂停 flag,然后设置暂停 flag
pause.go
func (u *pause) OnExecute(ctx context.Context, req ghttp.Request) (data any, err error) {
svc := genflow.NewGenflow()
pauseData := message.PauseData{
Type: genflow.PauseTypeUser,
SubType: 1,
Message: u.params.Message,
}
if ok := svc.HasPauseFlag(ctx, int(u.params.chatIDInt), int(u.params.queryIDInt)); ok {
protocol.UserOperaMonitor(ctx, protocol.UserOperaData{
Channel: u.params.Channel,
Operation: protocol.OperationTypePause,
SubType: 1,
ErrNo: fmt.Sprintf("%d", gerror.ErrorCodeUserPauseExixts),
ChatID: u.params.chatIDInt,
QueryID: u.params.queryIDInt,
})
return nil, errors.New("fail , already has pause flag")
}
key, err := svc.SetPauseData(ctx, int(u.params.chatIDInt), int(u.params.queryIDInt), pauseData)
if err != nil {
protocol.UserOperaMonitor(ctx, protocol.UserOperaData{
Channel: u.params.Channel,
Operation: protocol.OperationTypePause,
SubType: 1,
ErrNo: fmt.Sprintf("%d", gerror.ErrorCodeFuncUnknownError),
ChatID: u.params.chatIDInt,
QueryID: u.params.queryIDInt,
})
return nil, err
}
protocol.UserOperaMonitor(ctx, protocol.UserOperaData{
Channel: u.params.Channel,
Operation: protocol.OperationTypePause,
SubType: 1,
ErrNo: "0",
ChatID: u.params.chatIDInt,
QueryID: u.params.queryIDInt,
})
resp := PauseResponse{
Type: genflow.PauseTypeUser,
Message: u.params.Message,
SubType: 1,
MessageID: key,
}
return resp, nil
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
这里的 has 和 set 逻辑其实就是去设置 Redis ZSet,然后同步 MySQL
type PauseTToolsList struct {
PauseToolsList map[string][]string `json:"pause_tools_list"`
}
const (
PauseTypeUser = 1
PauseTypeSystem = 2
PauseSubTypeToolStop = 2 // 自动暂停
)
func (g *genflow) checkNeedPause(ctx context.Context) (pauseKey string, needPause bool) {
cacheKey := g.MakePauseCacheKey(g.information.Base.ChatID, g.information.Base.QueryID)
keys, err := resource.Redis().Genflow.ZRangeByScoreWithScores(ctx, cacheKey, &redis.ZRangeBy{
Min: "-inf",
Max: "+inf",
Count: 1,
}).Result()
if err != nil {
return "", false
}
if len(keys) == 0 {
return "", false
}
pauseKey, needPause = keys[0].Member.(string), true
resource.LoggerService().Notice(g.ctx, "get pause info ", logit.AutoField("redisCacheKey", cacheKey), logit.AutoField("pauseKey", pauseKey))
return
}
func (g *genflow) MakePauseCacheKey(chatID int, queryID int) string {
return fmt.Sprintf("pause:%d_%d", chatID, queryID)
}
// 设置暂停的flag信息
func (g *genflow) HasPauseFlag(ctx context.Context, chatID int, queryID int) bool {
cacheKey := g.MakePauseCacheKey(chatID, queryID)
hasCacheInfo := resource.Redis().Genflow.ZCard(ctx, cacheKey).Val() > 0
return hasCacheInfo
}
// 设置暂停后的结果信息
func (g *genflow) SetPauseData(ctx context.Context, chatID int, queryID int, value message.PauseData) (string, error) {
_v, _ := json.Marshal(value)
cacheKey := g.MakePauseCacheKey(chatID, queryID)
key := g.makeUniqID(ctx)
// 设置flag 的标识
resource.Redis().Genflow.ZAdd(ctx, cacheKey, &redis.Z{Score: float64(time.Now().Unix()), Member: key}).Err()
// 设置flag 的标识
g.isPauseFlag = true
// TODO 替换到mysql表中
return key, resource.Redis().Genflow.Set(ctx, key, string(_v), 0).Err()
}
// 获取暂停后的结果
func (g *genflow) GetPauseData(ctx context.Context, key string) (message.PauseData, error) {
ret := resource.Redis().Genflow.Get(ctx, key).Val()
var pauseData message.PauseData
err := json.Unmarshal([]byte(ret), &pauseData)
return pauseData, err
}
// 输出停止
func (g *genflow) sendOutputPause(info message.PauseInfo) {
var status string
if info.Type == PauseTypeUser {
status = StatusPauseUser
} else {
status = StatusPauseSystem
}
out := g.initOutputBase(status, EventPause, "pause")
out.Details = &outputDetails{
Type: status,
RunObject: info,
}
out.StepID = fmt.Sprintf("step-%d", g.information.GetCurrentStep()+1)
if g.overFlag < 1 {
g.sendCh <- out
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
为什么用 ZSet 存?是这样,每次调 chat 接口,其实都不是从头开始 chat,而是根据 queryID 和 chatID 调用 /message 接口,会直接从断点处开始继续输出 SSE,实现续传
# 续传 message
需要设置 continueKey 和 _continueData 和过期时间,标记重新开始生成
message.go
func MakeContinueKey(key string) string {
return fmt.Sprintf("continue:%s", key)
}
func (u *messageChange) OnExecute(ctx context.Context, req ghttp.Request) (data interface{}, err error) {
flagRet := u.CheckRisk(ctx, req, u.params.Type, u.params.Value)
if flagRet.Flag != 0 {
protocol.UserOperaMonitor(ctx, protocol.UserOperaData{
Channel: u.params.Channel,
Operation: protocol.OperationTypeContinue,
SubType: u.params.Type,
ErrNo: fmt.Sprintf("%d", gerror.ErrorCodeUserContinueRisk),
UID: u.params.UserID,
})
return messageResp{Flag: flagRet.Flag, FlagContent: flagRet.FlagContent}, nil
}
_data, err := resource.Redis().Genflow.Get(ctx, u.params.MessageID).Result()
if err != nil {
protocol.UserOperaMonitor(ctx, protocol.UserOperaData{
Channel: u.params.Channel,
Operation: protocol.OperationTypeContinue,
SubType: u.params.Type,
ErrNo: fmt.Sprintf("%d", gerror.ErrorCodeInternalError),
UID: u.params.UserID,
})
return nil, wkerror.New(gerror.ErrorCodeInternalError, gerror.ErrorMsgInternalError)
}
var pauseInfo message.PauseInfo
_ = json.Unmarshal([]byte(_data), &pauseInfo)
continueKey := genflowtypes.MakeContinueKey(u.params.MessageID)
continueData := genflowtypes.ContinueData{
MessageID: u.params.MessageID,
Type: u.params.Type,
Value: u.params.Value,
Extra: u.params.Extra,
}
_continueData, _ := json.Marshal(continueData)
err = resource.Redis().Genflow.Set(ctx, continueKey, _continueData, time.Hour*24*365).Err()
if err != nil {
protocol.UserOperaMonitor(ctx, protocol.UserOperaData{
Channel: u.params.Channel,
Operation: protocol.OperationTypeContinue,
SubType: u.params.Type,
ErrNo: fmt.Sprintf("%d", gerror.ErrorCodeInternalError),
UID: u.params.UserID,
})
return nil, wkerror.New(gerror.ErrorCodeInternalError, gerror.ErrorMsgInternalError)
}
// 风控处理
return messageResp{Flag: 0}, nil
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# GF 返回帧
展示到前端的帧结构大概有大几百帧,按顺序分为以下
- queued:任务入队
- model_choice:选择模型
- thoughts_execute:选择工具
- tool_call_info:调用大纲生成工具 makepptoutline
- ping:保持连接
- tool_call_info:大纲生成完毕
- pause:这里是在等待用户执行“生成 PPT 操作”,暂停返回
- continue:开始生成 PPT
- ping:保持连接
- thoughts_execute:选择工具
- tool_call_info:执行 PPT 生成工具 makeppt
- commerical:商业化回调接口
- run_end:结束帧
其中 tool_call_info 将重复执行数百次,直到任务完成,这是一个 Agent 结构的任务处理
event: queued
id: 1
data: {"channel":"…","chat_id":"…","query_id":"…","status":"run_begin","step_id":"step-1","flag":0,"send_id":1,"message":"run begin","event_type":"queued","details":{"type":"run_object","run_object":{"status":"queued","user_query":"根据上传的文档内容生成ppt","extra":{"disable_h5":true,"gen_method":"strict_compliance","html_ppt_gen_mode":"sse","ppt_mode":"html","scene":"generate_ppt","smallflow_v2":"88975_2-109673_1-109869_1-111936_3-115708_5-1164…<省略 3458 字符>…","wanpanAuthStatus":1},"file_infos":[{"file_id":"file-18189201408","name":"未命名文档.docx","size":30697,"file_type":4,"meta":"{\"doc_id\":\"1b68cbb280868762caaedd3383c4bb4cf7ecb71d\",\"doc_source\":\"private_lib\",\"query_id\":\"9e04f6cfc930f08583d049649b6648d7c0c70886\",\"tool_call_id\":\"\",\"bucket_object\":\"eb96be39d2c75257842e564ca132dee8/rtcs/wordeditor/d4296094d8f558352587b337ee1f8190/data/export/empty/1776341636_.docx\",\"md5sum\":\"eb96be39d2c75257842e564ca132dee8\",\"is_docx\":true,\"is_save_db\":\"\",\"is_ban\":false,\"bucket\":\"wordeditor\",\"need_update_file\":0,\"commit_status\":0}","source":2,"word_num":0,"create_time":0,"update_time":0,"hit_risk":false,"edit_status":0}]}}}
event: model_choice
id: 2
data: {"channel":"…","chat_id":"…","query_id":"…","status":"model_choice","step_id":"step-1","flag":0,"send_id":2,"message":"choice model type","event_type":"model_choice","details":{"type":"model_choice","run_object":{"is_simple":false,"model_type":4,"scene":"generate_ppt","img_gen_complex":false,"extra":{}}}}
event: thoughts_execute
id: 3
data: {"channel":"…","chat_id":"…","query_id":"…","status":"thoughts","step_id":"step-2","flag":0,"send_id":3,"is_end":1,"tokens_all":"","message":"","event_type":"thoughts_execute"}
event: tool_call_info
id: 4
data: {"channel":"…","chat_id":"…","query_id":"…","status":"tool_begin","step_id":"step-2","flag":0,"send_id":4,"message":"tool begin call ","event_type":"tool_call_info","details":{"type":"tool_info_array","run_object":{"tools":[{"id":"edbb36dd826df6ec4afe04a1b0717fd5360cb292","name":"wenku--wenchain_make_pptoutline","show_name":"PPT规划师","arguments":"{\"content\":\"\",\"file_ids\":[\"file-18189201408\"],\"genflow_extra\":{\"dispatch\":\"ppt_gen\",\"gen_method\":\"compliance\",\"language\":\"\",\"page_count\":\"\",\"ppt_mode\":\"standard\",\"ppt_scene\":\"document2ppt\",\"task_type\":\"生成\",\"tone_style\":\"\",\"topic\":\"\",\"tpl_type\":\"select_tpl\",\"write_for\":\"\"},\"ppt_type\":\"\",\"query\":\"根据上传的文档内容生成ppt\",\"user_instruct\":\"\"}","tool_config":{"commonToolName":""}}]}}}
event: ping
id: 7
data: {}
event: tool_call_info
id: 15
data: {"channel":"…","chat_id":"…","query_id":"…","status":"tool_submitted_all_output","step_id":"step-2","flag":0,"send_id":15,"message":"submit all ","event_type":"tool_call_info","details":{"type":"tool_info_array","run_object":{"tools":[{"id":"edbb36dd826df6ec4afe04a1b0717fd5360cb292","name":"wenku--wenchain_make_pptoutline","arguments":"{\"addition_query_idstr\":\"edbb36dd826df6ec4afe04a1b0717fd5360cb292\",\"content\":\"\",\"file_ids\":[\"file-18189201408\"],\"genflow_extra\":{\"dispatch\":\"ppt_gen\",\"gen_method\":\"compliance\",\"language\":\"\",\"page_count\":\"\",\"ppt_mode\":\"standard\",\"ppt_scene\":\"document2ppt\",\"task_type\":\"生成\",\"tone_style\":\"\",\"topic\":\"\",\"tpl_type\":\"select_tpl\",\"write_for\":\"\"},\"ppt_type\":\"\",\"query\":\"根据上传的文档内容生成ppt\",\"user_instruct\":\"\"}","output":"{\"title\":\"nihaos\",\"outline\":\"# nihaos\\n* nihaos Overview\\n * Introduction to nihaos\\n\",\"query\":\"根据上传的文档内容生成ppt\"}","tool_config":{"commonToolName":""}}]}}}
event: pause
id: 16
data: {"channel":"…","chat_id":"…","query_id":"…","status":"pause_system","step_id":"step-2","flag":0,"send_id":16,"message":"pause","event_type":"pause","details":{"type":"pause_system","run_object":{"message_id":"bedafdde4fcfafaad1f34693daef5ef7ba0d1204","type":2,"sub_type":2,"extra":""}}}
event: continue
id: 23
data: {"channel":"…","chat_id":"…","query_id":"…","status":"update_tool","step_id":"step-2","flag":0,"send_id":23,"message":"continue ","event_type":"continue","details":{"type":"update_tool","run_object":{"next_step":"step-3","value":[{"id":"edbb36dd826df6ec4afe04a1b0717fd5360cb292","value":"{\"title\":\"nihaos\",\"outline\":\"# nihaos\\n* nihaos Overview\\n * Introduction to nihaos\\n\"}"}],"extra":{"edbb36dd826df6ec4afe04a1b0717fd5360cb292":{"bdjson":"{\"id\":\"fe1e260a-8b28-461a-a5d4-d76a2cdf93af\",\"dataType\":\"data\",\"c\":{\"t\":\"text\",\"c\":[{\"t\":\"p\",\"c\":[{\"t\":\"span\",\"c\":\"nihaos\"}]},{\"t\":\"p\",\"c\":[{\"t\":\"desc\",\"c\":\"\"}]}]},\"ch\":[{\"id\":\"2b445ef9-a8b1-4531-a83b-0db377494de5\",\"dataType\":\"data\",\"c\":{\"t\":\"text\",\"c\":[{\"t\":\"p\",\"c\":[{\"t\":\"span\",\"c\":\"nihaos Overview\"}]},{\"t\":\"p\",\"c\":[{\"t\":\"desc\",\"c\":\"\"}]}]},\"ch\":[{\"id\":\"07276930-9a26-46b5-b927-d186369592b3\",\"dataType\":\"data\",\"c\":{\"t\":\"text\",\"c\":[{\"t\":\"p\",\"c\":[{\"t\":\"span\",\"c\":\"Introduction to nihaos\"}]},{\"t\":\"p\",\"c\":[{\"t\":\"desc\",\"c\":\"\"}]}]},\"ch\":[]}]}]}"}}}}}
event: thoughts_execute
id: 24
data: {"channel":"…","chat_id":"…","query_id":"…","status":"thoughts","step_id":"step-3","flag":0,"send_id":24,"is_end":1,"tokens_all":"","message":"","event_type":"thoughts_execute"}
event: tool_call_info
id: 25
data: {"channel":"…","chat_id":"…","query_id":"…","status":"tool_begin","step_id":"step-3","flag":0,"send_id":25,"message":"tool begin call ","event_type":"tool_call_info","details":{"type":"tool_info_array","run_object":{"tools":[{"id":"573ad5541ce42dc58bd63186bceb19e8b8f6ecf7","name":"wenku--wenchain_make_ppt","show_name":"PPT大师","sub_tool_name":"wenchain_make_ppt_html","arguments":"{\"content\":\"\",\"file_ids\":[\"file-18189201408\"],\"genflow_extra\":{\"dispatch\":\"ppt_gen\",\"gen_method\":\"compliance\",\"language\":\"\",\"page_count\":\"\",\"ppt_mode\":\"standard\",\"ppt_scene\":\"document2ppt\",\"task_type\":\"生成\",\"tone_style\":\"\",\"topic\":\"\",\"tpl_type\":\"select_tpl\",\"write_for\":\"\"},\"outline\":\"# nihaos\\n* nihaos Overview\\n * Introduction to nihaos\\n\",\"ppt_type\":\"\",\"query\":\"根据上传的文档内容生成ppt\",\"title\":\"nihaos\",\"user_instruct\":\"\"}","tool_config":{"commonToolName":""}}]}}}
event: commerical
id: 1331
data: {"channel":"…","chat_id":"…","query_id":"…","status":"commerical","step_id":"step-3","flag":0,"send_id":1331,"message":"","event_type":"commerical","details":{"type":"commercial_card","run_object":{"card_info":"{\"pointConsume\":{},\"interruptMsg\":{\"nonVip\":{},\"pointNotEnough\":{},\"vipPointNotEnough\":{}},\"remindMsg\":{\"nonVip\":{},\"vipNotEnough\":{},\"pointNotEnough\":{},\"vipPointNotEnough\":{}}}","tool_info":"[]","message":"","consume_point":0,"point_discount":0}}}
event: run_end
id: 1332
data: {"channel":"…","chat_id":"…","query_id":"…","status":"completed","step_id":"step-3","flag":0,"send_id":1332,"message":"completed output message","event_type":"run_end","details":{"type":"run_object","run_object":{"status":"completed","user_query":"","extra":null,"file_infos":null,"prompt_tokens":0,"completion_tokens":0,"total_tokens":0}}}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
至于这里的帧结构化输出,可以预想到,就是 Prompt 工程 + MCP + Try/Catch 兜底,然后在业务侧处理为
# SSE 流式输出设计
# 双 channel 流水线
输出不是一条 channel 直接怼到 HTTP,而是分成两级,中间挂一个独立协程做转运:
| channel | 类型 | 容量 | 职责 |
|---|---|---|---|
sendCh | chan outputMessage | 100000 | 业务侧产出:FSM 各状态把帧写进来 |
outch | chan resource.Event | 100000 | 对外输出:Run() 把它返回给 HTTP 层 range |
容量开到十万是刻意的选择——生成 PPT 时 tool_call_info 会连发数百帧,任何一级阻塞都会导致丢帧,宁可占内存也不能让发送缓冲区满。
sendToOutCh 就是夹在中间的轮询器,init() 里用 go safely.RunVoidContext(g.ctx, g.sendToOutCh) 常驻:
// 伪码:把业务帧从 sendCh 搬运到 outch,顺带处理暂停/保活/结束
func (g *genflow) sendToOutCh(ctx context.Context) {
for {
// 数据帧、暂停信号、保活定时器、结束信号多路 select
select {
case <-ctx.Done():
return
case frame := <-g.sendCh:
if g.isPauseFlag {
// 暂停期间不吐数据帧,改发 ping 维持连接
g.outch <- g.pingFrame()
continue
}
g.outch <- frame
case <-g.pauseSignalCh:
g.isPauseFlag = true
g.outch <- g.pauseFrame() // pause 帧,status=pause_user / pause_system
case <-g.continueSignalCh:
g.isPauseFlag = false
// 从断点续传,不重头跑:靠 continue:{messageID} 里记录的 next_step 定位
g.resume(g.getContinueData(ctx))
case <-g.keepaliveTimer.C:
g.outch <- g.pingFrame() // id:7 那种 data:{} 的帧
g.keepaliveTimer.Reset(KeepaliveTimer)
case <-g.backendTimeoutTimer.C: // 29min55s
g.outch <- g.endFrame(StatusTimeout)
return
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
关键点:暂停是传输层的暂停,不是任务终止。发 pause 帧、随后持续发 ping,但后台模型任务仍在跑(或者在断点挂起等续传),连接不会被代理掐断。
# 两类暂停语义的统一恢复
暂停有两种来源,表面看是两套接口,本质收敛到同一个轮询器:
| 类型 | 常量 | 触发 | pause 帧 status | 恢复方式 |
|---|---|---|---|---|
| 用户主动暂停 | PauseTypeUser = 1 | 用户点暂停 → /pause | pause_user | 用户点继续 → /message |
| 工具阻塞待补充 | PauseTypeSystem = 2,PauseSubTypeToolStop = 2 | 大纲生成完,等用户确认"生成 PPT" | pause_system | 用户提交确认 → /message 带 next_step |
两者走的是同一条路径:
- 标记:
pause.go调SetPauseData,在 Redis ZSetpause:{chatID}_{queryID}里ZAdd一个唯一 key(score 是时间戳),并把详情写进这个 key,g.isPauseFlag = true。 - 发帧:轮询器看到
isPauseFlag,往outch塞pause帧,前端停止渲染数据帧。 - 续传标记:
/message把续传数据(message_id、类型、next_step)写进continue:{messageID},过期一年,再投递continueSignalCh。 - 恢复:轮询器收到信号,清
isPauseFlag,从 ZSet 里定位断点继续执行。这就是为什么每次 chat 不是从头开始,而是靠queryID/chatID从断点续跑。
用 ZSet 而不是简单 string 存暂停标记,是为了支持"按时间取最早一个暂停点"(ZRangeByScoreWithScores ... Count: 1),并且同一会话可以有多个暂停记录待处理。
# pauseMonitor:把散落的 select 收敛成独立协程
上面是设计意图。落到代码里,真实的暂停判断原本是散在 FSM 各状态内的——modelToolChoices、dispatch 等处都各写一遍 if g.isPauseFlag { select {...} },等 continueSignalCh / continueWithChoiceCh / continueWithDispatCh。重复的 select 既难维护,也容易漏掉某个分支。
把这些 signals 抽象出来,收进一个独立的 pauseMonitor 协程,就是这套机制的干净表达:
// 伪码:根据散落在 FSM 各状态的 isPauseFlag + select 片段抽象,
// 不是逐字源码。pauseSignalCh 投递暂停,三类 continue channel 按
// 续传粒度分别投递,monitor 统一裁决是放行业务还是挂起等待。
type pauseKind int
const (
pauseUser pauseKind = iota // 用户主动
pauseToolStop // 工具阻塞待补充
)
func (g *genflow) pauseMonitor(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
// 统一入口:无论哪种暂停,都先查 ZSet 标记、发 pause 帧
case k := <-g.pauseSignalCh:
key, need := g.checkNeedPause(ctx)
if !need {
continue
}
g.isPauseFlag = true
g.outch <- g.pauseFrame(k) // k 决定 status 是 pause_user 还是 pause_system
// 三类续传:统一清 flag、从 continue:{messageID} 恢复
case <-g.continueSignalCh: // 通用续传
g.resume(g.getContinueData(ctx))
case <-g.continueWithChoiceCh: // 续传后重新做模型/工具选择
g.restoreToolChoice()
g.resume(g.getContinueData(ctx))
case <-g.continueWithDispatCh: // 续传后直接派发下一步(如补大纲跑 makeppt)
g.restoreToolDispatch()
g.resume(g.getContinueData(ctx))
}
g.isPauseFlag = false
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
这样两类暂停语义就有了统一的恢复出口:不管暂停来自用户还是工具阻塞,最后都是往某个 continue* channel 投一个信号,pauseMonitor 清标记、读 continue:{messageID}、按 next_step 恢复。FSM 主流程不再自己判断 isPauseFlag,只管产出帧;暂停策略全部内聚在 monitor 里。
对应到前端看到的帧序列,就是这一段:tool_call_info(大纲生成完毕)→ pause(type:2, sub_type:2)→ 用户确认 → continue(带 next_step: step-3 和补充的 outline)→ tool_call_info(执行 makeppt)。