-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchanges.txt
More file actions
1642 lines (1536 loc) · 52.7 KB
/
changes.txt
File metadata and controls
1642 lines (1536 loc) · 52.7 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
=== Changes since v1.5.0 ===
=== Commit Messages ===
* goimport
* Refactoring anthropic client
* README.md has been updated
* Fixing linting
* refactor(anthropic): add streaming support and improve testability
- Extract AnthropicClient interface with streaming capabilities
- Add GetStreamingResponse implementation for AnthropicLLMProvider
- Create RealAnthropicClient wrapper for Anthropic SDK
- Add comprehensive tests with mock client implementation
* refactor(anthropic): extract client interface for better testability
This commit introduces an AnthropicClient interface to improve testability of
the AnthropicLLMProvider. The changes include:
- Extract AnthropicClient interface from concrete implementation
- Create RealAnthropicClient that wraps the official Anthropic SDK
- Update AnthropicLLMProvider to use the interface instead of direct SDK usage
- Add comprehensive tests using mock client implementation
* Fixing code duplications for openai provider file
* README.md updated
* feat(ai): add streaming support for LLM providers
Adds streaming response capability to the LLM interface and OpenAI provider
implementation. This allows receiving tokens incrementally as they are
generated rather than waiting for the complete response.
Changes:
- Add StreamingLLMResponse type to represent partial response chunks
- Add GetStreamingResponse to LLMProvider interface
- Add streaming implementation for OpenAI provider
- Add tests for streaming functionality
- Add godoc with usage examples
To maintain backward compatibility, the existing Generate method remains
unchanged while exposing a new GenerateStream method for streaming responses.
* Updated godoc comment for ai/llm.go
* refactor(ai): move LLM provider to request constructor
- Update LLMRequest to store provider instance internally
- Simplify Generate() signature by removing provider parameter
- Update tests to reflect new constructor signature
This change improves encapsulation by moving provider dependency
to construction time rather than requiring it on every Generate()
call.
=== File Changes ===
README.md | 163 ++++++++++---------
ai/llm.go | 83 +++++++++-
ai/llm_provider_anthropic.go | 136 +++++++++++++---
ai/llm_provider_anthropic_client.go | 63 ++++++++
ai/llm_provider_anthropic_test.go | 302 +++++++++++++++++++++++++++++++++++-
ai/llm_provider_openai.go | 69 +++++++-
ai/llm_provider_openai_test.go | 96 ++++++++++++
ai/llm_test.go | 122 ++++++++++++++-
ai/types.go | 19 ++-
9 files changed, 926 insertions(+), 127 deletions(-)
=== Detailed Changes ===
commit 78b0a90fae91a9f0e3e998dc67dc6abe74c97f67
Author: Shaharia Azam <mail@shaharia.com>
Date: Mon Dec 16 19:17:30 2024 +0100
goimport
diff --git a/ai/llm_provider_anthropic_client.go b/ai/llm_provider_anthropic_client.go
index 3c08be9..7ec4538 100644
--- a/ai/llm_provider_anthropic_client.go
+++ b/ai/llm_provider_anthropic_client.go
@@ -3,6 +3,7 @@ package ai
import (
"context"
+
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/anthropics/anthropic-sdk-go/packages/ssestream"
diff --git a/ai/llm_provider_anthropic_test.go b/ai/llm_provider_anthropic_test.go
index fa80056..c64a65c 100644
--- a/ai/llm_provider_anthropic_test.go
+++ b/ai/llm_provider_anthropic_test.go
@@ -3,11 +3,11 @@ package ai
import (
"context"
"encoding/json"
- "github.com/anthropics/anthropic-sdk-go/packages/ssestream"
"strings"
"testing"
"github.com/anthropics/anthropic-sdk-go"
+ "github.com/anthropics/anthropic-sdk-go/packages/ssestream"
"github.com/stretchr/testify/assert"
)
commit d3924f8596d39408e054088766be4ab6a39d42b1
Author: Shaharia Azam <mail@shaharia.com>
Date: Mon Dec 16 19:11:54 2024 +0100
Refactoring anthropic client
diff --git a/ai/llm_provider_anthropic.go b/ai/llm_provider_anthropic.go
index 4110047..9278ce0 100644
--- a/ai/llm_provider_anthropic.go
+++ b/ai/llm_provider_anthropic.go
@@ -50,21 +50,21 @@ func NewAnthropicLLMProvider(config AnthropicProviderConfig) *AnthropicLLMProvid
}
}
-// GetResponse generates a response using Anthropic's API for the given messages and configuration.
-// It supports different message roles (user, assistant, system) and handles them appropriately.
-// System messages are handled separately through Anthropic's system parameter.
-func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequestConfig) (LLMResponse, error) {
- startTime := time.Now()
-
+// prepareMessageParams creates the Anthropic message parameters from LLM messages and config.
+// This is an internal helper function to reduce code duplication.
+func (p *AnthropicLLMProvider) prepareMessageParams(messages []LLMMessage, config LLMRequestConfig) anthropic.MessageNewParams {
var anthropicMessages []anthropic.MessageParam
+ var systemMessage string
+
+ // Process messages based on their role
for _, msg := range messages {
switch msg.Role {
+ case SystemRole:
+ systemMessage = msg.Text
case UserRole:
anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
case AssistantRole:
anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(anthropic.NewTextBlock(msg.Text)))
- case SystemRole:
- continue
default:
anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
}
@@ -79,15 +79,22 @@ func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequ
}
// Add system message if present
- for _, msg := range messages {
- if msg.Role == SystemRole {
- params.System = anthropic.F([]anthropic.TextBlockParam{
- anthropic.NewTextBlock(msg.Text),
- })
- break
- }
+ if systemMessage != "" {
+ params.System = anthropic.F([]anthropic.TextBlockParam{
+ anthropic.NewTextBlock(systemMessage),
+ })
}
+ return params
+}
+
+// GetResponse generates a response using Anthropic's API for the given messages and configuration.
+// It supports different message roles (user, assistant, system) and handles them appropriately.
+// System messages are handled separately through Anthropic's system parameter.
+func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequestConfig) (LLMResponse, error) {
+ startTime := time.Now()
+
+ params := p.prepareMessageParams(messages, config)
message, err := p.client.CreateMessage(context.Background(), params)
if err != nil {
return LLMResponse{}, err
@@ -132,42 +139,8 @@ func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequ
// }
// fmt.Print(chunk.Text)
// }
-//
-// GetStreamingResponse generates a streaming response using Anthropic's API.
func (p *AnthropicLLMProvider) GetStreamingResponse(ctx context.Context, messages []LLMMessage, config LLMRequestConfig) (<-chan StreamingLLMResponse, error) {
- // Create parameters for the API call
- var anthropicMessages []anthropic.MessageParam
- var systemMessage string
-
- // Process messages based on their role
- for _, msg := range messages {
- switch msg.Role {
- case SystemRole:
- systemMessage = msg.Text
- case UserRole:
- anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
- case AssistantRole:
- anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(anthropic.NewTextBlock(msg.Text)))
- default:
- anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
- }
- }
-
- params := anthropic.MessageNewParams{
- Model: anthropic.F(p.model),
- Messages: anthropic.F(anthropicMessages),
- MaxTokens: anthropic.F(config.MaxToken),
- TopP: anthropic.Float(config.TopP),
- Temperature: anthropic.Float(config.Temperature),
- }
-
- // Add system message if present
- if systemMessage != "" {
- params.System = anthropic.F([]anthropic.TextBlockParam{
- anthropic.NewTextBlock(systemMessage),
- })
- }
-
+ params := p.prepareMessageParams(messages, config)
stream := p.client.CreateStreamingMessage(ctx, params)
responseChan := make(chan StreamingLLMResponse, 100)
commit 87867a1d0ad69e77002074c09aaf7f0bfe3f0599
Author: Shaharia Azam <mail@shaharia.com>
Date: Mon Dec 16 19:03:35 2024 +0100
Fixing linting
diff --git a/ai/llm_provider_anthropic.go b/ai/llm_provider_anthropic.go
index 824817c..4110047 100644
--- a/ai/llm_provider_anthropic.go
+++ b/ai/llm_provider_anthropic.go
@@ -1,5 +1,4 @@
-// File: ai/llm_provider_anthropic.go
-
+// Package ai provides a flexible interface for interacting with various Language Learning Models (LLMs).
package ai
import (
diff --git a/ai/llm_provider_anthropic_client.go b/ai/llm_provider_anthropic_client.go
index db8084f..3c08be9 100644
--- a/ai/llm_provider_anthropic_client.go
+++ b/ai/llm_provider_anthropic_client.go
@@ -1,5 +1,4 @@
-// File: ai/llm_provider_anthropic_client.go
-
+// Package ai provides a flexible interface for interacting with various Language Learning Models (LLMs).
package ai
import (
commit 49fe4aa1c7d5eb133cf23d9bd81b207a68091313
Author: Shaharia Azam <mail@shaharia.com>
Date: Mon Dec 16 18:53:28 2024 +0100
refactor(anthropic): add streaming support and improve testability
- Extract AnthropicClient interface with streaming capabilities
- Add GetStreamingResponse implementation for AnthropicLLMProvider
- Create RealAnthropicClient wrapper for Anthropic SDK
- Add comprehensive tests with mock client implementation
diff --git a/ai/llm_provider_anthropic.go b/ai/llm_provider_anthropic.go
index 37fc319..824817c 100644
--- a/ai/llm_provider_anthropic.go
+++ b/ai/llm_provider_anthropic.go
@@ -109,3 +109,110 @@ func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequ
CompletionTime: time.Since(startTime).Seconds(),
}, nil
}
+
+// GetStreamingResponse generates a streaming response using Anthropic's API.
+// It returns a channel that receives chunks of the response as they're generated.
+//
+// Example usage:
+//
+// client := NewRealAnthropicClient("your-api-key")
+// provider := NewAnthropicLLMProvider(AnthropicProviderConfig{
+// Client: client,
+// Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+// })
+//
+// streamingResp, err := provider.GetStreamingResponse(ctx, messages, config)
+// if err != nil {
+// log.Fatal(err)
+// }
+//
+// for chunk := range streamingResp {
+// if chunk.Error != nil {
+// log.Printf("Error: %v", chunk.Error)
+// break
+// }
+// fmt.Print(chunk.Text)
+// }
+//
+// GetStreamingResponse generates a streaming response using Anthropic's API.
+func (p *AnthropicLLMProvider) GetStreamingResponse(ctx context.Context, messages []LLMMessage, config LLMRequestConfig) (<-chan StreamingLLMResponse, error) {
+ // Create parameters for the API call
+ var anthropicMessages []anthropic.MessageParam
+ var systemMessage string
+
+ // Process messages based on their role
+ for _, msg := range messages {
+ switch msg.Role {
+ case SystemRole:
+ systemMessage = msg.Text
+ case UserRole:
+ anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
+ case AssistantRole:
+ anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(anthropic.NewTextBlock(msg.Text)))
+ default:
+ anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
+ }
+ }
+
+ params := anthropic.MessageNewParams{
+ Model: anthropic.F(p.model),
+ Messages: anthropic.F(anthropicMessages),
+ MaxTokens: anthropic.F(config.MaxToken),
+ TopP: anthropic.Float(config.TopP),
+ Temperature: anthropic.Float(config.Temperature),
+ }
+
+ // Add system message if present
+ if systemMessage != "" {
+ params.System = anthropic.F([]anthropic.TextBlockParam{
+ anthropic.NewTextBlock(systemMessage),
+ })
+ }
+
+ stream := p.client.CreateStreamingMessage(ctx, params)
+ responseChan := make(chan StreamingLLMResponse, 100)
+
+ go func() {
+ defer close(responseChan)
+
+ for stream.Next() {
+ select {
+ case <-ctx.Done():
+ responseChan <- StreamingLLMResponse{
+ Error: ctx.Err(),
+ Done: true,
+ }
+ return
+ default:
+ event := stream.Current()
+
+ switch event.Type {
+ case anthropic.MessageStreamEventTypeContentBlockDelta:
+ delta, ok := event.Delta.(anthropic.ContentBlockDeltaEventDelta)
+ if !ok {
+ continue
+ }
+
+ if delta.Type == anthropic.ContentBlockDeltaEventDeltaTypeTextDelta && delta.Text != "" {
+ responseChan <- StreamingLLMResponse{
+ Text: delta.Text,
+ TokenCount: 1,
+ }
+ }
+ case anthropic.MessageStreamEventTypeMessageStop:
+ responseChan <- StreamingLLMResponse{Done: true}
+ return
+ }
+ }
+ }
+
+ if err := stream.Err(); err != nil {
+ responseChan <- StreamingLLMResponse{
+ Error: err,
+ Done: true,
+ }
+ }
+ }()
+
+ return responseChan, nil
+}
diff --git a/ai/llm_provider_anthropic_client.go b/ai/llm_provider_anthropic_client.go
index 29ee295..db8084f 100644
--- a/ai/llm_provider_anthropic_client.go
+++ b/ai/llm_provider_anthropic_client.go
@@ -6,6 +6,7 @@ import (
"context"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
+ "github.com/anthropics/anthropic-sdk-go/packages/ssestream"
)
// AnthropicClient defines the interface for interacting with Anthropic's API.
@@ -14,6 +15,10 @@ type AnthropicClient interface {
// CreateMessage creates a new message using Anthropic's API.
// The method takes a context and MessageNewParams and returns a Message response or an error.
CreateMessage(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error)
+
+ // CreateStreamingMessage creates a streaming message using Anthropic's API.
+ // It returns a stream that can be used to receive message chunks as they're generated.
+ CreateStreamingMessage(ctx context.Context, params anthropic.MessageNewParams) *ssestream.Stream[anthropic.MessageStreamEvent]
}
// RealAnthropicClient implements the AnthropicClient interface using Anthropic's official SDK.
@@ -25,11 +30,21 @@ type RealAnthropicClient struct {
//
// Example usage:
//
+// // Regular message generation
// client := NewRealAnthropicClient("your-api-key")
// provider := NewAnthropicLLMProvider(AnthropicProviderConfig{
// Client: client,
// Model: "claude-3-sonnet-20240229",
// })
+//
+// // Streaming message generation
+// streamingResp, err := provider.GetStreamingResponse(ctx, messages, config)
+// if err != nil {
+// log.Fatal(err)
+// }
+// for chunk := range streamingResp {
+// fmt.Print(chunk.Text)
+// }
func NewRealAnthropicClient(apiKey string) *RealAnthropicClient {
client := anthropic.NewClient(option.WithAPIKey(apiKey))
return &RealAnthropicClient{
@@ -41,3 +56,8 @@ func NewRealAnthropicClient(apiKey string) *RealAnthropicClient {
func (c *RealAnthropicClient) CreateMessage(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error) {
return c.messages.New(ctx, params)
}
+
+// CreateStreamingMessage implements the streaming support for the AnthropicClient interface.
+func (c *RealAnthropicClient) CreateStreamingMessage(ctx context.Context, params anthropic.MessageNewParams) *ssestream.Stream[anthropic.MessageStreamEvent] {
+ return c.messages.NewStreaming(ctx, params)
+}
diff --git a/ai/llm_provider_anthropic_test.go b/ai/llm_provider_anthropic_test.go
index 6426b8e..fa80056 100644
--- a/ai/llm_provider_anthropic_test.go
+++ b/ai/llm_provider_anthropic_test.go
@@ -2,6 +2,9 @@ package ai
import (
"context"
+ "encoding/json"
+ "github.com/anthropics/anthropic-sdk-go/packages/ssestream"
+ "strings"
"testing"
"github.com/anthropics/anthropic-sdk-go"
@@ -10,11 +13,79 @@ import (
// MockAnthropicClient implements AnthropicClient interface for testing
type MockAnthropicClient struct {
- createMessageFunc func(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error)
+ createMessageFunc func(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error)
+ createStreamingMessageFunc func(ctx context.Context, params anthropic.MessageNewParams) *ssestream.Stream[anthropic.MessageStreamEvent]
}
func (m *MockAnthropicClient) CreateMessage(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error) {
- return m.createMessageFunc(ctx, params)
+ if m.createMessageFunc != nil {
+ return m.createMessageFunc(ctx, params)
+ }
+ return nil, nil
+}
+
+func (m *MockAnthropicClient) CreateStreamingMessage(ctx context.Context, params anthropic.MessageNewParams) *ssestream.Stream[anthropic.MessageStreamEvent] {
+ if m.createStreamingMessageFunc != nil {
+ return m.createStreamingMessageFunc(ctx, params)
+ }
+ return nil
+}
+
+type mockEventStream struct {
+ events []anthropic.MessageStreamEvent
+ index int
+}
+
+// Implement ssestream.Runner interface
+func (m *mockEventStream) Run() error {
+ return nil
+}
+
+type mockDecoder struct {
+ events []anthropic.MessageStreamEvent
+ index int
+}
+
+func (d *mockDecoder) Event() ssestream.Event {
+ if d.index < 0 || d.index >= len(d.events) {
+ return ssestream.Event{}
+ }
+
+ event := d.events[d.index]
+
+ // Create a custom payload that can be unmarshaled correctly
+ payload := map[string]interface{}{
+ "type": event.Type,
+ "delta": event.Delta,
+ "index": event.Index,
+ }
+
+ if event.Type == anthropic.MessageStreamEventTypeMessageStart {
+ payload["message"] = event.Message
+ }
+
+ data, err := json.Marshal(payload)
+ if err != nil {
+ return ssestream.Event{}
+ }
+
+ return ssestream.Event{
+ Type: string(event.Type),
+ Data: data,
+ }
+}
+
+func (d *mockDecoder) Next() bool {
+ d.index++
+ return d.index < len(d.events)
+}
+
+func (d *mockDecoder) Err() error {
+ return nil
+}
+
+func (d *mockDecoder) Close() error {
+ return nil
}
func TestAnthropicLLMProvider_NewAnthropicLLMProvider(t *testing.T) {
@@ -126,3 +197,134 @@ func TestAnthropicLLMProvider_GetResponse(t *testing.T) {
})
}
}
+
+func TestAnthropicLLMProvider_GetStreamingResponse(t *testing.T) {
+ tests := []struct {
+ name string
+ messages []LLMMessage
+ config LLMRequestConfig
+ streamText []string
+ expectError bool
+ }{
+ {
+ name: "successful streaming response",
+ messages: []LLMMessage{
+ {Role: UserRole, Text: "Hello"},
+ },
+ config: LLMRequestConfig{
+ MaxToken: 100,
+ TopP: 0.9,
+ Temperature: 0.7,
+ },
+ streamText: []string{"Hello", " world", "!"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ mockClient := &MockAnthropicClient{
+ createStreamingMessageFunc: func(ctx context.Context, params anthropic.MessageNewParams) *ssestream.Stream[anthropic.MessageStreamEvent] {
+ var events []anthropic.MessageStreamEvent
+
+ // Create start event
+ events = append(events, anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeMessageStart,
+ Message: anthropic.Message{
+ Role: anthropic.MessageRoleAssistant,
+ Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+ },
+ })
+
+ // Create content block delta events
+ for i, text := range tt.streamText {
+ t.Logf("Adding delta event %d with text: %q", i, text)
+ events = append(events, anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeContentBlockDelta,
+ Index: int64(i),
+ Delta: anthropic.ContentBlockDeltaEventDelta{
+ Type: anthropic.ContentBlockDeltaEventDeltaTypeTextDelta,
+ Text: text,
+ },
+ })
+ }
+
+ // Add stop event
+ events = append(events, anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeMessageStop,
+ })
+
+ decoder := &mockDecoder{
+ events: events,
+ index: -1,
+ }
+
+ stream := ssestream.NewStream[anthropic.MessageStreamEvent](decoder, nil)
+ return stream
+ },
+ }
+
+ provider := NewAnthropicLLMProvider(AnthropicProviderConfig{
+ Client: mockClient,
+ Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+ })
+
+ ctx := context.Background()
+ stream, err := provider.GetStreamingResponse(ctx, tt.messages, tt.config)
+ assert.NoError(t, err)
+
+ var receivedText string
+ for chunk := range stream {
+ t.Logf("Received streaming chunk: %+v", chunk)
+ if chunk.Error != nil {
+ t.Fatalf("Unexpected error: %v", chunk.Error)
+ }
+ if !chunk.Done {
+ receivedText += chunk.Text
+ t.Logf("Current accumulated text: %q", receivedText)
+ }
+ }
+
+ t.Logf("Final text: %q", receivedText)
+ assert.Equal(t, strings.Join(tt.streamText, ""), receivedText)
+ })
+ }
+}
+
+func createStreamEvent(eventType string, index int64, text string) anthropic.MessageStreamEvent {
+ var event anthropic.MessageStreamEvent
+
+ switch eventType {
+ case "message_start":
+ event = anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeMessageStart,
+ Message: anthropic.Message{
+ Role: anthropic.MessageRoleAssistant,
+ Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+ },
+ }
+ case "content_block_delta":
+ /*textDelta := anthropic.TextDelta{
+ Type: anthropic.TextDeltaTypeTextDelta,
+ Text: text,
+ }*/
+ event = anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeContentBlockDelta,
+ Index: index,
+ Delta: anthropic.ContentBlockDeltaEventDelta{
+ Type: anthropic.ContentBlockDeltaEventDeltaTypeTextDelta,
+ Text: text,
+ },
+ }
+ case "content_block_stop":
+ event = anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeContentBlockStop,
+ Index: index,
+ }
+ case "message_stop":
+ event = anthropic.MessageStreamEvent{
+ Type: anthropic.MessageStreamEventTypeMessageStop,
+ }
+ }
+
+ return event
+}
commit 8f893579503c1f2ad135e8f2d2e7b5b468a7b6a4
Author: Shaharia Azam <mail@shaharia.com>
Date: Mon Dec 16 17:57:56 2024 +0100
refactor(anthropic): extract client interface for better testability
This commit introduces an AnthropicClient interface to improve testability of
the AnthropicLLMProvider. The changes include:
- Extract AnthropicClient interface from concrete implementation
- Create RealAnthropicClient that wraps the official Anthropic SDK
- Update AnthropicLLMProvider to use the interface instead of direct SDK usage
- Add comprehensive tests using mock client implementation
diff --git a/ai/llm_provider_anthropic.go b/ai/llm_provider_anthropic.go
index f4c5b40..37fc319 100644
--- a/ai/llm_provider_anthropic.go
+++ b/ai/llm_provider_anthropic.go
@@ -1,4 +1,5 @@
-// Package ai provides a flexible interface for interacting with various Language Learning Models (LLMs).
+// File: ai/llm_provider_anthropic.go
+
package ai
import (
@@ -6,20 +7,19 @@ import (
"time"
"github.com/anthropics/anthropic-sdk-go"
- "github.com/anthropics/anthropic-sdk-go/option"
)
// AnthropicLLMProvider implements the LLMProvider interface using Anthropic's official Go SDK.
// It provides access to Claude models through Anthropic's API.
type AnthropicLLMProvider struct {
- client *anthropic.Client
+ client AnthropicClient
model anthropic.Model
}
// AnthropicProviderConfig holds the configuration options for creating an Anthropic provider.
type AnthropicProviderConfig struct {
- // APIKey is the authentication key for Anthropic's API
- APIKey string
+ // Client is the AnthropicClient implementation to use
+ Client AnthropicClient
// Model specifies which Anthropic model to use (e.g., "claude-3-opus-20240229", "claude-3-sonnet-20240229")
Model anthropic.Model
@@ -27,13 +27,26 @@ type AnthropicProviderConfig struct {
// NewAnthropicLLMProvider creates a new Anthropic provider with the specified configuration.
// If no model is specified, it defaults to Claude 3.5 Sonnet.
+//
+// Example usage:
+//
+// client := NewRealAnthropicClient("your-api-key")
+// provider := NewAnthropicLLMProvider(AnthropicProviderConfig{
+// Client: client,
+// Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+// })
+//
+// response, err := provider.GetResponse(messages, config)
+// if err != nil {
+// log.Fatal(err)
+// }
func NewAnthropicLLMProvider(config AnthropicProviderConfig) *AnthropicLLMProvider {
if config.Model == "" {
config.Model = anthropic.ModelClaude_3_5_Sonnet_20240620
}
return &AnthropicLLMProvider{
- client: anthropic.NewClient(option.WithAPIKey(config.APIKey)),
+ client: config.Client,
model: config.Model,
}
}
@@ -41,7 +54,6 @@ func NewAnthropicLLMProvider(config AnthropicProviderConfig) *AnthropicLLMProvid
// GetResponse generates a response using Anthropic's API for the given messages and configuration.
// It supports different message roles (user, assistant, system) and handles them appropriately.
// System messages are handled separately through Anthropic's system parameter.
-// The function returns an LLMResponse containing the generated text and metadata, or an error if the operation fails.
func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequestConfig) (LLMResponse, error) {
startTime := time.Now()
@@ -53,7 +65,6 @@ func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequ
case AssistantRole:
anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(anthropic.NewTextBlock(msg.Text)))
case SystemRole:
- // Anthropic handles system messages differently - we'll add it to params.System
continue
default:
anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(msg.Text)))
@@ -78,7 +89,7 @@ func (p *AnthropicLLMProvider) GetResponse(messages []LLMMessage, config LLMRequ
}
}
- message, err := p.client.Messages.New(context.Background(), params)
+ message, err := p.client.CreateMessage(context.Background(), params)
if err != nil {
return LLMResponse{}, err
}
diff --git a/ai/llm_provider_anthropic_client.go b/ai/llm_provider_anthropic_client.go
new file mode 100644
index 0000000..29ee295
--- /dev/null
+++ b/ai/llm_provider_anthropic_client.go
@@ -0,0 +1,43 @@
+// File: ai/llm_provider_anthropic_client.go
+
+package ai
+
+import (
+ "context"
+ "github.com/anthropics/anthropic-sdk-go"
+ "github.com/anthropics/anthropic-sdk-go/option"
+)
+
+// AnthropicClient defines the interface for interacting with Anthropic's API.
+// This interface abstracts the essential message-related operations used by AnthropicLLMProvider.
+type AnthropicClient interface {
+ // CreateMessage creates a new message using Anthropic's API.
+ // The method takes a context and MessageNewParams and returns a Message response or an error.
+ CreateMessage(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error)
+}
+
+// RealAnthropicClient implements the AnthropicClient interface using Anthropic's official SDK.
+type RealAnthropicClient struct {
+ messages *anthropic.MessageService
+}
+
+// NewRealAnthropicClient creates a new instance of RealAnthropicClient with the provided API key.
+//
+// Example usage:
+//
+// client := NewRealAnthropicClient("your-api-key")
+// provider := NewAnthropicLLMProvider(AnthropicProviderConfig{
+// Client: client,
+// Model: "claude-3-sonnet-20240229",
+// })
+func NewRealAnthropicClient(apiKey string) *RealAnthropicClient {
+ client := anthropic.NewClient(option.WithAPIKey(apiKey))
+ return &RealAnthropicClient{
+ messages: client.Messages,
+ }
+}
+
+// CreateMessage implements the AnthropicClient interface using the real Anthropic client.
+func (c *RealAnthropicClient) CreateMessage(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error) {
+ return c.messages.New(ctx, params)
+}
diff --git a/ai/llm_provider_anthropic_test.go b/ai/llm_provider_anthropic_test.go
index 5de8cb0..6426b8e 100644
--- a/ai/llm_provider_anthropic_test.go
+++ b/ai/llm_provider_anthropic_test.go
@@ -1,21 +1,32 @@
package ai
import (
+ "context"
"testing"
"github.com/anthropics/anthropic-sdk-go"
+ "github.com/stretchr/testify/assert"
)
+// MockAnthropicClient implements AnthropicClient interface for testing
+type MockAnthropicClient struct {
+ createMessageFunc func(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error)
+}
+
+func (m *MockAnthropicClient) CreateMessage(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error) {
+ return m.createMessageFunc(ctx, params)
+}
+
func TestAnthropicLLMProvider_NewAnthropicLLMProvider(t *testing.T) {
tests := []struct {
name string
config AnthropicProviderConfig
- expectedModel string
+ expectedModel anthropic.Model
}{
{
name: "with specified model",
config: AnthropicProviderConfig{
- APIKey: "test-key",
+ Client: &MockAnthropicClient{},
Model: "claude-3-opus-20240229",
},
expectedModel: "claude-3-opus-20240229",
@@ -23,9 +34,9 @@ func TestAnthropicLLMProvider_NewAnthropicLLMProvider(t *testing.T) {
{
name: "with default model",
config: AnthropicProviderConfig{
- APIKey: "test-key",
+ Client: &MockAnthropicClient{},
},
- expectedModel: string(anthropic.ModelClaude_3_5_Sonnet_20240620),
+ expectedModel: anthropic.ModelClaude_3_5_Sonnet_20240620,
},
}
@@ -33,12 +44,85 @@ func TestAnthropicLLMProvider_NewAnthropicLLMProvider(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
provider := NewAnthropicLLMProvider(tt.config)
- if provider.model != tt.expectedModel {
- t.Errorf("expected model %q, got %q", tt.expectedModel, provider.model)
+ assert.Equal(t, tt.expectedModel, provider.model, "unexpected model")
+ assert.NotNil(t, provider.client, "expected client to be initialized")
+ })
+ }
+}
+
+func TestAnthropicLLMProvider_GetResponse(t *testing.T) {
+ tests := []struct {
+ name string
+ messages []LLMMessage
+ config LLMRequestConfig
+ expectedResult LLMResponse
+ expectError bool
+ }{
+ {
+ name: "successful response with all message types",
+ messages: []LLMMessage{
+ {Role: SystemRole, Text: "You are a helpful assistant"},
+ {Role: UserRole, Text: "Hello"},
+ {Role: AssistantRole, Text: "Hi there"},
+ },
+ config: LLMRequestConfig{
+ MaxToken: 100,
+ TopP: 0.9,
+ Temperature: 0.7,
+ },
+ expectedResult: LLMResponse{
+ Text: "Test response",
+ TotalInputToken: 10,
+ TotalOutputToken: 5,
+ },
+ expectError: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ mockClient := &MockAnthropicClient{
+ createMessageFunc: func(ctx context.Context, params anthropic.MessageNewParams) (*anthropic.Message, error) {
+ message := &anthropic.Message{
+ Role: anthropic.MessageRoleAssistant,
+ Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+ Usage: anthropic.Usage{
+ InputTokens: 10,
+ OutputTokens: 5,
+ },
+ Type: anthropic.MessageTypeMessage,
+ }
+
+ block := anthropic.ContentBlock{}
+ if err := block.UnmarshalJSON([]byte(`{
+ "type": "text",
+ "text": "Test response"
+ }`)); err != nil {
+ t.Fatal(err)
+ }
+
+ message.Content = []anthropic.ContentBlock{block}
+ return message, nil
+ },
}
- if provider.client == nil {
- t.Error("expected client to be initialized")
+
+ provider := NewAnthropicLLMProvider(AnthropicProviderConfig{
+ Client: mockClient,
+ Model: anthropic.ModelClaude_3_5_Sonnet_20240620,
+ })
+
+ result, err := provider.GetResponse(tt.messages, tt.config)
+
+ if tt.expectError {
+ assert.Error(t, err)
+ return
}
+
+ assert.NoError(t, err)
+ assert.Equal(t, tt.expectedResult.Text, result.Text)
+ assert.Equal(t, tt.expectedResult.TotalInputToken, result.TotalInputToken)
+ assert.Equal(t, tt.expectedResult.TotalOutputToken, result.TotalOutputToken)
+ assert.Greater(t, result.CompletionTime, float64(0), "completion time should be greater than 0")
})
}
}
commit 6618ad4a7eccacc3a3a14e8ac300a64a9808343c
Author: Shaharia Azam <mail@shaharia.com>
Date: Mon Dec 16 01:10:15 2024 +0100
Fixing code duplications for openai provider file
diff --git a/ai/llm_provider_openai.go b/ai/llm_provider_openai.go
index 9914d88..ecb76e7 100644
--- a/ai/llm_provider_openai.go
+++ b/ai/llm_provider_openai.go
@@ -34,11 +34,8 @@ func NewOpenAILLMProvider(config OpenAIProviderConfig) *OpenAILLMProvider {
}
}
-// GetResponse generates a response using OpenAI's API for the given messages and configuration.
-// It supports different message roles (user, assistant, system) and handles them appropriately.
-func (p *OpenAILLMProvider) GetResponse(messages []LLMMessage, config LLMRequestConfig) (LLMResponse, error) {
- startTime := time.Now()
-
+// convertToOpenAIMessages converts internal message format to OpenAI's format
+func (p *OpenAILLMProvider) convertToOpenAIMessages(messages []LLMMessage) []openai.ChatCompletionMessageParamUnion {
var openAIMessages []openai.ChatCompletionMessageParamUnion
for _, msg := range messages {
switch msg.Role {
@@ -52,14 +49,27 @@ func (p *OpenAILLMProvider) GetResponse(messages []LLMMessage, config LLMRequest
openAIMessages = append(openAIMessages, openai.UserMessage(msg.Text))
}
}
+ return openAIMessages
+}
- params := openai.ChatCompletionNewParams{
- Messages: openai.F(openAIMessages),
+// createCompletionParams creates OpenAI API parameters from request config
+func (p *OpenAILLMProvider) createCompletionParams(messages []openai.ChatCompletionMessageParamUnion, config LLMRequestConfig) openai.ChatCompletionNewParams {
+ return openai.ChatCompletionNewParams{
+ Messages: openai.F(messages),
Model: openai.F(p.model),
MaxTokens: openai.Int(config.MaxToken),
TopP: openai.Float(config.TopP),
Temperature: openai.Float(config.Temperature),
}
+}
+
+// GetResponse generates a response using OpenAI's API for the given messages and configuration.
+// It supports different message roles (user, assistant, system) and handles them appropriately.