后端:
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
前端:无
仓库:无
203 lines
6.0 KiB
Go
203 lines
6.0 KiB
Go
package newagentprompt
|
||
|
||
import (
|
||
"fmt"
|
||
"strings"
|
||
|
||
newagentmodel "github.com/LoveLosita/smartflow/backend/newAgent/model"
|
||
"github.com/cloudwego/eino/schema"
|
||
)
|
||
|
||
// buildStageMessages 组装某个阶段通用的 messages。
|
||
//
|
||
// 步骤说明:
|
||
// 1. 先合并 context 自带 system prompt 与阶段 prompt,保证通用约束和阶段约束都生效;
|
||
// 2. 再把置顶上下文块和工具摘要补成 system message,尽量顶在 history 前面;
|
||
// 3. 最后追加历史消息与本轮 user prompt,保持"新约束在前、历史在后"的稳定顺序。
|
||
func buildStageMessages(stageSystemPrompt string, ctx *newagentmodel.ConversationContext, runtimeUserPrompt string) []*schema.Message {
|
||
messages := make([]*schema.Message, 0, 4)
|
||
|
||
mergedSystemPrompt := mergeSystemPrompts(ctx, stageSystemPrompt)
|
||
if mergedSystemPrompt != "" {
|
||
messages = append(messages, schema.SystemMessage(mergedSystemPrompt))
|
||
}
|
||
|
||
if pinnedText := renderPinnedBlocks(ctx); pinnedText != "" {
|
||
messages = append(messages, schema.SystemMessage(pinnedText))
|
||
}
|
||
|
||
if toolText := renderToolSchemas(ctx); toolText != "" {
|
||
messages = append(messages, schema.SystemMessage(toolText))
|
||
}
|
||
|
||
if ctx != nil {
|
||
history := ctx.HistorySnapshot()
|
||
if len(history) > 0 {
|
||
// 兼容旧快照:裸 Tool 消息(无 ToolCallID)违反 OpenAI 兼容 API 格式约束,
|
||
// 会触发 API 拒绝请求导致连接断开。
|
||
// 这里将裸 Tool 消息降级为 User 消息,保证向后兼容。
|
||
for i, msg := range history {
|
||
if msg.Role == schema.Tool && msg.ToolCallID == "" {
|
||
history[i] = &schema.Message{
|
||
Role: schema.User,
|
||
Content: fmt.Sprintf("[工具执行结果]\n%s", msg.Content),
|
||
}
|
||
}
|
||
}
|
||
messages = append(messages, history...)
|
||
}
|
||
}
|
||
|
||
runtimeUserPrompt = strings.TrimSpace(runtimeUserPrompt)
|
||
if runtimeUserPrompt != "" {
|
||
messages = append(messages, schema.UserMessage(runtimeUserPrompt))
|
||
}
|
||
|
||
return messages
|
||
}
|
||
|
||
// renderStateSummary 把当前流程状态渲染成简洁文本。
|
||
func renderStateSummary(state *newagentmodel.CommonState) string {
|
||
if state == nil {
|
||
return "当前状态:state 缺失,请先做兜底处理。"
|
||
}
|
||
|
||
var sb strings.Builder
|
||
current, total := state.PlanProgress()
|
||
|
||
sb.WriteString(fmt.Sprintf("当前阶段:%s\n", state.Phase))
|
||
sb.WriteString(fmt.Sprintf("当前轮次:%d/%d\n", state.RoundUsed, state.MaxRounds))
|
||
|
||
if !state.HasPlan() {
|
||
sb.WriteString("当前完整 plan:暂无。\n")
|
||
} else {
|
||
sb.WriteString("当前完整 plan:\n")
|
||
for i, step := range state.PlanSteps {
|
||
sb.WriteString(fmt.Sprintf("%d. %s\n", i+1, strings.TrimSpace(step.Content)))
|
||
if strings.TrimSpace(step.DoneWhen) != "" {
|
||
sb.WriteString(fmt.Sprintf(" 完成判定:%s\n", strings.TrimSpace(step.DoneWhen)))
|
||
}
|
||
}
|
||
|
||
if step, ok := state.CurrentPlanStep(); ok {
|
||
sb.WriteString(fmt.Sprintf("当前步骤进度:%d/%d\n", current, total))
|
||
sb.WriteString("当前步骤内容:\n")
|
||
sb.WriteString(strings.TrimSpace(step.Content))
|
||
sb.WriteString("\n")
|
||
if strings.TrimSpace(step.DoneWhen) != "" {
|
||
sb.WriteString("当前步骤完成判定:\n")
|
||
sb.WriteString(strings.TrimSpace(step.DoneWhen))
|
||
sb.WriteString("\n")
|
||
}
|
||
} else {
|
||
sb.WriteString("当前步骤进度:暂时无有效当前步骤。\n")
|
||
}
|
||
}
|
||
|
||
// 渲染任务类约束元数据(如有),帮助 LLM 了解排程范围和策略,避免追问已有信息。
|
||
if len(state.TaskClasses) > 0 {
|
||
sb.WriteString("\n本次排课涉及的任务类约束:\n")
|
||
for _, tc := range state.TaskClasses {
|
||
line := fmt.Sprintf("- [ID=%d] %s:策略=%s,总时段预算=%d", tc.ID, tc.Name, tc.Strategy, tc.TotalSlots)
|
||
if tc.StartDate != "" || tc.EndDate != "" {
|
||
line += fmt.Sprintf(",日期范围=%s ~ %s", tc.StartDate, tc.EndDate)
|
||
}
|
||
if tc.AllowFillerCourse {
|
||
line += ",允许嵌入水课"
|
||
}
|
||
if len(tc.ExcludedSlots) > 0 {
|
||
line += fmt.Sprintf(",排除时段=%v", tc.ExcludedSlots)
|
||
}
|
||
sb.WriteString(line + "\n")
|
||
}
|
||
}
|
||
|
||
return sb.String()
|
||
}
|
||
|
||
// renderPinnedBlocks 把 ConversationContext 中的置顶块渲染成独立的 system 文本。
|
||
func renderPinnedBlocks(ctx *newagentmodel.ConversationContext) string {
|
||
if ctx == nil {
|
||
return ""
|
||
}
|
||
|
||
blocks := ctx.PinnedBlocksSnapshot()
|
||
if len(blocks) == 0 {
|
||
return ""
|
||
}
|
||
|
||
var sb strings.Builder
|
||
sb.WriteString("以下是后端置顶注入的上下文,请优先遵守:\n")
|
||
for _, block := range blocks {
|
||
title := strings.TrimSpace(block.Title)
|
||
if title == "" {
|
||
title = strings.TrimSpace(block.Key)
|
||
}
|
||
if title != "" {
|
||
sb.WriteString("【")
|
||
sb.WriteString(title)
|
||
sb.WriteString("】\n")
|
||
}
|
||
sb.WriteString(strings.TrimSpace(block.Content))
|
||
sb.WriteString("\n")
|
||
}
|
||
return strings.TrimSpace(sb.String())
|
||
}
|
||
|
||
// renderToolSchemas 把工具摘要渲染成独立文本块。
|
||
func renderToolSchemas(ctx *newagentmodel.ConversationContext) string {
|
||
if ctx == nil {
|
||
return ""
|
||
}
|
||
|
||
schemas := ctx.ToolSchemasSnapshot()
|
||
if len(schemas) == 0 {
|
||
return ""
|
||
}
|
||
|
||
var sb strings.Builder
|
||
sb.WriteString("以下是当前可用工具摘要,仅供你在规划时参考能力边界:\n")
|
||
for _, item := range schemas {
|
||
name := strings.TrimSpace(item.Name)
|
||
desc := strings.TrimSpace(item.Desc)
|
||
schemaText := strings.TrimSpace(item.SchemaText)
|
||
|
||
if name != "" {
|
||
sb.WriteString("- 工具名:")
|
||
sb.WriteString(name)
|
||
sb.WriteString("\n")
|
||
}
|
||
if desc != "" {
|
||
sb.WriteString(" 说明:")
|
||
sb.WriteString(desc)
|
||
sb.WriteString("\n")
|
||
}
|
||
if schemaText != "" {
|
||
sb.WriteString(" 参数摘要:")
|
||
sb.WriteString(schemaText)
|
||
sb.WriteString("\n")
|
||
}
|
||
}
|
||
|
||
return strings.TrimSpace(sb.String())
|
||
}
|
||
|
||
func mergeSystemPrompts(ctx *newagentmodel.ConversationContext, stageSystemPrompt string) string {
|
||
base := ""
|
||
if ctx != nil {
|
||
base = strings.TrimSpace(ctx.SystemPrompt)
|
||
}
|
||
stageSystemPrompt = strings.TrimSpace(stageSystemPrompt)
|
||
|
||
switch {
|
||
case base == "" && stageSystemPrompt == "":
|
||
return ""
|
||
case base == "":
|
||
return stageSystemPrompt
|
||
case stageSystemPrompt == "":
|
||
return base
|
||
default:
|
||
return base + "\n\n" + stageSystemPrompt
|
||
}
|
||
}
|