-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokens.go
50 lines (41 loc) · 949 Bytes
/
tokens.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
package agent
import (
"context"
"encoding/json"
"github.com/tiktoken-go/tokenizer"
)
func EstimateTokens(ctx context.Context, t tokenizer.Codec, m *Message) (int, error) {
type functionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
}
content, err := m.Content(ctx)
if err != nil {
return 0, err
}
cm := struct {
Role string `json:"role"`
Name string `json:"name"`
Content string `json:"content"`
FunctionCall *functionCall `json:"functionCall,omitempty"`
}{
Role: string(m.Role),
Name: m.Name,
Content: content,
}
if m.FunctionCallName != "" {
cm.FunctionCall = &functionCall{
Name: m.FunctionCallName,
Arguments: m.FunctionCallArgs,
}
}
data, err := json.Marshal(m)
if err != nil {
return 0, err
}
tokens, _, err := t.Encode(string(data))
if err != nil {
return 0, err
}
return len(tokens), nil
}