-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
434 lines (380 loc) · 11.3 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/fatih/color"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh/terminal"
"io"
"log"
"os"
"os/exec"
"regexp"
"runtime/debug"
"sort"
"strings"
)
type Model string
func (m *Model) String() string {
return string(*m)
}
func (m *Model) Set(value string) error {
*m = Model(value)
return nil
}
func main() {
defer func() {
if r := recover(); r != nil {
// This block will execute when a panic occurs.
// We can print a stack trace by calling debug.PrintStack.
debug.PrintStack()
fmt.Println("Panic:", r)
}
}()
var modelFlag Model = "gpt-4-0613"
flag.Var(&modelFlag, "model", "Model to use (e.g., gpt-4-0613 or gpt-3.5-turbo)")
debugFlag := flag.Bool("debug", false, "Enable debug mode")
executeFlag := flag.Bool("execute", false, "Execute the command instead of typing it out (dangerous!)")
textFlag := flag.Bool("text", false, "Enable text mode")
gpt3Flag := flag.Bool("3", false, "Shorthand for --model=gpt-3.5-turbo")
initFlag := flag.Bool("init", false, "Initialize AI")
listModelsFlag := flag.Bool("list-models", false, "List available models")
// Add shorthands
flag.Var(&modelFlag, "m", "Shorthand for model")
flag.BoolVar(debugFlag, "d", false, "Shorthand for debug")
flag.BoolVar(executeFlag, "x", false, "Shorthand for execute")
flag.Parse()
if initFlag != nil && *initFlag {
initApiKey()
}
aiClient := NewAIClient(getAPIKey(), modelFlag.String())
if *listModelsFlag {
listModels(aiClient)
os.Exit(0)
}
var mode = CommandMode
if *gpt3Flag {
modelFlag = "gpt-3.5-turbo"
}
if *textFlag {
mode = TextMode
if *debugFlag {
fmt.Println("Debug: Text mode enabled")
}
}
if *debugFlag {
fmt.Printf("Debug: Mode is %v\n", mode)
}
modelString := modelFlag.String()
userInput := ""
args := flag.Args()
if len(args) > 0 {
userInput = strings.Join(args, " ")
} else {
fmt.Println("Usage: ai [options] <natural language command>")
flag.PrintDefaults()
os.Exit(1)
}
if *debugFlag {
fmt.Println("Model:", modelFlag.String())
fmt.Println("Debug:", *debugFlag)
fmt.Println("User Input:", userInput)
}
functionCalled := false
isInteractive := isTerm(os.Stdin.Fd())
withPipedInput := !isInteractive
if withPipedInput {
stdinBytes, err := io.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
stdin := strings.TrimSpace(string(stdinBytes))
if len(stdin) > 0 {
userInput = fmt.Sprintf("%s\n\nUse the following additional context to improve your response:\n\n---\n\n%s\n", userInput, stdin)
}
}
if mode == CommandMode {
fmt.Printf("%s\r", color.YellowString("🤖 Thinking ..."))
}
var keyboard KeyboardInterface
if mode == CommandMode && !*executeFlag {
keyboard = NewKeyboard()
}
messages := generateChatGPTMessages(userInput, mode)
if *debugFlag {
fmt.Println("Debug: Messages generated")
for i, msg := range messages {
fmt.Printf("Debug: Message %d - Role: %s, Content: %.50s...\n", i, msg.Role, msg.Content)
}
for _, message := range messages {
fmt.Println(message.Content)
}
}
if mode == TextMode {
response, err := aiClient.ChatCompletion(messages)
if err != nil {
log.Fatalln(err)
}
if *debugFlag {
fmt.Printf("AI response (using model %s):\n", modelString)
}
fmt.Println(response)
} else {
chunkStream, err := aiClient.ChatCompletionStream(messages)
if err != nil {
panic(err)
}
defer chunkStream.Close()
if *debugFlag {
fmt.Println("Debug: Chat completion stream created")
}
var response = ""
var firstResponse = true
var functionName string
var functionArgs string
for {
// Clear the 'thinking' message on first chunk
if firstResponse {
firstResponse = false
color.Yellow("%s\r🤖", strings.Repeat(" ", 80))
}
chunkResponse, err := chunkStream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
fmt.Printf("\nStream error: %v\n", err)
return
}
if chunkResponse.Choices[0].Delta.FunctionCall != nil {
functionCalled = true
if chunkResponse.Choices[0].Delta.FunctionCall.Name != "" {
functionName = chunkResponse.Choices[0].Delta.FunctionCall.Name
}
if chunkResponse.Choices[0].Delta.FunctionCall.Arguments != "" {
functionArgs += chunkResponse.Choices[0].Delta.FunctionCall.Arguments
}
} else {
chunk := chunkResponse.Choices[0].Delta.Content
response += chunk
printChunk(chunk, isInteractive)
}
}
if *debugFlag {
fmt.Printf("Function called: %v\n", functionCalled)
if functionCalled {
fmt.Printf("Function name: %s\n", functionName)
fmt.Printf("Function arguments: %s\n", functionArgs)
}
}
if functionName == "return_command" {
var returnCommand ReturnCommandFunction
err := json.Unmarshal([]byte(functionArgs), &returnCommand)
if err != nil {
log.Fatalln("Error parsing function arguments:", err)
}
if returnCommand.Command == "" {
color.Yellow("No command returned. AI response:")
fmt.Println(response)
return
}
// Print the command in blue
color.Blue(returnCommand.Command)
// Check if required binaries are available
missingBinaries := checkBinaries(returnCommand.Binaries)
shell := getShellCached()
if len(missingBinaries) > 0 {
color.Yellow("Missing required binaries: %s", strings.Join(missingBinaries, ", "))
// Inform the AI about missing binaries and ask for an alternative
alternativeInput := fmt.Sprintf("The following binaries are missing: %s. Please provide a command to install these binaries, or if that's not possible, provide an alternative command that doesn't require these binaries. If installation instructions are complex, provide a brief explanation or a link to installation instructions.", strings.Join(missingBinaries, ", "))
alternativeMessages := append(messages, Message{Role: "user", Content: alternativeInput})
alternativeResponse, alternativeCommand := getAlternativeResponse(aiClient, alternativeMessages)
if alternativeCommand != nil && alternativeCommand.Command != "" {
fmt.Println("\nAI's alternative command:")
fmt.Println(alternativeCommand.Command)
// Check if required binaries for the alternative command are available
missingBinaries := checkBinaries(alternativeCommand.Binaries)
if len(missingBinaries) > 0 {
color.Yellow("The alternative command also requires missing binaries: %s", strings.Join(missingBinaries, ", "))
fmt.Println("\nAI's explanation:")
fmt.Println(alternativeResponse)
} else {
if *executeFlag {
executeCommands([]string{alternativeCommand.Command}, shell)
} else {
typeCommands([]string{alternativeCommand.Command}, keyboard, shell)
}
}
} else {
fmt.Println("\nAI's alternative response:")
fmt.Println(alternativeResponse)
}
return
}
executableCommands := []string{returnCommand.Command}
if *executeFlag {
executeCommands(executableCommands, shell)
} else {
if !keyboard.IsFocusTheSame() {
color.New(color.Faint).Println("Window focus changed during command generation.")
color.Unset()
if !withPipedInput {
fmt.Println("Press enter to continue")
fmt.Scanln()
}
}
typeCommands(executableCommands, keyboard, shell)
}
} else {
color.Yellow("No command returned. AI response:")
fmt.Println(response)
}
}
}
func listModels(aiClient *AIClient) {
models, err := aiClient.GetAvailableModels()
if err != nil {
fmt.Printf("Error fetching models: %v\n", err)
return
}
fmt.Println("Available models:")
sort.Strings(models)
for _, model := range models {
fmt.Println(model)
}
}
func printChunk(content string, isInteractive bool) {
if !isInteractive {
fmt.Print(content)
return
}
// Before lines that start with a hash, i.e. '\n#' or '^#', make the color green
commentRegex := regexp.MustCompile(`(?m)((\n|^)#)`)
var formattedContent = commentRegex.ReplaceAllString(content, fmt.Sprintf("%1s[%dm$1", "\x1b", color.FgGreen))
// Insert a color reset before each newline
var newlineRegex = regexp.MustCompile(`(?m)(\n)`)
formattedContent = newlineRegex.ReplaceAllString(formattedContent, fmt.Sprintf("%1s[%dm$1", "\x1b", color.Reset))
fmt.Print(formattedContent)
}
func executeCommands(commands []string, shell string) {
switch shell {
case "bash":
command := fmt.Sprintf("set -e\n%s", strings.Join(commands, "\n"))
err := executeCommand(command, shell)
if err != nil {
log.Fatalln(err)
}
case "powershell":
for _, command := range commands {
err := executeCommand(command, shell)
if err != nil {
log.Fatalln(err)
}
}
default:
log.Fatalf("Unsupported shell: %s", shell)
}
}
func executeCommand(command string, shell string) error {
var cmd *exec.Cmd
switch shell {
case "bash":
cmd = exec.Command("bash")
cmd.Stdin = strings.NewReader(command)
case "powershell":
cmd = exec.Command("powershell", "-Command", command)
default:
return fmt.Errorf("unsupported shell: %s", shell)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
type KeyboardInterface interface {
SendString(string)
SendNewLine()
IsFocusTheSame() bool
}
func typeCommands(executableCommands []string, keyboard KeyboardInterface, shell string) {
if len(executableCommands) == 0 {
return
}
if shell == "powershell" {
if len(executableCommands) == 1 {
keyboard.SendString(executableCommands[0])
return
}
keyboard.SendString("AiDo {\n")
for _, command := range executableCommands {
keyboard.SendString(command)
keyboard.SendNewLine()
}
keyboard.SendString("}")
} else {
if len(executableCommands) == 1 {
keyboard.SendString(executableCommands[0])
return
}
keyboard.SendString("(")
keyboard.SendNewLine()
for _, command := range executableCommands {
keyboard.SendString(command)
keyboard.SendNewLine()
}
keyboard.SendString(")")
}
}
func isTerm(fd uintptr) bool {
return terminal.IsTerminal(int(fd))
}
func checkBinaries(binaries []string) []string {
var missingBinaries []string
for _, binary := range binaries {
_, err := exec.LookPath(binary)
if err != nil {
missingBinaries = append(missingBinaries, binary)
}
}
return missingBinaries
}
func getAlternativeResponse(aiClient *AIClient, messages []Message) (string, *ReturnCommandFunction) {
chunkStream, err := aiClient.ChatCompletionStream(messages)
if err != nil {
panic(err)
}
defer chunkStream.Close()
var response string
var functionName string
var functionArgs string
var returnCommand *ReturnCommandFunction
for {
chunkResponse, err := chunkStream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
fmt.Printf("\nStream error: %v\n", err)
return "", nil
}
if chunkResponse.Choices[0].Delta.FunctionCall != nil {
if chunkResponse.Choices[0].Delta.FunctionCall.Name != "" {
functionName = chunkResponse.Choices[0].Delta.FunctionCall.Name
}
if chunkResponse.Choices[0].Delta.FunctionCall.Arguments != "" {
functionArgs += chunkResponse.Choices[0].Delta.FunctionCall.Arguments
}
} else if chunkResponse.Choices[0].Delta.Content != "" {
response += chunkResponse.Choices[0].Delta.Content
}
}
if functionName == "return_command" {
returnCommand = &ReturnCommandFunction{}
err := json.Unmarshal([]byte(functionArgs), returnCommand)
if err != nil {
log.Println("Error parsing function arguments:", err)
return response, nil
}
}
return response, returnCommand
}