Skip to content

Commit 7e60c02

Browse files
committed
Add token count command
1 parent a96f805 commit 7e60c02

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

cmd/count.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Copyright © 2023 Chandler <chandler@chand1012.dev>
3+
*/
4+
package cmd
5+
6+
import (
7+
"fmt"
8+
"os"
9+
10+
"github.com/chand1012/ottodocs/pkg/calc"
11+
"github.com/chand1012/ottodocs/pkg/config"
12+
"github.com/chand1012/ottodocs/pkg/utils"
13+
"github.com/spf13/cobra"
14+
)
15+
16+
// countCmd represents the count command
17+
var countCmd = &cobra.Command{
18+
Use: "count",
19+
Short: "Count tokens in given context and prompt",
20+
Long: `This command calculates the token count of the given context and prompt.
21+
It takes the context and prompt files as input.
22+
23+
Example usage:
24+
25+
otto count -c contextfile.txt -g "prompt"`,
26+
Run: func(cmd *cobra.Command, args []string) {
27+
c, err := config.Load()
28+
if err != nil {
29+
log.Errorf("Error loading config: %s", err)
30+
os.Exit(1)
31+
}
32+
33+
var prompt string
34+
35+
if chatPrompt == "" && len(contextFiles) == 0 {
36+
log.Error("Requires a prompt or context file as an argument. Example: otto count -c contextfile.txt -g \"prompt\"")
37+
os.Exit(1)
38+
}
39+
40+
if chatPrompt != "" {
41+
prompt = "GOAL:" + chatPrompt
42+
}
43+
44+
for _, contextFile := range contextFiles {
45+
content, err := utils.LoadFile(contextFile)
46+
if err != nil {
47+
log.Errorf("Error loading file: %s", err)
48+
os.Exit(1)
49+
}
50+
prompt += "\n\nFILE: " + contextFile + "\n\n" + content + "\n"
51+
}
52+
53+
tokens, err := calc.PreciseTokens(prompt)
54+
if err != nil {
55+
log.Errorf("Error calculating tokens: %s", err)
56+
os.Exit(1)
57+
}
58+
59+
utils.PrintColoredText("Token count: ", c.OttoColor)
60+
fmt.Println(tokens)
61+
},
62+
}
63+
64+
func init() {
65+
RootCmd.AddCommand(countCmd)
66+
67+
countCmd.Flags().StringVarP(&chatPrompt, "goal", "g", "", "Prompt for token count")
68+
countCmd.Flags().StringSliceVarP(&contextFiles, "context", "c", []string{}, "Context files")
69+
}

0 commit comments

Comments
 (0)