-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (70 loc) · 1.78 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
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"github.com/sashabaranov/go-openai"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func GetResponse(client *openai.Client, ctx context.Context, question string) {
resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
Model: "gpt-3.5-turbo", // Use "gpt-4" for more advanced responses
Messages: []openai.ChatCompletionMessage{
{Role: "user", Content: question},
},
})
if err != nil {
fmt.Println("Error:", err)
os.Exit(13)
}
// Print the response from ChatGPT
fmt.Println(resp.Choices[0].Message.Content)
}
type NullWriter int
func (NullWriter) Write([]byte) (int, error) { return 0, nil }
func main() {
log.SetOutput(new(NullWriter)) // Disable logging
// Load API key from environment variables or .env file
viper.SetConfigFile(".env")
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Error reading config file:", err)
os.Exit(1)
}
apiKey := viper.GetString("API_KEY")
if apiKey == "" {
fmt.Println("Missing API KEY in .env file")
os.Exit(1)
}
ctx := context.Background()
client := openai.NewClient(apiKey)
// Set up the CLI application
rootCmd := &cobra.Command{
Use: "chatgpt",
Short: "Chat with ChatGPT in console.",
Run: func(cmd *cobra.Command, args []string) {
scanner := bufio.NewScanner(os.Stdin)
quit := false
for !quit {
fmt.Print("Say something ('quit' to end): ")
if !scanner.Scan() {
break
}
question := scanner.Text()
switch question {
case "quit":
quit = true
default:
GetResponse(client, ctx, question)
}
}
},
}
// Execute the CLI command
if err := rootCmd.Execute(); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
}