MCPcopy Create free account
hub / github.com/astercloud/aster / Compress

Method Compress

pkg/context/compression_strategy.go:118–178  ·  view source on GitHub ↗

Compress 实现 CompressionStrategy 接口

(
	ctx context.Context,
	messages []Message,
	config WindowManagerConfig,
)

Source from the content-addressed store, hash-verified

116
117// Compress 实现 CompressionStrategy 接口
118func (s *PriorityBasedStrategy) Compress(
119 ctx context.Context,
120 messages []Message,
121 config WindowManagerConfig,
122) ([]Message, error) {
123 if len(messages) <= s.targetSize {
124 return messages, nil
125 }
126
127 // 计算所有消息的优先级
128 withPriority := CalculateMessagePriorities(ctx, messages, s.priorityCalculator)
129
130 // 保留的消息索引
131 keepIndices := make(map[int]bool)
132
133 // 1. 始终保留 system 消息
134 if config.AlwaysKeepSystem {
135 for i, msg := range messages {
136 if msg.Role == "system" {
137 keepIndices[i] = true
138 }
139 }
140 }
141
142 // 2. 始终保留最近的 N 条消息
143 recentCount := min(config.AlwaysKeepRecent, len(messages))
144 for i := len(messages) - recentCount; i < len(messages); i++ {
145 keepIndices[i] = true
146 }
147
148 // 3. 按优先级排序,选择最高优先级的消息
149 SortMessagesByPriority(withPriority, true) // 降序排序
150
151 remainingSlots := s.targetSize - len(keepIndices)
152 for _, msgWithPri := range withPriority {
153 if remainingSlots <= 0 {
154 break
155 }
156
157 // 找到该消息的原始索引
158 for i, msg := range messages {
159 if msg.Role == msgWithPri.Message.Role && msg.Content == msgWithPri.Message.Content {
160 if !keepIndices[i] {
161 keepIndices[i] = true
162 remainingSlots--
163 break
164 }
165 }
166 }
167 }
168
169 // 构建结果(保持原始顺序)
170 result := []Message{}
171 for i, msg := range messages {
172 if keepIndices[i] {
173 result = append(result, msg)
174 }
175 }

Calls 3

SortMessagesByPriorityFunction · 0.85
minFunction · 0.50