后端: 1. Prompt 层从 execute 专属骨架重构为全节点统一四段式 buildUnifiedStageMessages - 新增 unified_context.go:定义 StageMessagesConfig + buildUnifiedStageMessages 统一骨架,所有节点(Chat/Plan/Execute/Deliver/DeepAnswer)共用同一套 msg0~msg3 拼装逻辑 - 新增 conversation_view.go:通用对话历史渲染 buildConversationHistoryMessage,各节点复用,不再各自维护提取逻辑 - 新增 chat_context.go / plan_context.go / deliver_context.go:各节点自行渲染 msg1(对话视图)和 msg2(工作区),统一层只负责"怎么拼",不再替节点决定"放什么" - Chat/Plan/Deliver/Execute 的 BuildXXXMessages 全部从 buildStageMessages 切到 buildUnifiedStageMessages,移除旧路径 - 删除 execute_pinned.go:execute 记忆渲染合并到统一层 renderUnifiedMemoryContext - Plan prompt 不再在 user prompt 中拼装任务类 ID 列表和 renderStateSummary,改为依赖 msg2 规划工作区;Chat 粗排判断从"上下文有任务类 ID"改为"批量调度需求" - Deliver prompt 新增 IsAborted/IsExhaustedTerminal 区分,支持粗排收口和主动终止场景 2. Execute ReAct 上下文简化——移除归档搬运、窗口裁剪和重复工具压缩 - 移除 splitExecuteLoopRecordsByBoundary、findLatestExecuteBoundaryMarker、tailExecuteLoops、compressExecuteLoopObservationsByTool、buildEarlyExecuteReactSummary、trimExecuteMessage1ByBudget 等六个函数 - 移除 executeLoopWindowLimit / executeConversationTurnLimit / executeMessage1MaxRunes 等预算常量 - msg1 不再从历史中归档上一轮 ReAct 结果,只保留真实对话流(user + assistant speak),全量注入 - msg2 不再按 loop_closed / step_advanced 边界切分"归档/活跃",直接全量注入全部 ReAct Loop 记录 - token 预算由统一压缩层兜底,prompt 层不再做提前裁剪 3. 压缩层从 Execute 专属提升为全节点通用 UnifiedCompact - 删除 execute_compact.go(Execute 专属压缩文件) - 新增 unified_compact.go:UnifiedCompactInput 参数化,各节点(Plan/Chat/Deliver/Execute)构造时从自己的 NodeInput 提取公共字段,消除对 Execute 的直接依赖 - CompactionStore 接口扩展 LoadStageCompaction / SaveStageCompaction,各节点按 stageKey 独立维护压缩状态互不覆盖 - 非 4 段式消息时退化成按角色汇总统计,确保 context_token_stats 仍然刷新 4. Retry 重试机制全面下线 - dao/agent.go:saveChatHistoryCore / SaveChatHistory / SaveChatHistoryInTx 移除 retry_group_id / retry_index / retry_from_user_message_id / retry_from_assistant_message_id 四个参数,修复乱码注释 - dao/agent-cache.go:移除 ApplyRetrySeed 和 extractMessageHistoryID 两个方法 - conv/agent.go:ToEinoMessages 不再回灌 retry_* 字段到运行期上下文 - service/agentsvc/agent.go:移除 chatRetryMeta 及 resolveRetryGroupID / buildRetrySeed 等全部重试逻辑 - service/agentsvc/agent_quick_note.go:整个文件删除(retry 快速补写路径已无用) - service/events/chat_history_persist.go:移除 retry 参数传递 5. 节点层瘦身 + 可见消息逐条持久化 - agent_nodes.go 大幅简化:Chat/Plan/Execute/Deliver 节点方法移除 ToolSchema 注入、状态摘要渲染等逻辑,只做参数转发和状态落盘 - 新增 visible_message.go:persistVisibleAssistantMessage 统一处理可见 assistant speak 的实时持久化,失败仅记日志不中断主流程 - 新增 llm_debug.go:logNodeLLMContext 统一打印 LLM 上下文调试日志 - graph_run_state.go 新增 PersistVisibleMessageFunc 类型 + AgentGraphDeps.PersistVisibleMessage 字段 - service/agentsvc/agent_newagent.go 精简主循环,注入 PersistVisibleMessage 回调;agent_history.go 精简历史构建 - token_budget.go 移除 Execute 专属预算检查,统一到通用预算 前端: 1. 移除 retry 相关 UI 和类型 - agent.ts 移除 retry_group_id / retry_index / retry_total 字段及 normalize 逻辑 - AssistantPanel.vue 移除 retry 相关 UI 和交互代码(约 700 行精简) - dashboard.ts 移除 retry 相关类型定义 - AssistantView.vue 微调 2. ContextWindowMeter 压缩次数展示和数值格式优化 - 新增 formatCompactCount 工具函数,千位以上用 k 单位压缩(如 80k) - 新增压缩次数显示 3.修复了新对话发消息时,user和assistant消息被自动调换的bug 仓库:无
227 lines
6.1 KiB
Go
227 lines
6.1 KiB
Go
package dao
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/cloudwego/eino/schema"
|
|
"github.com/go-redis/redis/v8"
|
|
)
|
|
|
|
type AgentCache struct {
|
|
client *redis.Client
|
|
// 默认窗口大小(会被会话级动态窗口覆盖)
|
|
windowSize int
|
|
// 缓存过期时间
|
|
expiration time.Duration
|
|
}
|
|
|
|
const (
|
|
minHistoryWindowSize = 16
|
|
maxHistoryWindowSize = 4096
|
|
)
|
|
|
|
func NewAgentCache(client *redis.Client) *AgentCache {
|
|
return &AgentCache{
|
|
client: client,
|
|
windowSize: 128,
|
|
expiration: 1 * time.Hour,
|
|
}
|
|
}
|
|
|
|
func (m *AgentCache) historyKey(sessionID string) string {
|
|
return fmt.Sprintf("smartflow:history:%s", sessionID)
|
|
}
|
|
|
|
func (m *AgentCache) historyWindowKey(sessionID string) string {
|
|
return fmt.Sprintf("smartflow:history_window:%s", sessionID)
|
|
}
|
|
|
|
func (m *AgentCache) normalizeWindowSize(size int) int {
|
|
if size < minHistoryWindowSize {
|
|
return minHistoryWindowSize
|
|
}
|
|
if size > maxHistoryWindowSize {
|
|
return maxHistoryWindowSize
|
|
}
|
|
return size
|
|
}
|
|
|
|
func (m *AgentCache) getSessionWindowSize(ctx context.Context, sessionID string) (int, error) {
|
|
windowKey := m.historyWindowKey(sessionID)
|
|
val, err := m.client.Get(ctx, windowKey).Result()
|
|
if err == redis.Nil {
|
|
return m.windowSize, nil
|
|
}
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
size, convErr := strconv.Atoi(val)
|
|
if convErr != nil {
|
|
return m.windowSize, nil
|
|
}
|
|
return m.normalizeWindowSize(size), nil
|
|
}
|
|
|
|
// SetSessionWindowSize 设置会话级窗口上限。
|
|
func (m *AgentCache) SetSessionWindowSize(ctx context.Context, sessionID string, size int) error {
|
|
normalized := m.normalizeWindowSize(size)
|
|
windowKey := m.historyWindowKey(sessionID)
|
|
return m.client.Set(ctx, windowKey, normalized, m.expiration).Err()
|
|
}
|
|
|
|
// EnforceHistoryWindow 按当前会话窗口强制修剪历史队列。
|
|
func (m *AgentCache) EnforceHistoryWindow(ctx context.Context, sessionID string) error {
|
|
size, err := m.getSessionWindowSize(ctx, sessionID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
key := m.historyKey(sessionID)
|
|
pipe := m.client.Pipeline()
|
|
pipe.LTrim(ctx, key, 0, int64(size-1))
|
|
pipe.Expire(ctx, key, m.expiration)
|
|
_, err = pipe.Exec(ctx)
|
|
return err
|
|
}
|
|
|
|
func (m *AgentCache) PushMessage(ctx context.Context, sessionID string, msg *schema.Message) error {
|
|
key := m.historyKey(sessionID)
|
|
size, err := m.getSessionWindowSize(ctx, sessionID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 1. 序列化 Eino 消息。
|
|
data, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return fmt.Errorf("marshal message failed: %w", err)
|
|
}
|
|
|
|
// 2. 使用 Pipeline 保证“写入+裁剪+续期”原子执行。
|
|
pipe := m.client.Pipeline()
|
|
pipe.LPush(ctx, key, data)
|
|
pipe.LTrim(ctx, key, 0, int64(size-1))
|
|
pipe.Expire(ctx, key, m.expiration)
|
|
|
|
_, err = pipe.Exec(ctx)
|
|
return err
|
|
}
|
|
|
|
func (m *AgentCache) GetHistory(ctx context.Context, sessionID string) ([]*schema.Message, error) {
|
|
key := m.historyKey(sessionID)
|
|
|
|
vals, err := m.client.LRange(ctx, key, 0, -1).Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(vals) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
messages := make([]*schema.Message, len(vals))
|
|
for i, val := range vals {
|
|
var msg schema.Message
|
|
if err := json.Unmarshal([]byte(val), &msg); err != nil {
|
|
return nil, err
|
|
}
|
|
// LRANGE 返回 [最新...最旧],这里反转成 [最旧...最新]
|
|
messages[len(vals)-1-i] = &msg
|
|
}
|
|
return messages, nil
|
|
}
|
|
|
|
// BackfillHistory 在缓存失效时,把历史消息一次性回填到 Redis。
|
|
func (m *AgentCache) BackfillHistory(ctx context.Context, sessionID string, messages []*schema.Message) error {
|
|
key := m.historyKey(sessionID)
|
|
size, err := m.getSessionWindowSize(ctx, sessionID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(messages) == 0 {
|
|
return m.client.Del(ctx, key).Err()
|
|
}
|
|
|
|
values := make([]interface{}, len(messages))
|
|
for i, msg := range messages {
|
|
data, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return fmt.Errorf("marshal failed at index %d: %w", i, err)
|
|
}
|
|
values[i] = data
|
|
}
|
|
|
|
pipe := m.client.Pipeline()
|
|
pipe.Del(ctx, key)
|
|
pipe.LPush(ctx, key, values...)
|
|
pipe.LTrim(ctx, key, 0, int64(size-1))
|
|
pipe.Expire(ctx, key, m.expiration)
|
|
_, err = pipe.Exec(ctx)
|
|
return err
|
|
}
|
|
|
|
func (m *AgentCache) ClearHistory(ctx context.Context, sessionID string) error {
|
|
historyKey := m.historyKey(sessionID)
|
|
windowKey := m.historyWindowKey(sessionID)
|
|
return m.client.Del(ctx, historyKey, windowKey).Err()
|
|
}
|
|
|
|
func (m *AgentCache) GetConversationStatus(ctx context.Context, sessionID string) (bool, error) {
|
|
key := fmt.Sprintf("smartflow:conversation_status:%s", sessionID)
|
|
n, err := m.client.Exists(ctx, key).Result()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return n == 1, nil
|
|
}
|
|
|
|
func (m *AgentCache) SetConversationStatus(ctx context.Context, sessionID string) error {
|
|
key := fmt.Sprintf("smartflow:conversation_status:%s", sessionID)
|
|
// 仅用于“存在性”标记:只有不存在时才写入,避免重复写。
|
|
return m.client.SetNX(ctx, key, 1, m.expiration).Err()
|
|
}
|
|
|
|
func (m *AgentCache) DeleteConversationStatus(ctx context.Context, sessionID string) error {
|
|
key := fmt.Sprintf("smartflow:conversation_status:%s", sessionID)
|
|
return m.client.Del(ctx, key).Err()
|
|
}
|
|
|
|
// ---- Compaction 缓存 ----
|
|
|
|
func (m *AgentCache) compactionKey(chatID string) string {
|
|
return fmt.Sprintf("smartflow:compaction:%s", chatID)
|
|
}
|
|
|
|
// SaveCompactionCache 将压缩摘要缓存到 Redis。
|
|
func (m *AgentCache) SaveCompactionCache(ctx context.Context, chatID string, summary string, watermark int) error {
|
|
key := m.compactionKey(chatID)
|
|
data, _ := json.Marshal(map[string]any{
|
|
"summary": summary,
|
|
"watermark": watermark,
|
|
})
|
|
return m.client.Set(ctx, key, data, m.expiration).Err()
|
|
}
|
|
|
|
// LoadCompactionCache 从 Redis 读取压缩摘要缓存。
|
|
func (m *AgentCache) LoadCompactionCache(ctx context.Context, chatID string) (summary string, watermark int, ok bool, err error) {
|
|
key := m.compactionKey(chatID)
|
|
val, err := m.client.Get(ctx, key).Result()
|
|
if err != nil {
|
|
if err == redis.Nil {
|
|
return "", 0, false, nil
|
|
}
|
|
return "", 0, false, err
|
|
}
|
|
var data struct {
|
|
Summary string `json:"summary"`
|
|
Watermark int `json:"watermark"`
|
|
}
|
|
if jsonErr := json.Unmarshal([]byte(val), &data); jsonErr != nil {
|
|
return "", 0, false, nil
|
|
}
|
|
return data.Summary, data.Watermark, true, nil
|
|
}
|