-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathestimator.go
More file actions
60 lines (54 loc) · 1.54 KB
/
Copy pathestimator.go
File metadata and controls
60 lines (54 loc) · 1.54 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
package contexty
import (
"context"
"fmt"
)
// TokenEstimator counts tokens in semantic messages (provider-agnostic).
type TokenEstimator interface {
Estimate(ctx context.Context, msgs []Message) (int, error)
EstimatePerMessage(ctx context.Context, msgs []Message) ([]int, error)
}
// CharTokenEstimator uses rune count as a deterministic test estimator.
type CharTokenEstimator struct{}
// Estimate returns total rune count across text and tool parts.
func (CharTokenEstimator) Estimate(ctx context.Context, msgs []Message) (int, error) {
if err := ctx.Err(); err != nil {
return 0, fmt.Errorf("contexty: estimate tokens: %w", err)
}
per, err := CharTokenEstimator{}.EstimatePerMessage(ctx, msgs)
if err != nil {
return 0, err
}
total := 0
for _, n := range per {
total += n
}
return total, nil
}
// EstimatePerMessage returns per-message rune weights.
func (CharTokenEstimator) EstimatePerMessage(ctx context.Context, msgs []Message) ([]int, error) {
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("contexty: estimate per message: %w", err)
}
weights := make([]int, len(msgs))
for i, m := range msgs {
weights[i] = messageRuneWeight(m)
}
return weights, nil
}
func messageRuneWeight(m Message) int {
n := 0
for _, p := range m.Parts {
switch v := p.(type) {
case TextPart:
n += len([]rune(v.Text))
case ImagePart:
n += len(v.URL)
case ToolCallPart:
n += len(v.Name) + len(v.Arguments.PlainText()) + len(v.ID)
case ToolResultPart:
n += len(v.Payload.PlainText()) + len(v.ToolCallID)
}
}
return n
}