-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgotok.go
129 lines (111 loc) · 3.92 KB
/
gotok.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/pkoukk/tiktoken-go"
)
func printHelp() {
fmt.Println(`gotok: Token counting utility
Usage:
gotok [options] < [input]
Options:
--model string Use the embedding for this model (default: gpt-4o)
--encoding string Use this specific encoding (overrides model if set)
--input string Path to input file
--output string Output destination: stderr, stdout, or a file path (default: stderr)
--passthrough Pass the input to stdout (default: false)
--quiet Quiet mode: output token count only, suppresses passthrough
--list List available models and encodings
Notes:
- If both --input and stdin are provided, contents are concatenated.
- You can use '<' for stdin input, e.g., gotok < input.txt.
`)
}
func main() {
// Override the default usage message
flag.Usage = printHelp
// Define flags
model := flag.String("model", "gpt-4o", "Use the embedding for this model.")
encoding := flag.String("encoding", "o200k_base", "Use this specific encoding.")
inputFile := flag.String("input", "", "Path to input file.")
outputFile := flag.String("output", "stderr", "Output destination: stderr, stdout, or a file path.")
passthrough := flag.Bool("passthrough", false, "If true, pass the input to stdout.")
quiet := flag.Bool("quiet", false, "Quiet mode: output token count only.")
list := flag.Bool("list", false, "List available models and encodings.")
// Parse flags
flag.Parse()
// Display help if no arguments are provided and no input is provided on stdin
fileInfo, _ := os.Stdin.Stat()
if len(os.Args) == 1 && (fileInfo.Mode()&os.ModeCharDevice) != 0 {
printHelp()
os.Exit(0)
}
// Display available models and encodings if --list is provided
if *list {
fmt.Println("Available models and encodings:")
for m, tke := range tiktoken.MODEL_TO_ENCODING {
fmt.Printf("%-30v (%s)\n", m, tke)
}
return
}
// Read input from stdin and input file if provided
var input []byte
if *inputFile != "" {
fileData, err := ioutil.ReadFile(*inputFile)
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading input file:", err)
os.Exit(1)
}
input = append(input, fileData...)
}
stdinData, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading from stdin:", err)
os.Exit(1)
}
input = append(input, stdinData...)
// Initialize tokenizer based on model or encoding
var enc *tiktoken.Tiktoken
var encName string
if *encoding != "" {
enc, err = tiktoken.GetEncoding(*encoding)
encName = *encoding
} else {
enc, err = tiktoken.EncodingForModel(*model)
encName = tiktoken.MODEL_TO_ENCODING[*model]
}
if err != nil {
fmt.Fprintln(os.Stderr, "Error initializing tokenizer:", err)
os.Exit(1)
}
// Tokenize input and count tokens
tokens := enc.Encode(string(input), nil, nil)
tokenCount := len(tokens)
charCount := len(input)
// Construct output message
outputMsg := fmt.Sprintf("gotok: encoding=%s; chars=%d; tokens=%d\n", encName, charCount, tokenCount)
// Handle --quiet mode
if *quiet {
fmt.Printf("%d\n", tokenCount)
return
}
// Output result
if *outputFile == "stderr" {
fmt.Fprint(os.Stderr, outputMsg)
} else if *outputFile == "stdout" {
fmt.Print(outputMsg)
} else {
// Write to specified file
err := ioutil.WriteFile(*outputFile, []byte(outputMsg), 0644)
if err != nil {
fmt.Fprintln(os.Stderr, "Error writing to file:", err)
os.Exit(1)
}
}
// Conditionally pass input to stdout based on --passthrough
if *passthrough && !*quiet {
fmt.Print(string(input))
}
}