-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontextwindow.go
More file actions
914 lines (807 loc) · 27.2 KB
/
contextwindow.go
File metadata and controls
914 lines (807 loc) · 27.2 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
// Package contextwindow implements sqlite-backed context windows for LLM sessions,
// with opt-in LLM summarization for compaction, token count tracking, and a simple
// tool call abstraction.
//
// # Abbreviated usage
//
// model, err := NewOpenAIResponsesModel(shared.ResponsesModel4o)
// if err != nil {
// log.Fatalf("Failed to create model: %v", err)
// }
//
// cw, err := contextwindow.New(model, nil, "")
// if err != nil {
// log.Fatalf("Failed to create context window: %v", err)
// }
// defer cw.Close()
//
// if err := cw.AddPrompt(ctx, "how's the weather?"); err != nil {
// log.Fatalf("Failed to add prompt: %v", err)
// }
//
// response, err := cw.CallModel(ctx)
// if err != nil {
// log.Fatalf("Failed to call model: %v", err)
// }
//
// fmt.Printf("response: %s\n", response)
//
// # System prompts
//
// Use [ContextWindow.SetSystemPrompt] to provide a system prompt for each
// conversation.
//
// # Tool calling
//
// Instruct LLMs to call tools locally with [ContextWindow.AddTool] (and [NewTool]).
//
// lsTool := contextwindow.NewTool("list_files", `
// This tool lists files in the specified directory.
// `).AddStringParameter("directory", "Directory to list", true)
//
// cw.AddTool(lsTool, contextwindow.ToolRunnerFunc(func context.Context,
// args json.RawMessage) (string, error) {
// var treq struct {
// Dir string `json:"directory"`
// }
// json.Unmarshal(args, &treq)
// // actually run ls, or pretend to
// return "here\nare\nsome\nfiles.exe\n", nil
// })
//
// You can selectively enable and disable tools with [ContextWindow.CallModelWithOpts].
//
// Tool calls are very sensitive to the descriptions provided of the tool and arguments
// (the example up there is way too simple). Treat descriptions like part of the system
// prompt; tell the agent what to do.
//
// # Summarization
//
// Models have context token limits (we use [github.com/peterheb/gotoken/cl100kbase] to
// track usage); both input and output tokens count towards the limit.
//
// You can provide a summarizer model to automatically compact your context window:
//
// summarizerModel, err := openai.New(apiKey, "gpt-3.5-turbo")
// if err != nil {
// log.Fatalf("Failed to create summarizer: %v", err)
// }
//
// cw, err := contextwindow.New(model, summarizerModel, "")
//
// And then "compress" your context with [ContextWindow.SummarizeLiveContent].
//
// # Under the hood
//
// A context window is just a list of strings, representing the history of a
// "conversation" with an LLM. The "live" strings in a conversation will be
// fed to the LLM on every call; we retain the "unalive" strings in records
// so that tool calls can fetch them later.
//
// LLM conversations are stored in SQLite. If you don't care about persistant
// storage for your context, just specify ":memory:" as your database path.
//
// # Threading and Fallback Behavior
//
// When server-side threading is enabled, the library attempts to use
// response_id-based threading for efficiency. However, several conditions
// can cause automatic fallback to client-side threading:
//
// The response_id chain is broken or invalid
// Tool calls are present (they break server-side threading)
// The model's threading API call fails
// - The context has no previous response_id (first call)
//
// back is automatic and transparent - conversations continue normally
// g full message history. Check logs for threading decisions.
//
// # Thread Safety
//
// ContextWindow write operations (AddPrompt, SwitchContext, SetMaxTokens, etc.)
// require external coordination when used concurrently. However, you can use
// ContextWindow.Reader() to get a thread-safe read-only view:
//
// reader := cw.Reader()
// go updateUI(reader) // safe for concurrent use
// go updateMetrics(reader) // safe for concurrent use
//
// // Meanwhile, main thread can safely modify state:
// cw.SwitchContext("new-context")
// cw.SetMaxTokens(8192)
//
// ContextReader provides access to read operations like LiveRecords(), TokenUsage(),
// and context querying, all of which are safe for concurrent use.
package contextwindow
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/peterheb/gotoken"
_ "github.com/peterheb/gotoken/cl100kbase"
_ "modernc.org/sqlite"
)
// Model abstracts out an LLM client library.
type Model interface {
// Call sends messages, returns model reply and token usage.
Call(ctx context.Context, inputs []Record) (events []Record, tokensUsed int, err error)
}
// ServerSideThreadingCapable is an optional interface for models that support server-side threading.
type ServerSideThreadingCapable interface {
// CallWithThreading calls the model with optional server-side threading.
CallWithThreading(
ctx context.Context,
useServerSideThreading bool,
lastResponseID *string,
inputs []Record,
) (events []Record, responseID *string, tokensUsed int, err error)
}
// ToolCapable is an optional interface that models can implement
// to receive a ToolExecutor for handling tool calls.
type ToolCapable interface {
SetToolExecutor(ToolExecutor)
}
// MiddlewareCapable is an optional interface that models can implement
// to receive middleware updates.
type MiddlewareCapable interface {
SetMiddleware([]Middleware)
}
// CallOptsCapable is an optional interface that models can implement
// to support call options like disabling tools.
type CallOptsCapable interface {
CallWithOpts(ctx context.Context, inputs []Record, opts CallModelOpts) (events []Record, tokensUsed int, err error)
CallWithThreadingAndOpts(
ctx context.Context,
useServerSideThreading bool,
lastResponseID *string,
inputs []Record,
opts CallModelOpts,
) (events []Record, responseID *string, tokensUsed int, err error)
}
// Middleware allows hooking into tool call lifecycle events.
type Middleware interface {
// OnToolCall is invoked when a tool is about to be called.
OnToolCall(ctx context.Context, name, args string)
// OnToolResult is invoked when a tool call completes.
OnToolResult(ctx context.Context, name, result string, err error)
}
// ContextWindow holds our LLM context manager state.
type ContextWindow struct {
model Model
db *sql.DB
maxTokens int
summarizer Summarizer
summarizerPrompt string
middleware []Middleware
metrics *Metrics
currentContext string
registeredTools map[string]ToolDefinition
toolRunners map[string]ToolRunner
}
// ContextReader provides thread-safe read access to context window data.
// It's a thin proxy that forwards calls to safe read methods on the
// underlying ContextWindow.
//
// All methods on ContextReader are safe for concurrent use by multiple
// goroutines, even while the original ContextWindow is being modified.
type ContextReader struct {
cw *ContextWindow // reference to underlying context window
}
// NewContextDB opens a database to store context windows in (pass
// ":memory:" as the name for a transient database), and migrates
// its schema. You'll need to do this before creating context windows.
func NewContextDB(dbpath string) (*sql.DB, error) {
db, err := sql.Open("sqlite", dbpath)
if err != nil {
return nil, fmt.Errorf("open db: %w", err)
}
if err = InitializeSchema(db); err != nil {
db.Close()
return nil, fmt.Errorf("init schema: %w", err)
}
return db, nil
}
// NewContextWindow initializes a ContextWindow with an existing database
// connection and a specific context. If the context doesn't exist, it will be created.
// The caller is responsible for closing the database. You can provide an
// empty context name, in which case we'll generate a UUID for it.
func NewContextWindow(
db *sql.DB,
model Model,
contextName string,
) (*ContextWindow, error) {
return NewContextWindowWithThreading(db, model, contextName, false)
}
// NewContextWindowWithThreading creates a context window with specified threading mode.
func NewContextWindowWithThreading(
db *sql.DB,
model Model,
contextName string,
useServerSideThreading bool,
) (*ContextWindow, error) {
if contextName == "" {
contextName = uuid.New().String()
}
cw := &ContextWindow{
model: model,
db: db,
maxTokens: 4096,
metrics: &Metrics{},
currentContext: contextName,
registeredTools: make(map[string]ToolDefinition),
toolRunners: make(map[string]ToolRunner),
}
// If the model supports tool execution, configure it
if toolCapable, ok := model.(ToolCapable); ok {
toolCapable.SetToolExecutor(cw)
}
_, err := GetContextByName(db, contextName)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
_, err = CreateContextWithThreading(db, contextName, useServerSideThreading)
if err != nil {
return nil, fmt.Errorf("create context: %w", err)
}
} else {
return nil, fmt.Errorf("get context: %w", err)
}
}
return cw, nil
}
// Close closes the database connection. Only call this if you opened the database
// using NewContextWindow or NewContextWindowWithContext. If you used
// NewContextWindowWithDB, you should close the database yourself.
func (cw *ContextWindow) Close() error {
if cw.db == nil {
return nil
}
return cw.db.Close()
}
// AddPrompt logs a user prompt to the current context.
func (cw *ContextWindow) AddPrompt(text string) error {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return fmt.Errorf("add prompt: %w", err)
}
_, err = InsertRecord(cw.db, contextID, Prompt, text, true)
if err != nil {
return fmt.Errorf("add prompt: %w", err)
}
return nil
}
// AddToolCall logs a tool invocation to the current context.
func (cw *ContextWindow) AddToolCall(name, args string) error {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return fmt.Errorf("add tool call: %w", err)
}
content := fmt.Sprintf("%s(%s)", name, args)
_, err = InsertRecord(cw.db, contextID, ToolCall, content, true)
if err != nil {
return fmt.Errorf("add tool call: %w", err)
}
return nil
}
// AddToolOutput logs a tool's output to the current context.
func (cw *ContextWindow) AddToolOutput(output string) error {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return fmt.Errorf("add tool output: %w", err)
}
_, err = InsertRecord(cw.db, contextID, ToolOutput, output, true)
if err != nil {
return fmt.Errorf("add tool output: %w", err)
}
return nil
}
// SetRecordLiveStateByRange updates the live status of records in the specified range.
// Indices are based on the current LiveRecords() slice, with both start and end inclusive.
// This allows selective marking of context elements as active (live=true) or
// inactive (live=false) based on their position in the conversation.
//
// Examples:
//
// SetRecordLiveStateByRange(2, 4, false) // marks records at indices 2, 3, 4 as dead
// SetRecordLiveStateByRange(5, 5, false) // marks only record at index 5 as dead
func (cw *ContextWindow) SetRecordLiveStateByRange(startIndex, endIndex int, live bool) error {
if startIndex < 0 || endIndex < startIndex {
return fmt.Errorf("invalid range: startIndex=%d, endIndex=%d", startIndex, endIndex)
}
liveRecords, err := cw.LiveRecords()
if err != nil {
return fmt.Errorf("get live records: %w", err)
}
if startIndex >= len(liveRecords) {
return fmt.Errorf("startIndex %d out of range (have %d records)", startIndex, len(liveRecords))
}
if endIndex >= len(liveRecords) {
return fmt.Errorf("endIndex %d out of range (have %d records)", endIndex, len(liveRecords))
}
tx, err := cw.db.Begin()
if err != nil {
return fmt.Errorf("set record live state by range: %w", err)
}
defer tx.Rollback()
liveValue := 0
if live {
liveValue = 1
}
for i := startIndex; i <= endIndex; i++ {
recordID := liveRecords[i].ID
_, err = tx.Exec(`UPDATE records SET live = ? WHERE id = ?`, liveValue, recordID)
if err != nil {
return fmt.Errorf("set record %d live state: %w", recordID, err)
}
}
return tx.Commit()
}
// SetSystemPrompt sets the system prompt for the current context.
func (cw *ContextWindow) SetSystemPrompt(text string) error {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return fmt.Errorf("set system prompt: %w", err)
}
tx, err := cw.db.Begin()
if err != nil {
return fmt.Errorf("set system prompt: %w", err)
}
defer tx.Rollback()
_, err = tx.Exec(`UPDATE records SET live = 0 WHERE context_id = ? AND source = ?`, contextID, SystemPrompt)
if err != nil {
return fmt.Errorf("set system prompt: %w", err)
}
_, err = insertRecordTx(tx, contextID, SystemPrompt, text, true)
if err != nil {
return fmt.Errorf("set system prompt: %w", err)
}
return tx.Commit()
}
// AddMiddleware registers middleware to hook into tool call events.
func (cw *ContextWindow) AddMiddleware(m Middleware) {
cw.middleware = append(cw.middleware, m)
// If the model supports middleware, update it
if middlewareCapable, ok := cw.model.(MiddlewareCapable); ok {
middlewareCapable.SetMiddleware(cw.middleware)
}
}
// LiveRecords retrieves all "live" records from the context. This is an
// important function, since this is usually what you want to call to get
// what's currently meaningful in your context --- it's what gets sent
// to the LLM.
func (cw *ContextWindow) LiveRecords() ([]Record, error) {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return nil, fmt.Errorf("live records: %w", err)
}
recs, err := ListLiveRecords(cw.db, contextID)
if err != nil {
return nil, fmt.Errorf("live records: %w", err)
}
return recs, nil
}
// CallModelOpts contains options for model calls.
type CallModelOpts struct {
DisableTools bool
}
// CallModel drives an LLM. It composes live messages, invokes cw.model.Call,
// logs the response, updates token count, and triggers compaction.
func (cw *ContextWindow) CallModel(ctx context.Context) (string, error) {
return cw.CallModelWithOpts(ctx, CallModelOpts{})
}
func (cw *ContextWindow) shouldAttemptServerSideThreading(
ci Context,
recs []Record,
) (should bool, reason string /* not using this yet but seems like a good idea */) {
if !ci.UseServerSideThreading {
return false, "server-side threading not enabled for context"
}
_, ok := cw.model.(ServerSideThreadingCapable)
if !ok {
return false, "model does not support server-side threading"
}
if ci.LastResponseID == nil || *ci.LastResponseID == "" {
return false, "no last_response_id available (first call or chain broken)"
}
valid, reason := ValidateResponseIDChain(cw.db, ci)
if !valid {
return false, fmt.Sprintf("response_id chain invalid: %s", reason)
}
return true, "preconditions met"
}
// CallModelWithOpts drives an LLM with options. It composes live messages, invokes cw.model.Call,
// logs the response, updates token count, and triggers compaction.
func (cw *ContextWindow) CallModelWithOpts(ctx context.Context, opts CallModelOpts) (string, error) {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return "", fmt.Errorf("call model in context: %w", err)
}
// Get current context info to check threading mode
contextInfo, err := GetContext(cw.db, contextID)
if err != nil {
return "", fmt.Errorf("get context info: %w", err)
}
recs, err := ListLiveRecords(cw.db, contextID)
if err != nil {
return "", fmt.Errorf("list live records: %w", err)
}
var (
events []Record
tokensUsed int
responseID *string
)
attemptServerSide, _ := cw.shouldAttemptServerSideThreading(contextInfo, recs)
if attemptServerSide {
threadingModel := cw.model.(ServerSideThreadingCapable)
var err error
if optsModel, ok := threadingModel.(CallOptsCapable); ok {
events, responseID, tokensUsed, err = optsModel.CallWithThreadingAndOpts(
ctx,
true,
contextInfo.LastResponseID,
recs,
opts,
)
} else {
events, responseID, tokensUsed, err = threadingModel.CallWithThreading(
ctx,
true,
contextInfo.LastResponseID,
recs,
)
}
if err != nil {
// Fall through to client-side threading
attemptServerSide = false
}
}
// Use client-side threading (either as fallback or default)
if !attemptServerSide {
if optsModel, ok := cw.model.(CallOptsCapable); ok {
events, tokensUsed, err = optsModel.CallWithOpts(ctx, recs, opts)
} else {
events, tokensUsed, err = cw.model.Call(ctx, recs)
}
if err != nil {
if contextInfo.UseServerSideThreading {
return "", fmt.Errorf("call model (fallback to client-side threading): %w", err)
}
return "", fmt.Errorf("call model: %w", err)
}
// Client-side threading doesn't return responseID
responseID = nil
}
cw.metrics.Add(tokensUsed)
var lastMsg string
for _, event := range events {
_, err = InsertRecordWithResponseID(
cw.db,
contextID,
event.Source,
event.Content,
event.Live,
event.ResponseID,
)
if err != nil {
return "", fmt.Errorf("insert model response: %w", err)
}
lastMsg = event.Content
}
if responseID != nil {
err = UpdateContextLastResponseID(cw.db, contextID, *responseID)
if err != nil {
return lastMsg, fmt.Errorf("update last response ID: %w", err)
}
}
return lastMsg, nil
}
func (cw *ContextWindow) TotalTokens() int {
return cw.metrics.Total()
}
// LiveTokens estimates the total number of tokens in all "live" messages
// in the context. Depending on your model, at some threshold of tokens
// you'll want either to summarize, or to start a new context window.
func (cw *ContextWindow) LiveTokens() (int, error) {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return 0, fmt.Errorf("live tokens in context: %w", err)
}
recs, err := ListLiveRecords(cw.db, contextID)
if err != nil {
return 0, fmt.Errorf("list live records: %w", err)
}
var n int
for _, r := range recs {
n += r.EstTokens
}
return n, nil
}
// Metrics tracks token usage across model calls.
type Metrics struct {
mu sync.Mutex
total int
}
func (m *Metrics) Add(n int) {
m.mu.Lock()
m.total += n
m.mu.Unlock()
}
func (m *Metrics) Total() int {
m.mu.Lock()
n := m.total
m.mu.Unlock()
return n
}
// TokenUsage provides a snapshot of current token usage for UI display.
type TokenUsage struct {
Live int // tokens currently in context window
Total int // cumulative tokens used across all calls
Max int // maximum tokens allowed in context window
Percent float64 // live/max as percentage (0.0-1.0)
}
// TokenUsage returns current token usage metrics optimized for UI display.
func (cw *ContextWindow) TokenUsage() (TokenUsage, error) {
live, err := cw.LiveTokens()
if err != nil {
return TokenUsage{}, err
}
percent := 0.0
if cw.maxTokens > 0 {
percent = float64(live) / float64(cw.maxTokens)
}
return TokenUsage{
Live: live,
Total: cw.metrics.Total(),
Max: cw.maxTokens,
Percent: percent,
}, nil
}
// ContextStats provides metrics for a specific context without expensive computation.
type ContextStats struct {
LiveTokens int // tokens in live records
TotalRecords int // total number of records
LiveRecords int // number of live records
LastActivity *time.Time // timestamp of most recent record, nil if no records
}
type TokenReporter interface {
TotalTokens() int
LiveTokens() (int, error)
TokenUsage() (TokenUsage, error)
}
func tokenCount(s string) int {
tokOnce.Do(func() {
tok, tokErr = gotoken.GetTokenizer("cl100k_base")
})
if tokErr != nil {
return len(strings.Fields(s))
}
return tok.Count(s)
}
var (
tok gotoken.Tokenizer
tokOnce sync.Once
tokErr error
)
// Context management methods
// CreateContext creates a new named context window.
func (cw *ContextWindow) CreateContext(name string) error {
_, err := CreateContext(cw.db, name)
if err != nil {
return fmt.Errorf("create context: %w", err)
}
return nil
}
// ListContexts returns all available context windows.
func (cw *ContextWindow) ListContexts() ([]Context, error) {
contexts, err := ListContexts(cw.db)
if err != nil {
return nil, fmt.Errorf("list contexts: %w", err)
}
return contexts, nil
}
// GetContext retrieves context metadata by name.
func (cw *ContextWindow) GetContext(name string) (Context, error) {
ctx, err := GetContextByName(cw.db, name)
if err != nil {
return Context{}, fmt.Errorf("get context: %w", err)
}
return ctx, nil
}
// DeleteContext removes a context and all its records.
func (cw *ContextWindow) DeleteContext(name string) error {
if name == cw.currentContext {
contexts, err := ListContexts(cw.db)
if err != nil {
return fmt.Errorf("list contexts for deletion: %w", err)
}
if len(contexts) <= 1 {
_, err := CreateContext(cw.db, "default")
if err != nil {
return fmt.Errorf("create replacement context: %w", err)
}
cw.currentContext = "default"
} else {
for _, ctx := range contexts {
if ctx.Name != name {
cw.currentContext = ctx.Name
break
}
}
}
}
err := DeleteContextByName(cw.db, name)
if err != nil {
return fmt.Errorf("delete context: %w", err)
}
return nil
}
// ExportContext extracts a complete context with all its records.
func (cw *ContextWindow) ExportContext(name string) (ContextExport, error) {
export, err := ExportContextByName(cw.db, name)
if err != nil {
return ContextExport{}, fmt.Errorf("export context: %w", err)
}
return export, nil
}
// ExportContextJSON exports a context as JSON bytes.
func (cw *ContextWindow) ExportContextJSON(name string) ([]byte, error) {
jsonData, err := ExportContextJSONByName(cw.db, name)
if err != nil {
return nil, fmt.Errorf("export context json: %w", err)
}
return jsonData, nil
}
func (cw *ContextWindow) GetCurrentContext() string {
return cw.currentContext
}
// GetCurrentContextInfo returns the current context metadata.
func (cw *ContextWindow) GetCurrentContextInfo() (Context, error) {
return cw.GetContext(cw.currentContext)
}
// MaxTokens returns the maximum number of tokens allowed in the context window.
func (cw *ContextWindow) MaxTokens() int {
return cw.maxTokens
}
// SetMaxTokens updates the maximum number of tokens allowed in the context window.
func (cw *ContextWindow) SetMaxTokens(max int) {
cw.maxTokens = max
}
// SwitchContext switches the ContextWindow to operate on a different existing context.
func (cw *ContextWindow) SwitchContext(name string) error {
if name == "" {
return fmt.Errorf("context name cannot be empty")
}
_, err := GetContextByName(cw.db, name)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
// Context doesn't exist, create it with default settings
_, err = CreateContext(cw.db, name)
if err != nil {
return fmt.Errorf("create context: %w", err)
}
} else {
return fmt.Errorf("switch context: %w", err)
}
}
cw.currentContext = name
return nil
}
// SetServerSideThreading enables or disables server-side threading for the current context.
func (cw *ContextWindow) SetServerSideThreading(enabled bool) error {
contextID, err := getContextIDByName(cw.db, cw.currentContext)
if err != nil {
return fmt.Errorf("get context ID: %w", err)
}
return SetContextServerSideThreading(cw.db, contextID, enabled)
}
// IsServerSideThreadingEnabled returns whether server-side threading is enabled.
func (cw *ContextWindow) IsServerSideThreadingEnabled() (bool, error) {
contextInfo, err := cw.GetCurrentContextInfo()
if err != nil {
return false, err
}
return contextInfo.UseServerSideThreading, nil
}
// GetContextStats retrieves efficient statistics for any context.
// All metrics are computed using database aggregations with existing indexes.
func (cw *ContextWindow) GetContextStats(context Context) (ContextStats, error) {
stats := ContextStats{}
// Get record counts and live token sum in a single query
row := cw.db.QueryRow(`
SELECT
COUNT(*) as total_records,
COUNT(CASE WHEN live = 1 THEN 1 END) as live_records,
COALESCE(SUM(CASE WHEN live = 1 THEN est_tokens ELSE 0 END), 0) as live_tokens,
MAX(ts) as last_activity
FROM records
WHERE context_id = ?`,
context.ID,
)
var lastActivityStr sql.NullString
err := row.Scan(&stats.TotalRecords, &stats.LiveRecords, &stats.LiveTokens, &lastActivityStr)
if err != nil {
return ContextStats{}, fmt.Errorf("get context stats: %w", err)
}
if lastActivityStr.Valid && lastActivityStr.String != "" {
// Try multiple timestamp formats that SQLite might use
formats := []string{
"2006-01-02 15:04:05.999999999 -0700 MST", // SQLite format with timezone
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02 15:04:05",
time.RFC3339,
time.RFC3339Nano,
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05.999999999Z",
}
for _, format := range formats {
if t, err := time.Parse(format, lastActivityStr.String); err == nil {
stats.LastActivity = &t
break
}
}
}
return stats, nil
}
// Reader returns a thread-safe read-only view of this ContextWindow.
// The returned ContextReader is safe for concurrent use by multiple
// goroutines, even while this ContextWindow is being modified.
func (cw *ContextWindow) Reader() *ContextReader {
return &ContextReader{cw: cw}
}
// ContextReader methods - all forward to the underlying ContextWindow
// LiveRecords retrieves all "live" records from the context.
func (cr *ContextReader) LiveRecords() ([]Record, error) {
return cr.cw.LiveRecords()
}
// LiveTokens estimates the total number of tokens in all "live" messages.
func (cr *ContextReader) LiveTokens() (int, error) {
return cr.cw.LiveTokens()
}
// TotalTokens returns the cumulative token count across all model calls.
func (cr *ContextReader) TotalTokens() int {
return cr.cw.TotalTokens()
}
// TokenUsage returns current token usage metrics optimized for UI display.
func (cr *ContextReader) TokenUsage() (TokenUsage, error) {
return cr.cw.TokenUsage()
}
// GetCurrentContext returns the name of the current context.
func (cr *ContextReader) GetCurrentContext() string {
return cr.cw.GetCurrentContext()
}
// GetCurrentContextInfo returns the current context metadata.
func (cr *ContextReader) GetCurrentContextInfo() (Context, error) {
return cr.cw.GetCurrentContextInfo()
}
// ListContexts returns all available context windows.
func (cr *ContextReader) ListContexts() ([]Context, error) {
return cr.cw.ListContexts()
}
// GetContext retrieves context metadata by name.
func (cr *ContextReader) GetContext(name string) (Context, error) {
return cr.cw.GetContext(name)
}
// GetContextStats retrieves efficient statistics for any context.
func (cr *ContextReader) GetContextStats(context Context) (ContextStats, error) {
return cr.cw.GetContextStats(context)
}
// ExportContext extracts a complete context with all its records.
func (cr *ContextReader) ExportContext(name string) (ContextExport, error) {
return cr.cw.ExportContext(name)
}
// ExportContextJSON exports a context as JSON bytes.
func (cr *ContextReader) ExportContextJSON(name string) ([]byte, error) {
return cr.cw.ExportContextJSON(name)
}
// MaxTokens returns the maximum number of tokens allowed in the context window.
func (cr *ContextReader) MaxTokens() int {
return cr.cw.MaxTokens()
}
// Clone creates a copy of the current context with a new name.
func (cw *ContextWindow) Clone(destName string) error {
return CloneContext(cw.db, cw.currentContext, destName)
}