-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
392 lines (337 loc) · 8.9 KB
/
context.go
File metadata and controls
392 lines (337 loc) · 8.9 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package iteragent
import (
"fmt"
"math"
"strings"
"sync"
"time"
)
const charsPerToken = 4
func EstimateTokens(text string) int {
return len(text) / charsPerToken
}
func EstimateMessageTokens(msg Message) int {
if msg.Content == "" {
return 0
}
tokens := EstimateTokens(msg.Content) + 4
return tokens
}
func EstimateTotalTokens(messages []Message) int {
total := 0
for _, msg := range messages {
total += EstimateMessageTokens(msg)
}
return total
}
type ContextTracker struct {
mu sync.Mutex
inputTokens int
outputTokens int
estimatedTokens int
lastRealUsage *Usage
lastUpdate time.Time
}
func NewContextTracker() *ContextTracker {
return &ContextTracker{
lastUpdate: time.Now(),
}
}
func (c *ContextTracker) UpdateWithRealUsage(usage *Usage) {
c.mu.Lock()
defer c.mu.Unlock()
c.inputTokens = usage.InputTokens
c.outputTokens = usage.OutputTokens
c.lastRealUsage = usage
c.lastUpdate = time.Now()
c.estimatedTokens = 0
}
func (c *ContextTracker) AddEstimatedTokens(tokens int) {
c.mu.Lock()
defer c.mu.Unlock()
c.estimatedTokens += tokens
}
func (c *ContextTracker) TotalTokens() int {
c.mu.Lock()
defer c.mu.Unlock()
realTotal := 0
if c.lastRealUsage != nil {
realTotal = c.lastRealUsage.TotalTokens
}
return realTotal + c.estimatedTokens
}
func (c *ContextTracker) InputTokens() int {
c.mu.Lock()
defer c.mu.Unlock()
if c.lastRealUsage != nil {
return c.lastRealUsage.InputTokens
}
return 0
}
func (c *ContextTracker) OutputTokens() int {
c.mu.Lock()
defer c.mu.Unlock()
if c.lastRealUsage != nil {
return c.lastRealUsage.OutputTokens
}
return 0
}
func (c *ContextTracker) CacheHitRate() float64 {
c.mu.Lock()
defer c.mu.Unlock()
if c.lastRealUsage != nil {
return c.lastRealUsage.CacheHitRate()
}
return 0.0
}
// ContextConfig controls context compaction behaviour.
type ContextConfig struct {
MaxTokens int
KeepRecent int
KeepFirst int
ToolOutputMaxLines int
WarningThreshold float64
Strategy CompactionStrategy
}
// DefaultContextConfig returns sensible defaults for context management.
func DefaultContextConfig() ContextConfig {
return ContextConfig{
MaxTokens: 100000,
KeepRecent: 10,
KeepFirst: 2,
ToolOutputMaxLines: 50,
WarningThreshold: 0.8,
Strategy: &DefaultCompactionStrategy{},
}
}
func (c *ContextConfig) WarningTokens() int {
threshold := c.WarningThreshold
if threshold == 0 {
threshold = 0.8
}
return int(float64(c.MaxTokens) * threshold)
}
type ExecutionLimits struct {
MaxTurns int
MaxTokens int
MaxDuration time.Duration
}
func DefaultExecutionLimits() ExecutionLimits {
return ExecutionLimits{
MaxTurns: 50,
MaxTokens: 1000000,
MaxDuration: 10 * time.Minute,
}
}
type ExecutionTracker struct {
mu sync.Mutex
turnCount int
totalTokens int
startTime time.Time
limits ExecutionLimits
}
func NewExecutionTracker(limits ExecutionLimits) *ExecutionTracker {
return &ExecutionTracker{
startTime: time.Now(),
limits: limits,
}
}
func (e *ExecutionTracker) IncrementTurn(tokens int) {
e.mu.Lock()
defer e.mu.Unlock()
e.turnCount++
e.totalTokens += tokens
}
func (e *ExecutionTracker) TurnCount() int {
e.mu.Lock()
defer e.mu.Unlock()
return e.turnCount
}
func (e *ExecutionTracker) TotalTokens() int {
e.mu.Lock()
defer e.mu.Unlock()
return e.totalTokens
}
func (e *ExecutionTracker) Elapsed() time.Duration {
e.mu.Lock()
defer e.mu.Unlock()
return time.Since(e.startTime)
}
func (e *ExecutionTracker) AtTurnLimit() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.turnCount >= e.limits.MaxTurns
}
func (e *ExecutionTracker) AtTokenLimit() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.totalTokens >= e.limits.MaxTokens
}
func (e *ExecutionTracker) AtDurationLimit() bool {
e.mu.Lock()
defer e.mu.Unlock()
return time.Since(e.startTime) >= e.limits.MaxDuration
}
func (e *ExecutionTracker) ShouldContinue() bool {
return !e.AtTurnLimit() && !e.AtTokenLimit() && !e.AtDurationLimit()
}
// isToolResultMessage returns true if the message is a tool result (role "tool" or
// user message containing "Tool ... result:").
func isToolResultMessage(msg Message) bool {
if msg.Role == "tool" {
return true
}
if msg.Role == "user" && strings.Contains(msg.Content, " result:") {
return true
}
return false
}
// truncateLines keeps the first headN and last tailN lines of content, joining
// them with a truncation notice. Returns original if total lines <= headN+tailN.
func truncateLines(content string, headN, tailN int) string {
lines := strings.Split(content, "\n")
total := len(lines)
keep := headN + tailN
if total <= keep {
return content
}
dropped := total - keep
head := lines[:headN]
tail := lines[total-tailN:]
return strings.Join(head, "\n") +
fmt.Sprintf("\n\n[... %d lines truncated ...]\n\n", dropped) +
strings.Join(tail, "\n")
}
// CompactMessagesTiered applies a 3-tier compaction strategy to messages.
//
// Level 1 — Truncate tool outputs (head+tail):
//
// Find messages with Role == "tool" or user messages that look like tool results.
// Truncate content to ToolOutputMaxLines lines (head half + tail half).
//
// Level 2 — Summarize old turns:
//
// Keep the last KeepRecent messages intact.
// Replace older assistant messages with a summary; drop their tool results.
//
// Level 3 — Drop middle:
//
// Keep first KeepFirst and last KeepRecent messages; drop everything in between.
func CompactMessagesTiered(messages []Message, cfg ContextConfig) []Message {
if len(messages) <= 1 {
return messages
}
maxTokens := cfg.MaxTokens
keepRecent := cfg.KeepRecent
keepFirst := cfg.KeepFirst
maxLines := cfg.ToolOutputMaxLines
if keepRecent <= 0 {
keepRecent = 10
}
if keepFirst <= 0 {
keepFirst = 2
}
if maxLines <= 0 {
maxLines = 50
}
currentTokens := EstimateTotalTokens(messages)
if currentTokens <= maxTokens {
return messages
}
// ── Level 1: Truncate tool outputs ────────────────────────────────────────
result := make([]Message, len(messages))
copy(result, messages)
headN := maxLines / 2
tailN := maxLines - headN
for i, msg := range result {
if isToolResultMessage(msg) {
result[i].Content = truncateLines(msg.Content, headN, tailN)
}
}
currentTokens = EstimateTotalTokens(result)
if currentTokens <= maxTokens {
return result
}
// ── Level 2: Summarize old turns ──────────────────────────────────────────
// Determine the boundary: keep the last keepRecent messages intact.
cutoff := len(result) - keepRecent
if cutoff < 0 {
cutoff = 0
}
var compacted []Message
i := 0
for i < cutoff {
msg := result[i]
if msg.Role == "assistant" {
// Count tool calls embedded in response.
calls := ParseToolCalls(msg.Content)
var summary string
if len(calls) > 0 {
summary = fmt.Sprintf("[Assistant used %d tool(s)]", len(calls))
} else {
if len(msg.Content) > 200 {
summary = msg.Content[:200]
} else {
summary = msg.Content
}
}
compacted = append(compacted, Message{Role: "assistant", Content: summary})
// Skip adjacent tool result messages.
i++
for i < cutoff && isToolResultMessage(result[i]) {
i++
}
} else {
compacted = append(compacted, msg)
i++
}
}
// Append the recent tail intact.
compacted = append(compacted, result[cutoff:]...)
currentTokens = EstimateTotalTokens(compacted)
if currentTokens <= maxTokens {
return compacted
}
// ── Level 3: Drop middle ───────────────────────────────────────────────────
if len(compacted) <= keepFirst+keepRecent {
return compacted
}
head := compacted[:keepFirst]
tail := compacted[len(compacted)-keepRecent:]
return append(head, tail...)
}
type MessageSummary struct {
Content string
TokenCount int
}
func SummarizeMessages(messages []Message) []Message {
if len(messages) <= 10 {
return messages
}
var summary []Message
summary = append(summary, messages[0])
midStart := len(messages) / 3
midEnd := 2 * len(messages) / 3
if midStart < len(messages) && midEnd > midStart {
midSection := messages[midStart:midEnd]
summary = append(summary, Message{
Role: "system",
Content: fmt.Sprintf("[%d messages omitted]", len(midSection)),
})
}
summary = append(summary, messages[len(messages)-1:]...)
return summary
}
func TruncateToolOutput(content string, maxTokens int) string {
maxChars := maxTokens * charsPerToken
if len(content) <= maxChars {
return content
}
return content[:maxChars] + "\n\n[Output truncated]"
}
func CalculateTokenBuffer(currentTokens, maxTokens int) int {
return maxTokens - currentTokens
}
func EstimateResponseTokens(availableTokens int) int {
return int(math.Min(float64(availableTokens*2/3), 4096))
}