-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathhierarchy.go
More file actions
367 lines (330 loc) · 8.79 KB
/
hierarchy.go
File metadata and controls
367 lines (330 loc) · 8.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package summarize
import (
"context"
"fmt"
"strings"
"time"
"unicode"
)
// HierarchicalSummarizer implements Summarizer using rule-based compression.
// It does not require an LLM — compression is performed locally using
// extractive techniques (sentence selection, keyword extraction).
//
// For LLM-backed summarization, wrap this with an LLMSummarizer that
// overrides the compress method.
type HierarchicalSummarizer struct{}
// NewHierarchicalSummarizer creates a new summarizer.
func NewHierarchicalSummarizer() *HierarchicalSummarizer {
return &HierarchicalSummarizer{}
}
// Summarize compresses turns to fit within opts.MaxTokens.
// Turns are processed oldest-first; recent turns and high-importance turns
// are preserved at full fidelity.
func (s *HierarchicalSummarizer) Summarize(
ctx context.Context,
turns []Turn,
opts SummarizeOptions,
) ([]Turn, SummarizeStats, error) {
start := time.Now()
if opts.PreserveRecent < 0 {
opts.PreserveRecent = 10
}
if opts.ImportanceThreshold <= 0 {
opts.ImportanceThreshold = 0.7
}
if len(opts.AgeLevels) == 0 {
opts.AgeLevels = DefaultOptions().AgeLevels
}
// Score importance for turns that don't have it set.
ScoreTurns(turns)
// Count input tokens.
inputTokens := 0
for i := range turns {
turns[i].TokenCount = estimateTokens(turns[i].Content)
inputTokens += turns[i].TokenCount
}
stats := SummarizeStats{
InputTurns: len(turns),
InputTokens: inputTokens,
}
// Determine which turns to compress.
now := time.Now()
result := make([]Turn, len(turns))
copy(result, turns)
recentCutoff := len(result) - opts.PreserveRecent
if recentCutoff < 0 {
recentCutoff = 0
}
for i := range result {
t := &result[i]
// Always preserve recent turns (only when PreserveRecent > 0).
if opts.PreserveRecent > 0 && i >= recentCutoff {
stats.PreservedTurns++
continue
}
// Preserve high-importance turns at LevelFull or LevelParagraph.
maxLevel := s.maxLevelForAge(now.Sub(t.Timestamp), opts.AgeLevels)
if t.Importance >= opts.ImportanceThreshold && maxLevel > LevelParagraph {
maxLevel = LevelParagraph
}
if maxLevel <= t.Level {
// Already at or beyond target level.
stats.PreservedTurns++
continue
}
// Compress to target level.
if err := s.compressTo(t, maxLevel); err != nil {
return nil, stats, fmt.Errorf("compress turn %s: %w", t.ID, err)
}
t.TokenCount = estimateTokens(t.Content)
stats.CompressedTurns++
}
// If MaxTokens is set and we're still over budget, do a second pass
// compressing more aggressively from oldest to newest.
if opts.MaxTokens > 0 {
result = s.enforceTokenBudget(result, opts, recentCutoff)
}
// Compute output stats.
outputTokens := 0
for _, t := range result {
outputTokens += t.TokenCount
}
stats.OutputTurns = len(result)
stats.OutputTokens = outputTokens
if stats.InputTokens > 0 {
stats.ReductionPct = float64(stats.InputTokens-stats.OutputTokens) / float64(stats.InputTokens) * 100
}
stats.Latency = time.Since(start)
return result, stats, nil
}
// enforceTokenBudget does a second compression pass when still over budget.
// It progressively compresses oldest turns through all levels, including
// eviction (dropping turns entirely) as a last resort.
func (s *HierarchicalSummarizer) enforceTokenBudget(
turns []Turn,
opts SummarizeOptions,
recentCutoff int,
) []Turn {
total := 0
for _, t := range turns {
total += t.TokenCount
}
if total <= opts.MaxTokens {
return turns
}
// Compress oldest non-recent turns progressively through all levels.
for level := LevelParagraph; level <= LevelEvicted && total > opts.MaxTokens; level++ {
for i := range turns {
if opts.PreserveRecent > 0 && i >= recentCutoff {
break
}
t := &turns[i]
if t.Level >= level {
continue
}
if t.Importance >= opts.ImportanceThreshold && level > LevelParagraph {
continue
}
before := t.TokenCount
if level == LevelEvicted {
t.Level = LevelEvicted
t.Content = ""
t.TokenCount = 0
} else {
_ = s.compressTo(t, level)
t.TokenCount = estimateTokens(t.Content)
}
total -= before - t.TokenCount
if total <= opts.MaxTokens {
break
}
}
}
// Remove evicted turns from the slice.
out := turns[:0]
for _, t := range turns {
if t.Level != LevelEvicted {
out = append(out, t)
}
}
return out
}
// maxLevelForAge returns the maximum compression level for a given age.
func (s *HierarchicalSummarizer) maxLevelForAge(age time.Duration, levels []AgeLevel) Level {
max := LevelFull
for _, al := range levels {
if age >= al.After && al.MaxLevel > max {
max = al.MaxLevel
}
}
return max
}
// compressTo compresses a turn to the target level in-place.
// The original content is preserved in Turn.Original on first compression.
func (s *HierarchicalSummarizer) compressTo(t *Turn, target Level) error {
if t.Original == "" {
t.Original = t.Content
}
switch target {
case LevelParagraph:
t.Content = extractParagraphSummary(t.Original)
case LevelSentence:
t.Content = extractSentenceSummary(t.Original)
case LevelKeywords:
t.Content = extractKeywordSummary(t.Original)
}
t.Level = target
return nil
}
// extractParagraphSummary keeps the first paragraph and any code blocks.
func extractParagraphSummary(text string) string {
lines := strings.Split(text, "\n")
var out []string
inCode := false
paragraphDone := false
for _, line := range lines {
if strings.HasPrefix(line, "```") {
inCode = !inCode
out = append(out, line)
continue
}
if inCode {
out = append(out, line)
continue
}
if !paragraphDone {
out = append(out, line)
if line == "" && len(out) > 1 {
paragraphDone = true
}
}
}
result := strings.TrimSpace(strings.Join(out, "\n"))
if result == "" {
return truncate(text, 300)
}
return result
}
// extractSentenceSummary returns the first 1–2 sentences.
func extractSentenceSummary(text string) string {
// Strip code blocks first.
text = stripCodeBlocks(text)
sentences := splitSentences(text)
if len(sentences) == 0 {
return truncate(text, 150)
}
if len(sentences) == 1 {
return sentences[0]
}
return sentences[0] + " " + sentences[1]
}
// extractKeywordSummary extracts the most significant words.
func extractKeywordSummary(text string) string {
text = stripCodeBlocks(text)
words := strings.Fields(text)
var keywords []string
seen := map[string]bool{}
for _, w := range words {
w = strings.Trim(w, `.,;:!?"'()[]{}`)
lower := strings.ToLower(w)
if len(w) < 4 || isStopWord(lower) || seen[lower] {
continue
}
seen[lower] = true
keywords = append(keywords, w)
if len(keywords) >= 12 {
break
}
}
return strings.Join(keywords, ", ")
}
func stripCodeBlocks(text string) string {
var out strings.Builder
inCode := false
for _, line := range strings.Split(text, "\n") {
if strings.HasPrefix(line, "```") {
inCode = !inCode
continue
}
if !inCode {
out.WriteString(line)
out.WriteByte('\n')
}
}
return out.String()
}
func splitSentences(text string) []string {
var sentences []string
var cur strings.Builder
for _, r := range text {
cur.WriteRune(r)
if r == '.' || r == '!' || r == '?' {
s := strings.TrimSpace(cur.String())
if s != "" {
sentences = append(sentences, s)
}
cur.Reset()
}
}
if s := strings.TrimSpace(cur.String()); s != "" {
sentences = append(sentences, s)
}
return sentences
}
func truncate(s string, maxRunes int) string {
runes := []rune(s)
if len(runes) <= maxRunes {
return s
}
return string(runes[:maxRunes]) + "…"
}
func isStopWord(w string) bool {
return stopWords[w]
}
var stopWords = func() map[string]bool {
words := []string{
"the", "and", "for", "that", "this", "with", "from", "have",
"will", "been", "were", "they", "their", "there", "when",
"what", "which", "would", "could", "should", "about", "into",
"more", "also", "some", "than", "then", "just", "like",
}
m := map[string]bool{}
for _, w := range words {
m[w] = true
}
return m
}()
// DetectTurns segments a flat message list into Turn structs, assigning
// timestamps based on index when real timestamps are unavailable.
func DetectTurns(messages []struct {
Role string
Content string
}) []Turn {
now := time.Now()
turns := make([]Turn, len(messages))
for i, m := range messages {
turns[i] = Turn{
ID: fmt.Sprintf("turn-%d", i),
Role: m.Role,
Content: m.Content,
Original: m.Content,
Timestamp: now.Add(-time.Duration(len(messages)-i) * time.Minute),
Level: LevelFull,
TokenCount: estimateTokens(m.Content),
}
}
return turns
}
// TotalTokens returns the sum of token counts across all turns.
func TotalTokens(turns []Turn) int {
total := 0
for _, t := range turns {
total += t.TokenCount
}
return total
}
// isLetter is used by keyword extraction.
func isLetter(r rune) bool {
return unicode.IsLetter(r)
}
var _ = isLetter // suppress unused warning