Version: 0.9.2.dev.260406
后端:
1.Chat 四路由升级(二分类 chat/task → 四路由 direct_reply/execute/deep_answer/plan)
- 新建model/chat_contract.go:路由决策模型,含 NeedsRoughBuild 粗排标记
- 更新node/chat.go:四路由分流;新增 deep_answer 深度回答路径(二次 LLM 开 thinking)
- 更新prompt/chat.go:意图分类 prompt 升级为四路由 prompt;新增 deep_answer prompt
2.粗排节点(RoughBuild)全链路
- 新建node/rough_build.go:粗排节点,调用注入的算法函数,结果写入 ScheduleState 后进 Execute 微调
- 更新graph/common_graph.go:注册 RoughBuild 节点;Chat/Confirm 后可路由至粗排
- 更新model/graph_run_state.go:新增 RoughBuildPlacement/RoughBuildFunc 类型;Deps 注入入口
- 更新model/plan_contract.go:PlanDecision 新增 NeedsRoughBuild/TaskClassIDs 字段
- 更新node/plan.go:plan_done 时写入粗排标记和 TaskClassIDs
3.任务类约束元数据(TaskClassMeta)贯穿 prompt → tools → 持久化
- 更新tools/state.go:新增 TaskClassMeta;ScheduleState.TaskClasses;ScheduleTask.TaskClassID;Clone 深拷贝
- 更新conv/schedule_state.go:加载时构建 TaskClassMeta;Diff 支持 HostEventID 嵌入关系
- 更新conv/schedule_provider.go:新增 LoadTaskClassMetas 按需加载
- 更新model/state_store.go:ScheduleStateProvider 接口新增 LoadTaskClassMetas
- 更新prompt/base.go:renderStateSummary 渲染任务类约束
- 更新prompt/plan.go:注入任务类 ID 上下文和粗排识别规则
- 更新tools/read_tools.go:GetOverview 展示任务类约束
- 更新model/common_state.go:CommonState 新增 TaskClassIDs/TaskClasses/NeedsRoughBuild
4.Execute 健壮性增强(correction 重试 + 纯 ReAct 模式)
- 更新node/execute.go:未知工具名/空文本走 correction 重试而非 fatal;maxConsecutiveCorrections 提升为包级常量;新增无 plan 纯ReAct 模式;工具结果截断;speak 排除 ask_user/confirm
- 更新prompt/execute.go:新增 ReAct 模式 system prompt 和 contract
5.写入持久化完善(task_item source + 嵌入水课)
- 更新conv/schedule_persist.go:place/move/unplace 支持 task_item source,含嵌入水课和普通 task event 两条路径
- 新建conv/schedule_preview.go:ScheduleState → 排程预览缓存,复用旧格式,前端无需改动
6.状态持久化体系(Redis → MySQL outbox 异步)
- 更新dao/cache.go:Redis 快照 TTL 从 24h 改为 2h,配合 MySQL outbox
- 新建model/agent_state_snapshot_record.go:快照 MySQL 记录模型
- 新建service/events/agent_state_persist.go:outbox 异步持久化处理器
- 更新cmd/start.go + inits/mysql.go:注册快照事件处理器 + AutoMigrate
- 更新service/agentsvc/agent_newagent.go:注入 RoughBuildFunc;outbox 异步写快照;排程结果写 Redis 预览缓存
7.基础设施与稳定性
- 更新stream/sse_adapter.go:outChan 满时静默丢弃,保证持久化不被 SSE 阻断
- 更新service/agentsvc/agent.go:新增 readAgentExtraIntSlice;outChan 容量 8→256
- 更新node/agent_nodes.go:Chat 注入工具 schema;Deliver 改 saveAgentState 替代 deleteAgentState
前端:无
仓库:无
This commit is contained in:
@@ -289,7 +289,30 @@ func readAgentExtraInt(extra map[string]any, key string) int {
|
||||
return value
|
||||
}
|
||||
|
||||
// parseAgentLooseInt 负责把 extra 中的“弱类型数字”归一成 int。
|
||||
// readAgentExtraIntSlice 从 extra 中提取 []int。
|
||||
// 支持 JSON 数组格式([]any,每个元素为 float64/int)。
|
||||
func readAgentExtraIntSlice(extra map[string]any, key string) []int {
|
||||
if len(extra) == 0 {
|
||||
return nil
|
||||
}
|
||||
raw, ok := extra[key]
|
||||
if !ok || raw == nil {
|
||||
return nil
|
||||
}
|
||||
arr, ok := raw.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
result := make([]int, 0, len(arr))
|
||||
for _, item := range arr {
|
||||
if v, ok := parseAgentLooseInt(item); ok && v > 0 {
|
||||
result = append(result, v)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// parseAgentLooseInt 负责把 extra 中的”弱类型数字”归一成 int。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 负责兼容前端 JSON 解码后的常见数值类型,以及字符串形式的数字。
|
||||
@@ -530,7 +553,7 @@ func (s *AgentService) AgentChat(ctx context.Context, userMessage string, ifThin
|
||||
requestStart := time.Now()
|
||||
traceID := uuid.NewString()
|
||||
|
||||
outChan := make(chan string, 8)
|
||||
outChan := make(chan string, 256)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
@@ -547,7 +570,7 @@ func (s *AgentService) agentChatOld(ctx context.Context, userMessage string, ifT
|
||||
requestStart := time.Now()
|
||||
traceID := uuid.NewString()
|
||||
|
||||
outChan := make(chan string, 8)
|
||||
outChan := make(chan string, 256)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
// 0. 初始化”请求级 token 统计器”,用于聚合本次请求所有模型开销。
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/LoveLosita/smartflow/backend/conv"
|
||||
"github.com/LoveLosita/smartflow/backend/model"
|
||||
"github.com/LoveLosita/smartflow/backend/pkg"
|
||||
eventsvc "github.com/LoveLosita/smartflow/backend/service/events"
|
||||
)
|
||||
|
||||
// runNewAgentGraph 运行 newAgent 通用 graph,直接替换旧 agent 路由逻辑。
|
||||
@@ -100,6 +101,21 @@ func (s *AgentService) runNewAgentGraph(
|
||||
conversationContext = s.loadConversationContext(requestCtx, chatID, userMessage)
|
||||
}
|
||||
|
||||
// 5.5 若 extra 携带 task_class_ids,写入 CommonState(仅首轮/尚未设置时生效,跨轮持久化)。
|
||||
if taskClassIDs := readAgentExtraIntSlice(extra, "task_class_ids"); len(taskClassIDs) > 0 {
|
||||
cs := runtimeState.EnsureCommonState()
|
||||
if len(cs.TaskClassIDs) == 0 {
|
||||
cs.TaskClassIDs = taskClassIDs
|
||||
if s.scheduleProvider != nil {
|
||||
if metas, metaErr := s.scheduleProvider.LoadTaskClassMetas(requestCtx, userID, taskClassIDs); metaErr != nil {
|
||||
log.Printf("加载任务类约束元数据失败 chat=%s err=%v", chatID, metaErr)
|
||||
} else {
|
||||
cs.TaskClasses = metas
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 构造 AgentGraphRequest。
|
||||
var confirmAction string
|
||||
if len(extra) > 0 {
|
||||
@@ -132,6 +148,7 @@ func (s *AgentService) runNewAgentGraph(
|
||||
ToolRegistry: s.toolRegistry,
|
||||
ScheduleProvider: s.scheduleProvider,
|
||||
SchedulePersistor: s.schedulePersistor,
|
||||
RoughBuildFunc: s.makeRoughBuildFunc(),
|
||||
}
|
||||
|
||||
// 10. 构造 AgentGraphRunInput 并运行 graph。
|
||||
@@ -154,6 +171,33 @@ func (s *AgentService) runNewAgentGraph(
|
||||
|
||||
// 11. 持久化聊天历史(用户消息 + 助手回复)。
|
||||
s.persistChatAfterGraph(requestCtx, userID, chatID, userMessage, finalState, retryMeta, requestStart, outChan, errChan)
|
||||
// 11.5. 将最终状态快照异步写入 MySQL(通过 outbox)。
|
||||
// Deliver 节点已将快照保存到 Redis(2h TTL),此处通过 outbox 异步写入 MySQL 做永久存储。
|
||||
if finalState != nil {
|
||||
snapshot := &newagentmodel.AgentStateSnapshot{
|
||||
RuntimeState: finalState.EnsureRuntimeState(),
|
||||
ConversationContext: finalState.EnsureConversationContext(),
|
||||
}
|
||||
eventsvc.PublishAgentStateSnapshot(requestCtx, s.eventPublisher, snapshot, chatID, userID)
|
||||
}
|
||||
|
||||
// 11.6. 将排程结果写入 Redis 预览缓存,复用旧 agent 的 SchedulePlanPreviewCache 格式。
|
||||
// 前端通过 GET /agent/schedule-preview 获取,无需改动。
|
||||
if finalState != nil && finalState.ScheduleState != nil {
|
||||
flowState := finalState.EnsureFlowState()
|
||||
preview := conv.ScheduleStateToPreview(
|
||||
finalState.ScheduleState,
|
||||
userID,
|
||||
chatID,
|
||||
flowState.TaskClassIDs,
|
||||
"", // summary 由转换函数自动生成
|
||||
)
|
||||
if preview != nil && s.cacheDAO != nil {
|
||||
if err := s.cacheDAO.SetSchedulePlanPreviewToCache(requestCtx, userID, chatID, preview); err != nil {
|
||||
log.Printf("[WARN] 写入排程预览缓存失败 chat=%s: %v", chatID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 12. 发送 OpenAI 兼容的流式结束标记,告知客户端 stream 已完成。
|
||||
_ = chunkEmitter.EmitDone()
|
||||
@@ -203,6 +247,10 @@ func (s *AgentService) loadOrCreateRuntimeState(ctx context.Context, chatID stri
|
||||
cs := snapshot.RuntimeState.EnsureCommonState()
|
||||
cs.UserID = userID
|
||||
cs.ConversationID = chatID
|
||||
|
||||
// 不需要手动重置 Phase:所有请求统一先过 Chat 节点,Chat 会根据路由决策覆盖 Phase。
|
||||
// 保留完整的 RuntimeState(PlanSteps、CurrentStep 等),支持连续对话调整日程。
|
||||
|
||||
return snapshot.RuntimeState, snapshot.ConversationContext
|
||||
}
|
||||
return newRT()
|
||||
@@ -376,6 +424,35 @@ func (s *AgentService) persistChatAfterGraph(
|
||||
}
|
||||
}
|
||||
|
||||
// makeRoughBuildFunc 把 AgentService 上的 HybridScheduleWithPlanMultiFunc 封装成
|
||||
// newAgent 层的 RoughBuildFunc,完成外层 model.TaskClassItem → RoughBuildPlacement 的转换。
|
||||
// HybridScheduleWithPlanMultiFunc 未注入时返回 nil,RoughBuild 节点会静默跳过粗排。
|
||||
func (s *AgentService) makeRoughBuildFunc() newagentmodel.RoughBuildFunc {
|
||||
if s.HybridScheduleWithPlanMultiFunc == nil {
|
||||
return nil
|
||||
}
|
||||
return func(ctx context.Context, userID int, taskClassIDs []int) ([]newagentmodel.RoughBuildPlacement, error) {
|
||||
_, items, err := s.HybridScheduleWithPlanMultiFunc(ctx, userID, taskClassIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
placements := make([]newagentmodel.RoughBuildPlacement, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item.EmbeddedTime == nil {
|
||||
continue
|
||||
}
|
||||
placements = append(placements, newagentmodel.RoughBuildPlacement{
|
||||
TaskItemID: item.ID,
|
||||
Week: item.EmbeddedTime.Week,
|
||||
DayOfWeek: item.EmbeddedTime.DayOfWeek,
|
||||
SectionFrom: item.EmbeddedTime.SectionFrom,
|
||||
SectionTo: item.EmbeddedTime.SectionTo,
|
||||
})
|
||||
}
|
||||
return placements, nil
|
||||
}
|
||||
}
|
||||
|
||||
// --- 依赖注入字段 ---
|
||||
|
||||
// toolRegistry 由 cmd/start.go 注入
|
||||
|
||||
126
backend/service/events/agent_state_persist.go
Normal file
126
backend/service/events/agent_state_persist.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
"github.com/LoveLosita/smartflow/backend/dao"
|
||||
kafkabus "github.com/LoveLosita/smartflow/backend/infra/kafka"
|
||||
outboxinfra "github.com/LoveLosita/smartflow/backend/infra/outbox"
|
||||
"github.com/LoveLosita/smartflow/backend/model"
|
||||
newagentmodel "github.com/LoveLosita/smartflow/backend/newAgent/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
const (
|
||||
// EventTypeAgentStateSnapshotPersist 是"agent 状态快照持久化"的业务事件类型。
|
||||
EventTypeAgentStateSnapshotPersist = "agent.state.snapshot.persist"
|
||||
)
|
||||
|
||||
// AgentStateSnapshotPayload 是 outbox 事件的业务载荷。
|
||||
type AgentStateSnapshotPayload struct {
|
||||
ConversationID string `json:"conversation_id"`
|
||||
UserID int `json:"user_id"`
|
||||
Phase string `json:"phase"`
|
||||
SnapshotJSON string `json:"snapshot_json"`
|
||||
}
|
||||
|
||||
// RegisterAgentStateSnapshotHandler 注册"agent 状态快照持久化"消费者处理器。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只负责快照写入 agent_state_snapshot_records 表;
|
||||
// 2. 使用 upsert 语义,同一 conversation_id 只保留最新快照;
|
||||
// 3. 通过 outbox 通用消费事务保证"业务写入 + consumed 推进"原子一致。
|
||||
func RegisterAgentStateSnapshotHandler(
|
||||
bus *outboxinfra.EventBus,
|
||||
outboxRepo *outboxinfra.Repository,
|
||||
repoManager *dao.RepoManager,
|
||||
) error {
|
||||
if bus == nil {
|
||||
return errors.New("event bus is nil")
|
||||
}
|
||||
if outboxRepo == nil {
|
||||
return errors.New("outbox repository is nil")
|
||||
}
|
||||
if repoManager == nil {
|
||||
return errors.New("repo manager is nil")
|
||||
}
|
||||
|
||||
handler := func(ctx context.Context, envelope kafkabus.Envelope) error {
|
||||
var payload AgentStateSnapshotPayload
|
||||
if unmarshalErr := json.Unmarshal(envelope.Payload, &payload); unmarshalErr != nil {
|
||||
_ = outboxRepo.MarkDead(ctx, envelope.OutboxID, "解析快照载荷失败: "+unmarshalErr.Error())
|
||||
return nil
|
||||
}
|
||||
|
||||
return outboxRepo.ConsumeAndMarkConsumed(ctx, envelope.OutboxID, func(tx *gorm.DB) error {
|
||||
record := model.AgentStateSnapshotRecord{
|
||||
ConversationID: payload.ConversationID,
|
||||
UserID: payload.UserID,
|
||||
Phase: payload.Phase,
|
||||
SnapshotJSON: payload.SnapshotJSON,
|
||||
}
|
||||
return tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "conversation_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"user_id", "phase", "snapshot_json", "updated_at"}),
|
||||
}).Create(&record).Error
|
||||
})
|
||||
}
|
||||
|
||||
return bus.RegisterEventHandler(EventTypeAgentStateSnapshotPersist, handler)
|
||||
}
|
||||
|
||||
// PublishAgentStateSnapshot 发布"agent 状态快照持久化"事件到 outbox。
|
||||
//
|
||||
// 设计说明:
|
||||
// 1. 将快照 JSON 序列化后通过 outbox 异步写入 MySQL;
|
||||
// 2. publisher 为 nil 时静默降级(Kafka 未启用场景);
|
||||
// 3. 发布失败只记日志,不中断主流程。
|
||||
func PublishAgentStateSnapshot(
|
||||
ctx context.Context,
|
||||
publisher outboxinfra.EventPublisher,
|
||||
snapshot *newagentmodel.AgentStateSnapshot,
|
||||
conversationID string,
|
||||
userID int,
|
||||
) {
|
||||
if publisher == nil {
|
||||
return
|
||||
}
|
||||
if snapshot == nil {
|
||||
return
|
||||
}
|
||||
|
||||
snapshotJSON, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
log.Printf("[WARN] 序列化 agent 状态快照失败 chat=%s: %v", conversationID, err)
|
||||
return
|
||||
}
|
||||
|
||||
phase := ""
|
||||
if snapshot.RuntimeState != nil {
|
||||
cs := snapshot.RuntimeState.EnsureCommonState()
|
||||
if cs != nil {
|
||||
phase = string(cs.Phase)
|
||||
}
|
||||
}
|
||||
|
||||
payload := AgentStateSnapshotPayload{
|
||||
ConversationID: conversationID,
|
||||
UserID: userID,
|
||||
Phase: phase,
|
||||
SnapshotJSON: string(snapshotJSON),
|
||||
}
|
||||
|
||||
if err := publisher.Publish(ctx, outboxinfra.PublishRequest{
|
||||
EventType: EventTypeAgentStateSnapshotPersist,
|
||||
EventVersion: outboxinfra.DefaultEventVersion,
|
||||
MessageKey: conversationID,
|
||||
AggregateID: conversationID,
|
||||
Payload: payload,
|
||||
}); err != nil {
|
||||
log.Printf("[WARN] 发布 agent 状态快照事件失败 chat=%s: %v", conversationID, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user