-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontextwindow_test.go
More file actions
2749 lines (2237 loc) · 79.1 KB
/
contextwindow_test.go
File metadata and controls
2749 lines (2237 loc) · 79.1 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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package contextwindow
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/packages/param"
"github.com/openai/openai-go/v2/shared"
"github.com/stretchr/testify/assert"
_ "modernc.org/sqlite"
)
type dummyModel struct {
cw *ContextWindow
events []Record
closeDB bool
}
func (m *dummyModel) Call(ctx context.Context, inputs []Record) ([]Record, int, error) {
if m.closeDB && m.cw != nil {
m.cw.db.Close()
}
return m.events, 0, nil
}
type MockModel struct {
LastOptsDisableTools bool
events []Record
}
func (m *MockModel) Call(ctx context.Context, inputs []Record) ([]Record, int, error) {
m.LastOptsDisableTools = false // Default behavior
return m.events, 0, nil
}
func (m *MockModel) CallWithOpts(ctx context.Context, inputs []Record, opts CallModelOpts) ([]Record, int, error) {
m.LastOptsDisableTools = opts.DisableTools
return m.events, 0, nil
}
func (m *MockModel) CallWithThreadingAndOpts(
ctx context.Context,
useServerSideThreading bool,
lastResponseID *string,
inputs []Record,
opts CallModelOpts,
) ([]Record, *string, int, error) {
m.LastOptsDisableTools = opts.DisableTools
return m.events, nil, 0, nil
}
func TestNewContextWindowAndClose(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw, err := NewContextWindow(db, &dummyModel{}, "")
assert.NoError(t, err)
assert.NotNil(t, cw.db)
// Test record insertion before closing
err = cw.AddPrompt("test prompt")
assert.NoError(t, err)
// Now close and test error
err = cw.Close()
assert.NoError(t, err)
// Try to add another prompt after closing
err = cw.AddPrompt("should fail")
assert.Error(t, err)
assert.Contains(t, err.Error(), "sql: database is closed")
}
func TestAddMethodsErrorPropagation(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw, err := NewContextWindow(db, &dummyModel{}, "")
assert.NoError(t, err)
assert.NoError(t, cw.db.Close())
assert.Contains(t, cw.AddPrompt("p").Error(), "sql: database is closed")
assert.Contains(t, cw.AddToolCall("t", "a").Error(), "sql: database is closed")
assert.Contains(t, cw.AddToolOutput("o").Error(), "sql: database is closed")
}
func TestAddPromptEstTokens(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw, err := NewContextWindow(db, &dummyModel{}, "")
assert.NoError(t, err)
err = cw.AddPrompt("hello world")
assert.NoError(t, err)
recs, err := cw.LiveRecords()
assert.NoError(t, err)
assert.Equal(t, tokenCount("hello world"), recs[0].EstTokens)
}
func TestCallModelInsertRecordError(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
m := &dummyModel{closeDB: true}
cw, err := NewContextWindow(db, m, "")
assert.NoError(t, err)
m.cw = cw
m.events = []Record{{
Source: ModelResp,
Content: "x",
Live: true,
EstTokens: tokenCount("x"),
}}
_, err = cw.CallModel(context.Background())
assert.Contains(t, err.Error(), "sql: database is closed")
}
func TestContextWindowToolCall(t *testing.T) {
if os.Getenv("OPENAI_API_KEY") == "" {
t.Skip("set OPENAI_API_KEY to run integration test")
}
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
m, err := NewOpenAIModel(shared.ChatModelGPT4o)
assert.NoError(t, err)
cw, err := NewContextWindow(db, m, "")
assert.NoError(t, err)
lsTool := shared.FunctionDefinitionParam{
Name: "ls",
Description: param.NewOpt("list files in a directory"),
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{},
},
}
err = cw.RegisterTool("ls", lsTool, ToolRunnerFunc(func(ctx context.Context, args json.RawMessage) (string, error) {
return "go.mod", nil
}))
assert.NoError(t, err)
err = cw.AddPrompt("Please list the files in the current directory.")
assert.NoError(t, err)
reply, err := cw.CallModel(context.Background())
assert.NoError(t, err)
assert.True(t, strings.Contains(reply, "go.mod"))
recs, err := cw.LiveRecords()
assert.NoError(t, err)
var (
foundPrompt bool
foundCall bool
foundOutput bool
foundResp bool
)
for _, r := range recs {
if r.Source == Prompt && strings.Contains(r.Content, "list the") {
foundPrompt = true
}
if r.Source == ToolCall && strings.Contains(r.Content, "ls") {
foundCall = true
}
if r.Source == ToolOutput && strings.Contains(r.Content, "go.mod") {
foundOutput = true
}
if r.Source == ModelResp && len(r.Content) > 0 {
foundResp = true
}
}
assert.True(t, foundPrompt)
assert.True(t, foundCall)
assert.True(t, foundOutput)
assert.True(t, foundResp)
}
// Context management tests
func TestCreateAndListContexts(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw, err := NewContextWindow(db, &dummyModel{}, "")
assert.NoError(t, err)
defer cw.Close()
contexts, err := cw.ListContexts()
assert.NoError(t, err)
assert.Equal(t, 1, len(contexts))
assert.NotEmpty(t, contexts[0].Name)
err = cw.CreateContext("test-context")
assert.NoError(t, err)
contexts, err = cw.ListContexts()
assert.NoError(t, err)
assert.Equal(t, 2, len(contexts))
found := false
for _, ctx := range contexts {
if ctx.Name == "test-context" {
found = true
break
}
}
assert.True(t, found)
}
func TestContextWindowIsolation(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw1, err := NewContextWindow(db, &dummyModel{}, "context1")
assert.NoError(t, err)
defer cw1.Close()
cw2, err := NewContextWindow(db, &dummyModel{}, "context2")
assert.NoError(t, err)
defer cw2.Close()
err = cw1.AddPrompt("Hello from context 1")
assert.NoError(t, err)
err = cw2.AddPrompt("Hello from context 2")
assert.NoError(t, err)
ctx1Records, err := cw1.LiveRecords()
assert.NoError(t, err)
assert.Equal(t, 1, len(ctx1Records))
assert.Contains(t, ctx1Records[0].Content, "context 1")
ctx2Records, err := cw2.LiveRecords()
assert.NoError(t, err)
assert.Equal(t, 1, len(ctx2Records))
assert.Contains(t, ctx2Records[0].Content, "context 2")
}
func TestNewContextWindowWithContext(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw, err := NewContextWindow(db, &dummyModel{}, "custom")
assert.NoError(t, err)
defer cw.Close()
assert.Equal(t, "custom", cw.GetCurrentContext())
ctx, err := cw.GetCurrentContextInfo()
assert.NoError(t, err)
assert.Equal(t, "custom", ctx.Name)
contexts, err := cw.ListContexts()
assert.NoError(t, err)
assert.Equal(t, 1, len(contexts))
assert.Equal(t, "custom", contexts[0].Name)
}
func TestContextNameConflict(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
cw, err := NewContextWindow(db, &dummyModel{}, "")
assert.NoError(t, err)
defer cw.Close()
err = cw.CreateContext("test")
assert.NoError(t, err)
// With the new get-or-create behavior, this should succeed
err = cw.CreateContext("test")
assert.NoError(t, err)
// Verify the context exists and can be accessed
ctx, err := cw.GetContext("test")
assert.NoError(t, err)
assert.Equal(t, "test", ctx.Name)
}
func TestCreateContextWithExistingName(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
defer db.Close()
_, err = NewContextWindow(db, &dummyModel{}, "shared")
assert.NoError(t, err)
// Note: we don't close cw1 here because it doesn't own the DB.
// Second instance should use existing context
cw2, err := NewContextWindow(db, &dummyModel{}, "shared")
assert.NoError(t, err)
assert.Equal(t, "shared", cw2.GetCurrentContext())
contexts, err := cw2.ListContexts()
assert.NoError(t, err)
assert.Equal(t, 1, len(contexts))
assert.Equal(t, "shared", contexts[0].Name)
}
func TestNewContextWindowWithDB(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
// Open database manually
db, err := sql.Open("sqlite", path)
assert.NoError(t, err)
defer db.Close()
// Initialize schema manually
err = InitializeSchema(db)
assert.NoError(t, err)
// Create context window with existing DB
cw, err := NewContextWindow(db, &dummyModel{}, "shared-db")
assert.NoError(t, err)
assert.Equal(t, "shared-db", cw.GetCurrentContext())
// Add some data
err = cw.AddPrompt("Hello from shared DB")
assert.NoError(t, err)
// Create another context window with same DB
cw2, err := NewContextWindow(db, &dummyModel{}, "another-context")
assert.NoError(t, err)
assert.Equal(t, "another-context", cw2.GetCurrentContext())
// Verify data isolation
records1, err := cw.LiveRecords()
assert.NoError(t, err)
assert.Equal(t, 1, len(records1))
records2, err := cw2.LiveRecords()
assert.NoError(t, err)
assert.Equal(t, 0, len(records2))
// Both should see the same contexts list
contexts1, err := cw.ListContexts()
assert.NoError(t, err)
contexts2, err := cw2.ListContexts()
assert.NoError(t, err)
assert.Equal(t, len(contexts1), len(contexts2))
assert.Equal(t, 2, len(contexts1)) // shared-db + another-context
// Note: We don't call cw.Close() or cw2.Close() because they don't own the DB
}
// testMiddleware collects tool call events for testing
type testMiddleware struct {
toolCalls []string
toolResults []string
mu sync.Mutex
}
func (tm *testMiddleware) OnToolCall(ctx context.Context, name, args string) {
tm.mu.Lock()
defer tm.mu.Unlock()
tm.toolCalls = append(tm.toolCalls, fmt.Sprintf("%s(%s)", name, args))
}
func (tm *testMiddleware) OnToolResult(ctx context.Context, name, result string, err error) {
tm.mu.Lock()
defer tm.mu.Unlock()
if err != nil {
tm.toolResults = append(tm.toolResults, fmt.Sprintf("%s:error:%s", name, err.Error()))
} else {
tm.toolResults = append(tm.toolResults, fmt.Sprintf("%s:%s", name, result))
}
}
// toolCallModel simulates a model that makes tool calls and executes middleware
type toolCallModel struct {
response string
middleware []Middleware
}
func (m *toolCallModel) Call(ctx context.Context, inputs []Record) ([]Record, int, error) {
// Simulate middleware execution for tool calls
for _, mw := range m.middleware {
mw.OnToolCall(ctx, "hello_world", "{}")
mw.OnToolResult(ctx, "hello_world", "hello world", nil)
}
// Simulate tool call events
events := []Record{
{
Source: ToolCall,
Content: "hello_world({})",
Live: true,
EstTokens: 5,
},
{
Source: ToolOutput,
Content: "hello world",
Live: true,
EstTokens: 2,
},
{
Source: ModelResp,
Content: m.response,
Live: true,
EstTokens: 10,
},
}
return events, 20, nil
}
// SetMiddleware allows the test model to receive middleware
func (m *toolCallModel) SetMiddleware(middleware []Middleware) {
m.middleware = middleware
}
func TestMiddlewareHooks(t *testing.T) {
path := filepath.Join(t.TempDir(), "middleware-test.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
defer db.Close()
// Create a test model that simulates tool calls
testModel := &toolCallModel{
response: "I used the hello_world tool and got the result.",
}
cw, err := NewContextWindow(db, testModel, "test-middleware")
assert.NoError(t, err)
// Register test middleware - this should also update the model
middleware := &testMiddleware{}
cw.AddMiddleware(middleware)
// Make a call that should trigger tool calls
response, err := cw.CallModel(context.Background())
assert.NoError(t, err)
assert.Equal(t, "I used the hello_world tool and got the result.", response)
// Verify middleware was called
middleware.mu.Lock()
assert.Len(t, middleware.toolCalls, 1)
assert.Equal(t, "hello_world({})", middleware.toolCalls[0])
assert.Len(t, middleware.toolResults, 1)
assert.Equal(t, "hello_world:hello world", middleware.toolResults[0])
middleware.mu.Unlock()
}
func TestContextWindowToolManagement(t *testing.T) {
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
mockModel := &mockModel{}
cw, err := NewContextWindow(db, mockModel, "test-context")
assert.NoError(t, err)
// Initially no tools
tools, err := cw.ListTools()
assert.NoError(t, err)
assert.Len(t, tools, 0)
// Register a tool (automatically adds it to the context)
err = cw.RegisterTool("test_tool", "test definition", ToolRunnerFunc(func(ctx context.Context, args json.RawMessage) (string, error) {
return "test result", nil
}))
assert.NoError(t, err)
// Tool should be listed
tools, err = cw.ListTools()
assert.NoError(t, err)
assert.Len(t, tools, 1)
assert.Equal(t, "test_tool", tools[0])
// Tool should exist
has, err := cw.HasTool("test_tool")
assert.NoError(t, err)
assert.True(t, has)
// Register another tool
err = cw.RegisterTool("another_tool", "another definition", ToolRunnerFunc(func(ctx context.Context, args json.RawMessage) (string, error) {
return "another result", nil
}))
assert.NoError(t, err)
tools, err = cw.ListTools()
assert.NoError(t, err)
assert.Len(t, tools, 2)
// Both tools should exist
has, err = cw.HasTool("test_tool")
assert.NoError(t, err)
assert.True(t, has)
has, err = cw.HasTool("another_tool")
assert.NoError(t, err)
assert.True(t, has)
}
func TestContextToolPersistence(t *testing.T) {
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
mockModel := &mockModel{}
// Create first context window and add tools
cw1, err := NewContextWindow(db, mockModel, "persistence-test-context")
assert.NoError(t, err)
// Register tools with first context window
err = cw1.RegisterTool("persistent_tool", "persistent definition", ToolRunnerFunc(func(ctx context.Context, args json.RawMessage) (string, error) {
return "persistent result", nil
}))
assert.NoError(t, err)
err = cw1.RegisterTool("another_tool", "another definition", ToolRunnerFunc(func(ctx context.Context, args json.RawMessage) (string, error) {
return "another result", nil
}))
assert.NoError(t, err)
// Create second context window with same context name
cw2, err := NewContextWindow(db, mockModel, "persistence-test-context")
assert.NoError(t, err)
// Tool names are persisted, definitions are provided by the caller
// Tools should be persisted
tools, err := cw2.ListTools()
assert.NoError(t, err)
assert.Len(t, tools, 2)
assert.Contains(t, tools, "persistent_tool")
assert.Contains(t, tools, "another_tool")
// Create context window with different name
cw3, err := NewContextWindow(db, mockModel, "different-context")
assert.NoError(t, err)
// Should have no tools
tools, err = cw3.ListTools()
assert.NoError(t, err)
assert.Len(t, tools, 0)
}
// mockModel for testing - implements Model interface
type mockModel struct{}
func (m *mockModel) Call(ctx context.Context, inputs []Record) ([]Record, int, error) {
return []Record{
{
Source: ModelResp,
Content: "Mock response",
Live: true,
EstTokens: 10,
},
}, 10, nil
}
type dummyModelTokens struct {
events []Record
tokens int
}
func (m *dummyModelTokens) Call(ctx context.Context, inputs []Record) ([]Record, int, error) {
return m.events, m.tokens, nil
}
func TestTokenCounts(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
m := &dummyModelTokens{
events: []Record{{
Source: ModelResp,
Content: "z",
Live: true,
EstTokens: tokenCount("z"),
}},
tokens: 5,
}
cw, err := NewContextWindow(db, m, "")
assert.NoError(t, err)
err = cw.AddPrompt("a b c")
assert.NoError(t, err)
live, err := cw.LiveTokens()
assert.NoError(t, err)
assert.Equal(t, tokenCount("a b c"), live)
_, err = cw.CallModel(context.Background())
assert.NoError(t, err)
assert.Equal(t, 5, cw.TotalTokens())
live, err = cw.LiveTokens()
assert.NoError(t, err)
assert.Equal(t, tokenCount("a b c")+tokenCount("z"), live)
}
func TestTokenUsage(t *testing.T) {
path := filepath.Join(t.TempDir(), "cw.db")
db, err := NewContextDB(path)
assert.NoError(t, err)
m := &dummyModelTokens{
events: []Record{{
Source: ModelResp,
Content: "response",
Live: true,
EstTokens: tokenCount("response"),
}},
tokens: 10,
}
cw, err := NewContextWindow(db, m, "")
assert.NoError(t, err)
// Set a custom max tokens for testing
cw.SetMaxTokens(100)
assert.Equal(t, 100, cw.MaxTokens())
err = cw.AddPrompt("hello world")
assert.NoError(t, err)
// Before calling model
usage, err := cw.TokenUsage()
assert.NoError(t, err)
assert.Equal(t, tokenCount("hello world"), usage.Live)
assert.Equal(t, 0, usage.Total) // no model calls yet
assert.Equal(t, 100, usage.Max)
assert.Equal(t, float64(usage.Live)/100.0, usage.Percent)
// After calling model
_, err = cw.CallModel(context.Background())
assert.NoError(t, err)
usage, err = cw.TokenUsage()
assert.NoError(t, err)
assert.Equal(t, tokenCount("hello world")+tokenCount("response"), usage.Live)
assert.Equal(t, 10, usage.Total) // tokens from model call
assert.Equal(t, 100, usage.Max)
expectedPercent := float64(usage.Live) / 100.0
assert.Equal(t, expectedPercent, usage.Percent)
}
func TestServerSideThreading(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
if os.Getenv("OPENAI_API_KEY") == "" {
t.Skip("OPENAI_API_KEY not set")
}
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
// Test with responses model which supports server-side threading
model, err := NewOpenAIResponsesModel(ResponsesModel4o)
assert.NoError(t, err)
// Create context with server-side threading enabled
cw, err := NewContextWindowWithThreading(db, model, "test-threading", true)
assert.NoError(t, err)
defer cw.Close()
// Verify server-side threading is enabled
enabled, err := cw.IsServerSideThreadingEnabled()
assert.NoError(t, err)
assert.True(t, enabled)
// Add a system prompt and user prompt
err = cw.SetSystemPrompt("You are a helpful assistant. Please respond briefly.")
assert.NoError(t, err)
err = cw.AddPrompt("Hello, who are you?")
assert.NoError(t, err)
// Make first call - this should not use server-side threading since there's no previous response
ctx := context.Background()
resp1, err := cw.CallModel(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, resp1)
// Add another prompt
err = cw.AddPrompt("What's 2+2?")
assert.NoError(t, err)
// Make second call - this should use server-side threading
resp2, err := cw.CallModel(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, resp2)
// Verify that the context has a last response ID stored
contextInfo, err := cw.GetCurrentContextInfo()
assert.NoError(t, err)
assert.NotNil(t, contextInfo.LastResponseID)
assert.NotEmpty(t, *contextInfo.LastResponseID)
}
func TestClientSideThreading(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
if os.Getenv("OPENAI_API_KEY") == "" {
t.Skip("OPENAI_API_KEY not set")
}
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
// Test with completions model which doesn't support server-side threading
model, err := NewOpenAIModel(openai.ChatModelGPT4oMini)
assert.NoError(t, err)
// Create context with server-side threading disabled (default)
cw, err := NewContextWindow(db, model, "test-client-threading")
assert.NoError(t, err)
defer cw.Close()
// Verify server-side threading is disabled
enabled, err := cw.IsServerSideThreadingEnabled()
assert.NoError(t, err)
assert.False(t, enabled)
// Add a system prompt and user prompt
err = cw.SetSystemPrompt("You are a helpful assistant. Please respond briefly.")
assert.NoError(t, err)
err = cw.AddPrompt("Hello, who are you?")
assert.NoError(t, err)
// Make first call
ctx := context.Background()
resp1, err := cw.CallModel(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, resp1)
// Add another prompt
err = cw.AddPrompt("What's 2+2?")
assert.NoError(t, err)
// Make second call - should use client-side threading
resp2, err := cw.CallModel(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, resp2)
// Context should not have a last response ID since client-side threading doesn't set it
contextInfo, err := cw.GetCurrentContextInfo()
assert.NoError(t, err)
assert.Nil(t, contextInfo.LastResponseID)
}
func TestToggleThreadingMode(t *testing.T) {
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
// Use dummy model to avoid needing API key for this test
model := &dummyModel{}
// Create context with client-side threading initially
cw, err := NewContextWindow(db, model, "test-toggle")
assert.NoError(t, err)
defer cw.Close()
// Initially should be disabled
enabled, err := cw.IsServerSideThreadingEnabled()
assert.NoError(t, err)
assert.False(t, enabled)
// Enable server-side threading
err = cw.SetServerSideThreading(true)
assert.NoError(t, err)
// Should now be enabled
enabled, err = cw.IsServerSideThreadingEnabled()
assert.NoError(t, err)
assert.True(t, enabled)
// Disable again
err = cw.SetServerSideThreading(false)
assert.NoError(t, err)
// Should be disabled
enabled, err = cw.IsServerSideThreadingEnabled()
assert.NoError(t, err)
assert.False(t, enabled)
}
func TestDatabaseSchemaWithResponseID(t *testing.T) {
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
// Create a context with server-side threading
ctx, err := CreateContextWithThreading(db, "test-schema", true)
assert.NoError(t, err)
assert.True(t, ctx.UseServerSideThreading)
assert.Nil(t, ctx.LastResponseID)
// Insert a record with response ID
responseID := "resp_123456"
rec, err := InsertRecordWithResponseID(db, ctx.ID, ModelResp, "Hello world", true, &responseID)
assert.NoError(t, err)
assert.NotNil(t, rec.ResponseID)
assert.Equal(t, responseID, *rec.ResponseID)
// Update context's last response ID
err = UpdateContextLastResponseID(db, ctx.ID, responseID)
assert.NoError(t, err)
// Retrieve context and verify
updatedCtx, err := GetContext(db, ctx.ID)
assert.NoError(t, err)
assert.NotNil(t, updatedCtx.LastResponseID)
assert.Equal(t, responseID, *updatedCtx.LastResponseID)
// List records and verify response ID is preserved
recs, err := ListRecordsInContext(db, ctx.ID)
assert.NoError(t, err)
assert.Len(t, recs, 1)
assert.NotNil(t, recs[0].ResponseID)
assert.Equal(t, responseID, *recs[0].ResponseID)
}
func TestSetContextServerSideThreading(t *testing.T) {
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
// Create a context with default threading (client-side)
ctx, err := CreateContext(db, "test-set-threading")
assert.NoError(t, err)
assert.False(t, ctx.UseServerSideThreading)
// Enable server-side threading
err = SetContextServerSideThreading(db, ctx.ID, true)
assert.NoError(t, err)
// Verify it's enabled
updatedCtx, err := GetContext(db, ctx.ID)
assert.NoError(t, err)
assert.True(t, updatedCtx.UseServerSideThreading)
// Disable server-side threading
err = SetContextServerSideThreading(db, ctx.ID, false)
assert.NoError(t, err)
// Verify it's disabled
updatedCtx, err = GetContext(db, ctx.ID)
assert.NoError(t, err)
assert.False(t, updatedCtx.UseServerSideThreading)
}
// TestServerSideThreadingFallback verifies fallback behavior when server-side threading
// cannot be used, ensuring conversations continue successfully
func TestServerSideThreadingFallback(t *testing.T) {
db, err := NewContextDB(":memory:")
assert.NoError(t, err)
defer db.Close()
// Create a mock responses model that we can control
mockModel := &mockResponsesModel{}
// Create context with server-side threading enabled
cw, err := NewContextWindowWithThreading(db, mockModel, "test-fallback", true)
assert.NoError(t, err)
defer cw.Close()
// Add a prompt and make first call (no previous response ID, should fallback to client-side)
err = cw.AddPrompt("Hello")
assert.NoError(t, err)
ctx := context.Background()
resp1, err := cw.CallModel(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, resp1)
// Verify the mock was called with client-side threading (no previous response ID)
// First call falls back because there's no LastResponseID yet
assert.False(t, mockModel.lastCallUsedServerSide)
assert.Nil(t, mockModel.lastPreviousResponseID)
// Verify conversation continues successfully - check that response was recorded
recs, err := cw.LiveRecords()
assert.NoError(t, err)
assert.Greater(t, len(recs), 0)
// Manually set LastResponseID to simulate what would happen after a server-side call
// In a real scenario, this would be set by the previous server-side threading call
ctxInfo, err := GetContextByName(db, "test-fallback")
assert.NoError(t, err)
testResponseID := "mock_response_123"
err = UpdateContextLastResponseID(db, ctxInfo.ID, testResponseID)
assert.NoError(t, err)
// Also set responseID on the last model response record to make chain valid
recs, err = cw.LiveRecords()
assert.NoError(t, err)
for i := len(recs) - 1; i >= 0; i-- {
if recs[i].Source == ModelResp {
_, err = db.Exec(`UPDATE records SET response_id = ? WHERE id = ?`, testResponseID, recs[i].ID)
assert.NoError(t, err)
break
}
}
// Add another prompt - this should use server-side threading now that we have LastResponseID
err = cw.AddPrompt("How are you?")
assert.NoError(t, err)
resp2, err := cw.CallModel(ctx)
assert.NoError(t, err)
assert.NotEmpty(t, resp2)
// Verify the mock was called with server-side threading (now we have LastResponseID)
assert.True(t, mockModel.lastCallUsedServerSide)
assert.NotNil(t, mockModel.lastPreviousResponseID)
// Verify conversation continues successfully with both responses
recs, err = cw.LiveRecords()
assert.NoError(t, err)
assert.Greater(t, len(recs), 2) // Should have prompts and responses
}
// Mock model for testing server-side threading behavior
type mockResponsesModel struct {
lastCallUsedServerSide bool
lastPreviousResponseID *string
lastInputs []Record
}
func (m *mockResponsesModel) Call(ctx context.Context, inputs []Record) ([]Record, int, error) {
// CallWithThreading with client-side threading (useServerSideThreading=false)
// Still return a responseID so LastResponseID gets set
events, responseID, tokens, err := m.CallWithThreading(ctx, false, nil, inputs)
// Set responseID on events for consistency
if responseID != nil && len(events) > 0 {
for i := range events {
if events[i].Source == ModelResp {
events[i].ResponseID = responseID
}
}
}
return events, tokens, err
}
func (m *mockResponsesModel) CallWithThreading(
ctx context.Context,
useServerSideThreading bool,
lastResponseID *string,
inputs []Record,
) ([]Record, *string, int, error) {
// Record the call parameters
m.lastCallUsedServerSide = useServerSideThreading && lastResponseID != nil
m.lastPreviousResponseID = lastResponseID
m.lastInputs = inputs
// Return a mock response
responseID := "mock_response_123"
return []Record{
{
Source: ModelResp,
Content: "Mock response",
Live: true,
EstTokens: 10,
ResponseID: &responseID,
},
}, &responseID, 25, nil
}
func (m *mockResponsesModel) SetToolExecutor(executor ToolExecutor) {
// No-op for mock
}
func (m *mockResponsesModel) SetMiddleware(middleware []Middleware) {
// No-op for mock
}
func TestSchemaMigrationWithNewContextDB(t *testing.T) {
// This test verifies that NewContextDB properly handles schema migration
db, err := NewContextDB(":memory:")
assert.NoError(t, err)