Compress 实现 CompressionStrategy 接口
( ctx context.Context, messages []Message, config WindowManagerConfig, )
| 202 | |
| 203 | // Compress 实现 CompressionStrategy 接口 |
| 204 | func (s *TokenBasedStrategy) Compress( |
| 205 | ctx context.Context, |
| 206 | messages []Message, |
| 207 | config WindowManagerConfig, |
| 208 | ) ([]Message, error) { |
| 209 | // 计算目标 Token 数 |
| 210 | targetTokens := int(float64(config.Budget.AvailableTokens()) * s.targetUsage) |
| 211 | |
| 212 | // 计算当前 Token 数 |
| 213 | currentTokens, err := s.tokenCounter.EstimateMessages(ctx, messages) |
| 214 | if err != nil { |
| 215 | return nil, fmt.Errorf("failed to estimate current tokens: %w", err) |
| 216 | } |
| 217 | |
| 218 | // 如果已经在目标范围内,不需要压缩 |
| 219 | if currentTokens <= targetTokens { |
| 220 | return messages, nil |
| 221 | } |
| 222 | |
| 223 | // 保留的消息索引(从后往前) |
| 224 | keepIndices := make(map[int]bool) |
| 225 | |
| 226 | // 1. 始终保留 system 消息 |
| 227 | if config.AlwaysKeepSystem { |
| 228 | for i, msg := range messages { |
| 229 | if msg.Role == "system" { |
| 230 | keepIndices[i] = true |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // 2. 始终保留最近的 N 条消息 |
| 236 | recentCount := min(config.AlwaysKeepRecent, len(messages)) |
| 237 | for i := len(messages) - recentCount; i < len(messages); i++ { |
| 238 | keepIndices[i] = true |
| 239 | } |
| 240 | |
| 241 | // 3. 从后往前逐步添加消息,直到达到 Token 目标 |
| 242 | for i := len(messages) - 1; i >= 0; i-- { |
| 243 | if keepIndices[i] { |
| 244 | continue // 已经保留 |
| 245 | } |
| 246 | |
| 247 | // 尝试添加这条消息 |
| 248 | testIndices := make(map[int]bool) |
| 249 | for k := range keepIndices { |
| 250 | testIndices[k] = true |
| 251 | } |
| 252 | testIndices[i] = true |
| 253 | |
| 254 | // 构建测试消息列表 |
| 255 | testMessages := []Message{} |
| 256 | for j := range messages { |
| 257 | if testIndices[j] { |
| 258 | testMessages = append(testMessages, messages[j]) |
| 259 | } |
| 260 | } |
| 261 |