-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
373 lines (318 loc) · 8.68 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strings"
"github.com/atotto/clipboard"
"github.com/fatih/color"
openai "github.com/sashabaranov/go-openai"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// NOTE: GPT-4 is in limited beta
const defaultModel = openai.GPT3Dot5Turbo
var model = defaultModel
// coloring
var prompt *color.Color
var option *color.Color
var gptResponse *color.Color
var note *color.Color
const configApiKey = "api_key"
const configModel = "model"
// a conversation struct to record previous conversations as context for future message
var conversation []openai.ChatCompletionMessage
func configureCommand(cmd *cobra.Command, args []string) {
note.Println("OpenAI API key can be generated on https://platform.openai.com/account/api-keys")
note.Println("List of models available to use can be found at https://platform.openai.com/docs/models")
fmt.Println()
// Get input on api key
reader := bufio.NewReader(os.Stdin)
prompt.Print("Enter your OpenAI API key (press enter to use existing): ")
apiKey, _ := reader.ReadString('\n')
apiKey = strings.TrimSpace(apiKey)
if len(apiKey) == 0 {
apiKey = viper.GetString(configApiKey)
// if no existing api key found
if len(apiKey) == 0 {
fmt.Println("No existing API key found. Please generate one from https://platform.openai.com/account/api-keys")
os.Exit(1)
}
}
viper.Set(configApiKey, apiKey)
// get input on model
prompt.Printf("What model would you like to use (default=\"%s\", press enter to use): ", defaultModel)
model, _ := reader.ReadString('\n')
model = strings.TrimSpace(model)
if len(model) == 0 {
model = defaultModel
}
viper.Set(configModel, model)
// Write to config file
if err := viper.WriteConfig(); err != nil {
fmt.Println("Error writing config file:", err)
os.Exit(1)
}
fmt.Println("Configuration saved to config file:", viper.ConfigFileUsed(), "👏")
}
func generateCommand(cmd *cobra.Command, args []string) {
// Initialize the OpenAI API client with the API key from the config file
client, err := getClient()
if err != nil {
fmt.Println("Error initializing OpenAI API client:", err)
os.Exit(1)
}
// Get input from the user
reader := bufio.NewReader(os.Stdin)
prompt.Print("Describe your request: ")
sentence, _ := reader.ReadString('\n')
sentence = strings.TrimSpace(sentence)
// Generate a command line script from the sentence using OpenAI's GPT-3 API
_, script, err := generateScript(client, sentence)
if err != nil {
fmt.Println("Error generating script:", err)
os.Exit(1)
}
fmt.Println(script)
fmt.Println()
// Present the user with four options: execute, explain, edit, and chat
option.Print("[R] Run - ")
option.Print("[E] Explain - ")
option.Print("[C] Copy - ")
option.Println("[T] Chat with AI")
prompt.Print("Enter your choice: ")
choice, _ := reader.ReadString('\n')
choice = strings.TrimSpace(choice)
switch choice {
case "R", "r":
// Execute the script
if err := executeScript(script); err != nil {
fmt.Printf("Error executing script: %s\n", err.Error())
os.Exit(1)
}
case "E", "e":
// Explain the script
err := explainScript(client, script)
if err != nil {
fmt.Println("Error explaining script:", err)
os.Exit(1)
}
case "C", "c":
// Edit the script
copyScript(script)
case "T", "t":
// Chat with the AI
chatWithAI(client)
default:
fmt.Println("Invalid choice")
os.Exit(1)
}
}
func chatCommand(cmd *cobra.Command, args []string) {
client, err := getClient()
if err != nil {
fmt.Println("Error initializing OpenAI API client:", err)
os.Exit(1)
}
chatWithAI(client)
}
func getClient() (*openai.Client, error) {
// Get the API key from the config file
err := viper.ReadInConfig()
if err != nil {
return nil, err
}
apiKey := viper.GetString(configApiKey)
// Initialize the OpenAI API client with the API key
client := openai.NewClient(apiKey)
return client, nil
}
// read gpt response stream and print the stream tokens
func outputStream(stream *openai.ChatCompletionStream) {
for {
resp, err := stream.Recv()
if err == io.EOF {
fmt.Println()
return
} else if err != nil {
fmt.Println(err)
os.Exit(1)
}
if len(resp.Choices) == 0 {
fmt.Println()
return
}
gptResponse.Print(resp.Choices[0].Delta.Content)
}
}
func generateScript(client *openai.Client, sentence string) (string, string, error) {
conversation = append(conversation, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: "Generate the bash script for sentence with no explanation. sentence: " + sentence + " =>",
})
doneChan := make(chan bool)
bar := getProgressBar()
go showSpinner(bar, doneChan)
completion, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: model,
Messages: conversation,
},
)
doneChan <- true
bar.Finish()
if err != nil {
return "", "", err
}
script := completion.Choices[0].Message.Content
script = strings.TrimSpace(script)
script = strings.TrimPrefix(script, "```")
script = strings.TrimSuffix(script, "```")
script = strings.TrimSpace(script)
return completion.ID, script, nil
}
// Generate an explanation of the script
func explainScript(client *openai.Client, script string) error {
conversation = append(conversation, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: "Explain the script",
})
doneChan := make(chan bool)
bar := getProgressBar()
go showSpinner(bar, doneChan)
stream, err := client.CreateChatCompletionStream(
context.Background(),
openai.ChatCompletionRequest{
Model: model,
Messages: conversation,
},
)
doneChan <- true
bar.Finish()
if err != nil {
return err
}
outputStream(stream)
return nil
}
func copyScript(script string) error {
err := clipboard.WriteAll(script)
if err != nil {
return err
}
fmt.Println("Script copied to clipboard!")
return nil
}
func chatWithAI(client *openai.Client) {
// Start a chat session with OpenAI's GPT-3 API
note.Println("Enter your message below or type 'quit' to exit the chat:")
reader := bufio.NewReader(os.Stdin)
for {
prompt.Print("> ")
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading message:", err)
continue
}
message = strings.TrimSpace(message)
if message == "quit" {
break
}
conversation = append(conversation, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: "User: " + message + "\nAI:",
})
doneChan := make(chan bool)
bar := getProgressBar()
go showSpinner(bar, doneChan)
stream, err := client.CreateChatCompletionStream(
context.Background(),
openai.ChatCompletionRequest{
Model: model,
Messages: conversation,
},
)
doneChan <- true
bar.Finish()
if err != nil {
fmt.Println("Error generating AI response:", err)
continue
}
outputStream(stream)
fmt.Println()
}
}
var rootCmd = &cobra.Command{
Use: "gptc",
Short: "GPT-CLI: Supercharge your CLI with ChatGPT",
Version: "1.0.0",
Run: func(cmd *cobra.Command, args []string) {
if !viper.IsSet(configApiKey) || viper.GetString(configApiKey) == "" {
note.Println("It appears that you don't have an API key configured yet, let's do that first 🙌")
configureCmd.Run(cmd, args)
fmt.Println()
}
generateCmd.Run(cmd, args)
},
}
var configureCmd = &cobra.Command{
Use: "configure",
Aliases: []string{"c"},
Short: "Configure the OpenAI API key",
Run: configureCommand,
}
var generateCmd = &cobra.Command{
Use: "generate",
Aliases: []string{"g"},
Short: "Generate script based on your description",
Run: generateCommand,
}
var chatCmd = &cobra.Command{
Use: "chat",
Short: "Chat with AI",
Run: chatCommand,
}
func initConfig() {
// set up config file
home, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
configFilePath := fmt.Sprintf("%s/.gpt_cli.yaml", home)
viper.SetConfigFile(configFilePath)
_, err = os.OpenFile(configFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err)
return
}
// init config
if err = viper.ReadInConfig(); err != nil {
fmt.Println(err)
os.Exit(1)
}
if !viper.IsSet(configModel) {
model = defaultModel
}
}
func main() {
prompt = color.New(color.FgGreen, color.Bold)
option = color.New(color.FgYellow, color.Bold)
gptResponse = color.New(color.Italic)
note = color.New(color.Bold)
// initialize the conversation context
conversation = make([]openai.ChatCompletionMessage, 0)
// Initialize the CLI tool
rootCmd.AddCommand(configureCmd)
rootCmd.AddCommand(generateCmd)
rootCmd.AddCommand(chatCmd)
initConfig()
// Execute the CLI tool
if err := rootCmd.Execute(); err != nil {
fmt.Println("Error executing CLI tool:", err)
os.Exit(1)
}
}