-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcount_tokens_test.go
88 lines (73 loc) · 2.28 KB
/
count_tokens_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
package anthropic_test
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/liushuangls/go-anthropic/v2"
"github.com/liushuangls/go-anthropic/v2/internal/test"
)
func TestCountTokens(t *testing.T) {
server := test.NewTestServer()
server.RegisterHandler("/v1/messages/count_tokens", handleCountTokens)
ts := server.AnthropicTestServer()
ts.Start()
defer ts.Close()
baseUrl := ts.URL + "/v1"
client := anthropic.NewClient(
test.GetTestToken(),
anthropic.WithBaseURL(baseUrl),
anthropic.WithBetaVersion(anthropic.BetaTokenCounting20241101),
)
request := anthropic.MessagesRequest{
Model: anthropic.ModelClaude3Dot5HaikuLatest,
MultiSystem: anthropic.NewMultiSystemMessages("you are an assistant", "you are snarky"),
Messages: []anthropic.Message{
anthropic.NewUserTextMessage("What is your name?"),
anthropic.NewAssistantTextMessage("My name is Claude."),
anthropic.NewUserTextMessage("What is your favorite color?"),
},
}
t.Run("count tokens success", func(t *testing.T) {
resp, err := client.CountTokens(context.Background(), request)
if err != nil {
t.Fatalf("CountTokens error: %v", err)
}
t.Logf("CountTokens resp: %+v", resp)
})
t.Run("count tokens failure", func(t *testing.T) {
request.MaxTokens = 10
_, err := client.CountTokens(context.Background(), request)
if err == nil {
t.Fatalf("CountTokens expected error, got nil")
}
t.Logf("CountTokens error: %v", err)
})
}
func handleCountTokens(w http.ResponseWriter, r *http.Request) {
var err error
var resBytes []byte
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
var req anthropic.MessagesRequest
if req, err = getRequest[anthropic.MessagesRequest](r); err != nil {
http.Error(w, "could not read request", http.StatusInternalServerError)
return
}
if req.MaxTokens > 0 {
http.Error(w, "max_tokens: Extra inputs are not permitted", http.StatusBadRequest)
return
}
betaHeaders := r.Header.Get("Anthropic-Beta")
if !strings.Contains(betaHeaders, string(anthropic.BetaTokenCounting20241101)) {
http.Error(w, "missing beta version header", http.StatusBadRequest)
return
}
res := anthropic.CountTokensResponse{
InputTokens: 100,
}
resBytes, _ = json.Marshal(res)
_, _ = w.Write(resBytes)
}