forked from kardolus/chatgpt-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
277 lines (241 loc) · 7.01 KB
/
main.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package main
import (
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"github.com/chzyer/readline"
"github.com/kardolus/chatgpt-cli/client"
"github.com/kardolus/chatgpt-cli/config"
"github.com/kardolus/chatgpt-cli/configmanager"
"github.com/kardolus/chatgpt-cli/history"
"github.com/kardolus/chatgpt-cli/http"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
queryMode bool
clearHistory bool
showVersion bool
showConfig bool
interactiveMode bool
listModels bool
listThreads bool
modelName string
threadName string
maxTokens int
contextWindow int
GitCommit string
GitVersion string
ServiceURL string
shell string
)
func main() {
var rootCmd = &cobra.Command{
Use: "chatgpt",
Short: "ChatGPT CLI Tool",
Long: "A powerful ChatGPT client that enables seamless interactions with the GPT model. " +
"Provides multiple modes and context management features, including the ability to " +
"pipe custom context into the conversation.",
RunE: run,
SilenceUsage: true,
SilenceErrors: true,
}
rootCmd.PersistentFlags().BoolVarP(&interactiveMode, "interactive", "i", false, "Use interactive mode")
rootCmd.PersistentFlags().BoolVarP(&queryMode, "query", "q", false, "Use query mode instead of stream mode")
rootCmd.PersistentFlags().BoolVar(&clearHistory, "clear-history", false, "Clear all prior conversation context for the current thread")
rootCmd.PersistentFlags().BoolVarP(&showConfig, "config", "c", false, "Display the configuration")
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "Display the version information")
rootCmd.PersistentFlags().BoolVarP(&listModels, "list-models", "l", false, "List available models")
rootCmd.PersistentFlags().BoolVarP(&listThreads, "list-threads", "", false, "List available threads")
rootCmd.PersistentFlags().StringVar(&modelName, "set-model", "", "Set a new default GPT model by specifying the model name")
rootCmd.PersistentFlags().StringVar(&threadName, "set-thread", "", "Set a new active thread by specifying the thread name")
rootCmd.PersistentFlags().StringVar(&threadName, "delete-thread", "", "Delete the specified thread")
rootCmd.PersistentFlags().StringVar(&shell, "set-completions", "", "Generate autocompletion script for your current shell")
rootCmd.PersistentFlags().IntVar(&maxTokens, "set-max-tokens", 0, "Set a new default max token size by specifying the max tokens")
rootCmd.PersistentFlags().IntVar(&contextWindow, "set-context-window", 0, "Set a new default context window size")
viper.AutomaticEnv()
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func run(cmd *cobra.Command, args []string) error {
// Flags that do not require an API key
if showVersion {
fmt.Printf("ChatGPT CLI version %s (commit %s)\n", GitVersion, GitCommit)
return nil
}
if cmd.Flag("set-completions").Changed {
return config.GenCompletions(cmd, shell)
}
if cmd.Flag("set-model").Changed {
cm := configmanager.New(config.New())
if err := cm.WriteModel(modelName); err != nil {
return err
}
fmt.Println("Model successfully updated to", modelName)
return nil
}
if cmd.Flag("set-max-tokens").Changed {
cm := configmanager.New(config.New())
if err := cm.WriteMaxTokens(maxTokens); err != nil {
return err
}
fmt.Println("Max tokens successfully updated to", maxTokens)
return nil
}
if cmd.Flag("set-context-window").Changed {
cm := configmanager.New(config.New())
if err := cm.WriteContextWindow(contextWindow); err != nil {
return err
}
fmt.Println("Context window successfully updated to", contextWindow)
return nil
}
if cmd.Flag("set-thread").Changed {
cm := configmanager.New(config.New())
if err := cm.WriteThread(threadName); err != nil {
return err
}
fmt.Println("Thread successfully updated to", threadName)
return nil
}
if cmd.Flag("delete-thread").Changed {
cm := configmanager.New(config.New())
if err := cm.DeleteThread(threadName); err != nil {
return err
}
fmt.Printf("Successfully deleted thead %s\n", threadName)
return nil
}
if listThreads {
cm := configmanager.New(config.New())
threads, err := cm.ListThreads()
if err != nil {
return err
}
fmt.Println("Available threads:")
for _, thread := range threads {
fmt.Println(thread)
}
return nil
}
if clearHistory {
cm := configmanager.New(config.New())
if err := cm.DeleteThread(cm.Config.Thread); err != nil {
return err
}
fmt.Println("History successfully cleared.")
return nil
}
if showConfig {
cm := configmanager.New(config.New()).WithEnvironment()
if c, err := cm.ShowConfig(); err != nil {
return err
} else {
fmt.Println(c)
}
return nil
}
// Flags that require an API key
hs, _ := history.New() // do not error out
client, err := client.New(http.RealCallerFactory, config.New(), hs)
if err != nil {
return err
}
if ServiceURL != "" {
client = client.WithServiceURL(ServiceURL)
}
// Check if there is input from the pipe (stdin)
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
pipeContent, err := io.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("failed to read from pipe: %w", err)
}
client.ProvideContext(string(pipeContent))
}
if listModels {
models, err := client.ListModels()
if err != nil {
return err
}
fmt.Println("Available models:")
for _, model := range models {
fmt.Println(model)
}
return nil
}
if interactiveMode {
fmt.Printf("Entering interactive mode. Type 'exit' and press Enter or press Ctrl+C to quit.\n\n")
rl, err := readline.New("")
if err != nil {
return err
}
defer rl.Close()
prompt := func(counter string) string {
cm := configmanager.New(config.New())
if len(cm.Config.CommandPrompt) != 0 {
return cm.Config.CommandPrompt
} else {
return fmt.Sprintf("[%s] [%s]: ", time.Now().Format("2006-01-02 15:04:05"), counter)
}
}
qNum, usage := 1, 0
for {
if queryMode {
rl.SetPrompt(prompt(strconv.Itoa(usage)))
} else {
rl.SetPrompt(prompt(fmt.Sprintf("Q%d", qNum)))
}
line, err := rl.Readline()
if err == readline.ErrInterrupt || err == io.EOF {
fmt.Println("Bye!")
break
}
if line == "exit" || line == "/q" {
fmt.Println("Bye!")
if queryMode {
fmt.Printf("Total tokens used: %d\n", usage)
}
break
}
if queryMode {
result, qUsage, err := client.Query(line)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("%s\n\n", result)
usage += qUsage
}
} else {
if err := client.Stream(line); err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println()
qNum++
}
}
}
} else {
if len(args) == 0 {
return errors.New("you must specify your query")
}
if queryMode {
result, _, err := client.Query(strings.Join(args, " "))
if err != nil {
return err
}
fmt.Println(result)
} else {
if err := client.Stream(strings.Join(args, " ")); err != nil {
return err
}
}
}
return nil
}