Compress 实现 CompressionStrategy 接口
( ctx context.Context, messages []Message, config WindowManagerConfig, )
| 39 | |
| 40 | // Compress 实现 CompressionStrategy 接口 |
| 41 | func (s *SlidingWindowStrategy) Compress( |
| 42 | ctx context.Context, |
| 43 | messages []Message, |
| 44 | config WindowManagerConfig, |
| 45 | ) ([]Message, error) { |
| 46 | if len(messages) <= s.windowSize { |
| 47 | // 不需要压缩 |
| 48 | return messages, nil |
| 49 | } |
| 50 | |
| 51 | // 保留的消息索引 |
| 52 | keepIndices := make(map[int]bool) |
| 53 | |
| 54 | // 1. 始终保留 system 消息 |
| 55 | if config.AlwaysKeepSystem { |
| 56 | for i, msg := range messages { |
| 57 | if msg.Role == "system" { |
| 58 | keepIndices[i] = true |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // 2. 始终保留最近的 N 条消息 |
| 64 | recentCount := min(config.AlwaysKeepRecent, len(messages)) |
| 65 | for i := len(messages) - recentCount; i < len(messages); i++ { |
| 66 | keepIndices[i] = true |
| 67 | } |
| 68 | |
| 69 | // 3. 从剩余消息中选择最新的填充到窗口大小 |
| 70 | remainingSlots := s.windowSize - len(keepIndices) |
| 71 | if remainingSlots > 0 { |
| 72 | for i := len(messages) - 1; i >= 0 && remainingSlots > 0; i-- { |
| 73 | if !keepIndices[i] { |
| 74 | keepIndices[i] = true |
| 75 | remainingSlots-- |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // 构建结果(保持原始顺序) |
| 81 | result := []Message{} |
| 82 | for i, msg := range messages { |
| 83 | if keepIndices[i] { |
| 84 | result = append(result, msg) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | return result, nil |
| 89 | } |
| 90 | |
| 91 | // PriorityBasedStrategy 基于优先级的压缩策略 |
| 92 | // 优先保留高优先级消息 |