-
Notifications
You must be signed in to change notification settings - Fork 13
/
message_test.go
849 lines (740 loc) · 22.5 KB
/
message_test.go
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
package anthropic_test
import (
"context"
"embed"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/liushuangls/go-anthropic/v2"
"github.com/liushuangls/go-anthropic/v2/internal/test"
"github.com/liushuangls/go-anthropic/v2/internal/test/checks"
"github.com/liushuangls/go-anthropic/v2/jsonschema"
)
//go:embed internal/test/sources/*
var sources embed.FS
var rateLimitHeaders = map[string]string{
"anthropic-ratelimit-requests-limit": "100",
"anthropic-ratelimit-requests-remaining": "99",
"anthropic-ratelimit-requests-reset": "2024-06-04T07:13:19Z",
"anthropic-ratelimit-tokens-limit": "10000",
"anthropic-ratelimit-tokens-remaining": "9900",
"anthropic-ratelimit-tokens-reset": "2024-06-04T07:13:19Z",
"retry-after": "", // retry-after is optional and may not be present.
}
func TestMessages(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(rateLimitHeaders))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
anthropic.WithAPIVersion(anthropic.APIVersion20230601),
anthropic.WithEmptyMessagesLimit(100),
anthropic.WithHTTPClient(http.DefaultClient),
)
t.Run("create messages success", func(t *testing.T) {
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
t.Logf("CreateMessages resp: %+v", resp)
})
t.Run("create messages success with single system message", func(t *testing.T) {
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
System: "test system message",
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
t.Logf("CreateMessages resp: %+v", resp)
})
t.Run("create messages success with single multi-system message", func(t *testing.T) {
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
MultiSystem: anthropic.NewMultiSystemMessages("test single multi-system message"),
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
t.Logf("CreateMessages resp: %+v", resp)
})
t.Run("create messages success with multi-system messages", func(t *testing.T) {
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
MultiSystem: anthropic.NewMultiSystemMessages(
"test multi-system messages",
"here",
"are",
"some",
"more",
"messages",
"for",
"testing",
),
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
t.Logf("CreateMessages resp: %+v", resp)
})
}
func TestNewUserTextMessage(t *testing.T) {
m := anthropic.NewUserTextMessage("What is your name?")
if m.Role != anthropic.RoleUser {
t.Fatalf("Role mismatch. got %s, want %s", m.Role, anthropic.RoleUser)
}
if m.Content[0].Type != anthropic.MessagesContentTypeText {
t.Fatalf(
"Content type mismatch. got %s, want %s",
m.Content[0].Type,
anthropic.MessagesContentTypeText,
)
}
if *m.Content[0].Text != "What is your name?" {
t.Fatalf("Content text mismatch. got %s, want %s", *m.Content[0].Text, "What is your name?")
}
}
func TestNewAssistantTextMessage(t *testing.T) {
m := anthropic.NewAssistantTextMessage("My name is Claude.")
if m.Role != anthropic.RoleAssistant {
t.Fatalf("Role mismatch. got %s, want %s", m.Role, anthropic.RoleAssistant)
}
if m.Content[0].Type != anthropic.MessagesContentTypeText {
t.Fatalf(
"Content type mismatch. got %s, want %s",
m.Content[0].Type,
anthropic.MessagesContentTypeText,
)
}
if *m.Content[0].Text != "My name is Claude." {
t.Fatalf("Content text mismatch. got %s, want %s", *m.Content[0].Text, "My name is Claude.")
}
}
func TestGetFirstContent(t *testing.T) {
t.Run("returns empty content", func(t *testing.T) {
m := anthropic.Message{}
c := m.GetFirstContent()
if c.Type != "" {
t.Fatalf("Content type mismatch. got %s, want %s", c.Type, "")
}
if c.Text != nil {
t.Fatalf("Content text mismatch. got %s, want %s", *c.Text, "")
}
})
t.Run("returns single content", func(t *testing.T) {
m := anthropic.NewAssistantTextMessage("My name is Claude.")
c := m.GetFirstContent()
if c.Type != anthropic.MessagesContentTypeText {
t.Fatalf(
"Content type mismatch. got %s, want %s",
c.Type,
anthropic.MessagesContentTypeText,
)
}
if *c.Text != "My name is Claude." {
t.Fatalf("Content text mismatch. got %s, want %s", *c.Text, "My name is Claude.")
}
})
t.Run("returns first content when multiple content present", func(t *testing.T) {
m := anthropic.Message{
Role: anthropic.RoleAssistant,
Content: []anthropic.MessageContent{
anthropic.NewTextMessageContent("My name is Claude."),
anthropic.NewTextMessageContent("What is your name?"),
},
}
c := m.GetFirstContent()
if c.Type != anthropic.MessagesContentTypeText {
t.Fatalf(
"Content type mismatch. got %s, want %s",
c.Type,
anthropic.MessagesContentTypeText,
)
}
if *c.Text != "My name is Claude." {
t.Fatalf("Content text mismatch. got %s, want %s", *c.Text, "My name is Claude.")
}
})
}
func TestGetFirstContentText(t *testing.T) {
t.Run("returns empty text", func(t *testing.T) {
m := anthropic.MessagesResponse{}
if m.GetFirstContentText() != "" {
t.Fatalf("Content text mismatch. got %s, want %s", m.GetFirstContentText(), "")
}
})
t.Run("returns text", func(t *testing.T) {
m := anthropic.MessagesResponse{
Content: []anthropic.MessageContent{
anthropic.NewTextMessageContent("test string"),
},
}
if m.GetFirstContentText() != "test string" {
t.Fatalf("Content text mismatch. got %s, want %s", m.GetFirstContentText(), "")
}
})
}
func TestGetText(t *testing.T) {
t.Run("returns empty text", func(t *testing.T) {
c := anthropic.MessageContent{}
if c.GetText() != "" {
t.Fatalf("Content text mismatch. got %s, want %s", c.GetText(), "")
}
})
t.Run("returns text", func(t *testing.T) {
c := anthropic.NewTextMessageContent("My name is Claude.")
if c.GetText() != "My name is Claude." {
t.Fatalf("Content text mismatch. got %s, want %s", c.GetText(), "My name is Claude.")
}
})
}
func TestConcatText(t *testing.T) {
t.Run("concatenates text when text content text present", func(t *testing.T) {
mc := anthropic.NewTextMessageContent("original")
mc.ConcatText(" added")
if mc.GetText() != "original added" {
t.Fatalf("Content text mismatch. got %s, want %s", mc.GetText(), "original added")
}
})
t.Run("concatenates text when text content text not present", func(t *testing.T) {
mc := anthropic.MessageContent{}
mc.ConcatText("added")
if mc.GetText() != "added" {
t.Fatalf("Content text mismatch. got %s, want %s", mc.GetText(), "added")
}
})
}
func TestMessagesTokenError(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(rateLimitHeaders))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken()+"1",
anthropic.WithBaseURL(baseUrl),
)
_, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
})
checks.HasError(t, err, "should error")
var e *anthropic.RequestError
if !errors.As(err, &e) {
t.Log("should request error")
}
t.Logf("CreateMessages error: %s", err)
}
func TestMessagesVision(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(rateLimitHeaders))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
)
imagePath := "internal/test/sources/ant.jpg"
imageMediaType := "image/jpeg"
imageFile, err := sources.Open(imagePath)
if err != nil {
t.Fatal(err)
}
imageData, err := io.ReadAll(imageFile)
if err != nil {
t.Fatal(err)
}
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Opus20240229,
Messages: []anthropic.Message{
{
Role: anthropic.RoleUser,
Content: []anthropic.MessageContent{
anthropic.NewImageMessageContent(
anthropic.NewMessageContentSource(
anthropic.MessagesContentSourceTypeBase64,
imageMediaType,
imageData,
),
),
anthropic.NewTextMessageContent("Describe these images."),
},
},
},
MaxTokens: 1000,
})
if err != nil {
t.Fatal(err)
}
t.Logf("CreateMessages resp: %+v", resp)
}
func TestMessagesToolUse(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(rateLimitHeaders))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
)
request := anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is the weather like in San Francisco?"),
},
MaxTokens: 1000,
Tools: []anthropic.ToolDefinition{
{
Name: "get_weather",
Description: "Get the current weather in a given location",
InputSchema: jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"location": {
Type: jsonschema.String,
Description: "The city and state, e.g. San Francisco, CA",
},
"unit": {
Type: jsonschema.String,
Enum: []string{"celsius", "fahrenheit"},
Description: "The unit of temperature, either 'celsius' or 'fahrenheit'",
},
},
Required: []string{"location"},
},
},
},
}
resp, err := client.CreateMessages(context.Background(), request)
if err != nil {
t.Fatal(err)
}
request.Messages = append(request.Messages, anthropic.Message{
Role: anthropic.RoleAssistant,
Content: resp.Content,
})
var toolUse *anthropic.MessageContentToolUse
for _, c := range resp.Content {
if c.Type == anthropic.MessagesContentTypeToolUse {
toolUse = c.MessageContentToolUse
t.Logf("ToolUse: %+v", toolUse)
} else {
t.Logf("Content: %+v", c)
}
}
if toolUse == nil {
t.Fatal("tool use not found")
}
request.Messages = append(
request.Messages,
anthropic.NewToolResultsMessage(toolUse.ID, "65 degrees", false),
)
resp, err = client.CreateMessages(context.Background(), request)
if err != nil {
t.Fatal(err)
}
t.Logf("CreateMessages resp: %+v", resp)
var hasDegrees bool
for _, m := range resp.Content {
if m.Type == anthropic.MessagesContentTypeText {
if strings.Contains(m.GetText(), "65 degrees") {
hasDegrees = true
break
}
}
}
if !hasDegrees {
t.Fatalf("Expected response to contain '65 degrees', got: %+v", resp.Content)
}
}
func TestMessagesRateLimitHeaders(t *testing.T) {
expectedSuccess := map[string]any{
"anthropic-ratelimit-requests-limit": 100,
"anthropic-ratelimit-requests-remaining": 99,
"anthropic-ratelimit-requests-reset": "2024-06-04T07:13:19Z",
"anthropic-ratelimit-tokens-limit": 10000,
"anthropic-ratelimit-tokens-remaining": 9900,
"anthropic-ratelimit-tokens-reset": "2024-06-04T07:13:19Z",
"retry-after": -1, // if not present, should be -1
}
requestFailRateLimitHeaders := make(map[string]string)
for k, v := range rateLimitHeaders {
requestFailRateLimitHeaders[k] = v
}
requestFailRateLimitHeaders["retry-after"] = "10"
expectedFail := make(map[string]any)
for k, v := range expectedSuccess {
expectedFail[k] = v
}
expectedFail["retry-after"] = 10
headerConfigs := []struct {
name string
header map[string]string
expected map[string]any
}{
{
name: "parses rate limit headers for successful request",
header: rateLimitHeaders,
expected: expectedSuccess,
},
{
name: "parses rate limit headers for failed request",
header: requestFailRateLimitHeaders,
expected: expectedFail,
},
}
for _, c := range headerConfigs {
t.Run(c.name, func(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(c.header))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
)
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
rlHeaders, err := resp.GetRateLimitHeaders()
if err != nil {
t.Fatalf("GetRateLimitHeaders error: %v", err)
}
bs, err := json.Marshal(rlHeaders)
if err != nil {
t.Fatal(err)
}
bs2, err := json.Marshal(c.expected)
if err != nil {
t.Fatal(err)
}
if string(bs) != string(bs2) {
t.Fatalf("rate limit headers mismatch. got %s, want %s", string(bs), string(bs2))
}
})
}
t.Run("returns error for missing rate limit headers", func(t *testing.T) {
invalidHeaders := map[string]string{}
resp, err := getRespWithHeaders(invalidHeaders)
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
_, err = resp.GetRateLimitHeaders()
if err == nil {
t.Fatal("expected error, got nil")
}
})
}
func TestMessagesWithCaching(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(rateLimitHeaders))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
anthropic.WithAPIVersion(anthropic.APIVersion20230601),
anthropic.WithEmptyMessagesLimit(100),
anthropic.WithHTTPClient(http.DefaultClient),
)
t.Run("caches single message", func(t *testing.T) {
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
{
Role: anthropic.RoleUser,
Content: []anthropic.MessageContent{
{
Type: anthropic.MessagesContentTypeText,
Text: toPtr("Is there a doctor on board?"),
CacheControl: &anthropic.MessageCacheControl{
Type: anthropic.CacheControlTypeEphemeral,
},
},
},
},
},
MaxTokens: 1000,
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
t.Logf("CreateMessages resp: %+v", resp)
})
t.Run("caches a multi-system message", func(t *testing.T) {
resp, err := client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
MultiSystem: []anthropic.MessageSystemPart{
{
Type: "text",
Text: "You are on a plane. You hear a voice over the intercom: 'Is there a doctor on board?'",
},
{
Type: "text",
Text: "<the entire contents of the safety card, the safety demonstration, and your medical training>",
CacheControl: &anthropic.MessageCacheControl{
Type: anthropic.CacheControlTypeEphemeral,
},
},
},
Messages: []anthropic.Message{
{
Role: anthropic.RoleUser,
Content: []anthropic.MessageContent{
{
Type: anthropic.MessagesContentTypeText,
Text: toPtr("Is there a doctor on board?"),
},
},
},
},
MaxTokens: 1000,
})
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
t.Logf("CreateMessages resp: %+v", resp)
})
}
func TestSetCacheControl(t *testing.T) {
mc := anthropic.MessageContent{
Type: anthropic.MessagesContentTypeText,
Text: toPtr("hello"),
}
t.Run("sets cache control", func(t *testing.T) {
mc.SetCacheControl(anthropic.CacheControlTypeEphemeral)
if mc.CacheControl == nil {
t.Fatal("expected cache control to be set")
}
if mc.CacheControl.Type != anthropic.CacheControlTypeEphemeral {
t.Fatalf(
"expected cache control type to be %s, got %s",
anthropic.CacheControlTypeEphemeral,
mc.CacheControl.Type,
)
}
})
}
func TestMessagesRequest_MarshalJSON(t *testing.T) {
t.Run("marshals MessagesRequest with system", func(t *testing.T) {
req := anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
System: "test",
}
bs, err := json.Marshal(req)
if err != nil {
t.Fatal(err)
}
expected := `{"system":"test","model":"claude-3-haiku-20240307","messages":[{"role":"user","content":[{"type":"text","text":"What is your name?"}]}],"max_tokens":1000}`
if string(bs) != expected {
t.Fatalf(
"marshalled MessagesRequest mismatch. \ngot %s, \nwant %s",
string(bs),
expected,
)
}
})
t.Run("marshals MessagesRequest with multi system", func(t *testing.T) {
req := anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
MultiSystem: []anthropic.MessageSystemPart{
{
Type: "text",
Text: "test",
},
},
}
bs, err := json.Marshal(req)
if err != nil {
t.Fatal(err)
}
expected := `{"system":[{"type":"text","text":"test"}],"model":"claude-3-haiku-20240307","messages":[{"role":"user","content":[{"type":"text","text":"What is your name?"}]}],"max_tokens":1000}`
if string(bs) != expected {
t.Fatalf(
"marshalled MessagesRequest mismatch. \ngot %s, \nwant %s",
string(bs),
expected,
)
}
})
t.Run("marshals MessagesRequest with no system", func(t *testing.T) {
req := anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
}
bs, err := json.Marshal(req)
if err != nil {
t.Fatal(err)
}
expected := `{"model":"claude-3-haiku-20240307","messages":[{"role":"user","content":[{"type":"text","text":"What is your name?"}]}],"max_tokens":1000}`
if string(bs) != expected {
t.Fatalf(
"marshalled MessagesRequest mismatch. \ngot %s, \nwant %s",
string(bs),
expected,
)
}
})
}
func TestUsageHeaders(t *testing.T) {
resp, err := getRespWithHeaders(rateLimitHeaders)
if err != nil {
t.Fatalf("CreateMessages error: %v", err)
}
usage := resp.Usage
if usage.InputTokens != 10 {
t.Fatalf("InputTokens mismatch. got %d, want 10", usage.InputTokens)
}
if usage.OutputTokens != 10 {
t.Fatalf("OutputTokens mismatch. got %d, want 10", usage.OutputTokens)
}
if usage.CacheCreationInputTokens != 0 {
t.Fatalf(
"CacheCreationInputTokens mismatch. got %d, want 0",
usage.CacheCreationInputTokens,
)
}
if usage.CacheReadInputTokens != 0 {
t.Fatalf("CacheReadInputTokens mismatch. got %d, want 0", usage.CacheReadInputTokens)
}
}
func getRespWithHeaders(headers map[string]string) (anthropic.MessagesResponse, error) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages", handleMessagesEndpoint(headers))
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
)
return client.CreateMessages(context.Background(), anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Haiku20240307,
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
},
MaxTokens: 1000,
})
}
// Allows for injection of custom rate limit headers in the response to test client parsing.
func handleMessagesEndpoint(headers map[string]string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var err error
var resBytes []byte
// completions only accepts POST requests
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
var messagesReq anthropic.MessagesRequest
if messagesReq, err = getRequest[anthropic.MessagesRequest](r); err != nil {
http.Error(w, "could not read request", http.StatusInternalServerError)
return
}
var hasToolResult bool
for _, m := range messagesReq.Messages {
for _, c := range m.Content {
if c.Type == anthropic.MessagesContentTypeToolResult {
hasToolResult = true
break
}
}
}
res := anthropic.MessagesResponse{
Type: "completion",
ID: strconv.Itoa(int(time.Now().Unix())),
Role: anthropic.RoleAssistant,
Content: []anthropic.MessageContent{
anthropic.NewTextMessageContent("hello"),
},
StopReason: anthropic.MessagesStopReasonEndTurn,
Model: messagesReq.Model,
Usage: anthropic.MessagesUsage{
InputTokens: 10,
OutputTokens: 10,
},
}
if len(messagesReq.Tools) > 0 {
if hasToolResult {
res.Content = []anthropic.MessageContent{
anthropic.NewTextMessageContent(
"The current weather in San Francisco is 65 degrees Fahrenheit. It's a nice, moderate temperature typical of the San Francisco Bay Area climate.",
),
}
} else {
m := map[string]any{
"location": "San Francisco, CA",
"unit": "celsius",
}
bs, _ := json.Marshal(m)
res.Content = []anthropic.MessageContent{
anthropic.NewTextMessageContent("Okay, let me check the weather in San Francisco:"),
anthropic.NewToolUseMessageContent("toolu_01Ex86JyJAe8RSbFRCTM3pQo", "get_weather", bs),
}
res.StopReason = anthropic.MessagesStopReasonToolUse
}
}
resBytes, _ = json.Marshal(res)
for k, v := range headers {
w.Header().Set(k, v)
}
_, _ = w.Write(resBytes)
}
}