/
main.go
183 lines (158 loc) · 3.67 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
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"strings"
openai "github.com/sashabaranov/go-openai"
)
const kMaxTokens = 4000
func main() {
apiKey, err := getAPIKey()
if err != nil {
printError(err)
printError(errors.New("hint: you can set OPENAI_API_KEY environment " +
"variable or create askai_config.yaml file with your API key"))
return
}
c := openai.NewClient(apiKey)
ctx := context.Background()
if len(os.Args) > 1 {
if os.Args[1] == "help" {
printUsage()
return
}
prompt := ""
for _, arg := range os.Args[1:] {
prompt += arg + " "
}
simpleMode(c, ctx, prompt)
return
}
fmt.Println("Welcome to askai! Type 'help' to see available commands.")
history := []openai.ChatCompletionMessage{}
for {
reader := bufio.NewReader(os.Stdin)
fmt.Print("> ")
text, err := reader.ReadString('\n')
if err != nil {
printError(err)
continue
}
text = strings.TrimSpace(text)
switch text {
case "exit":
return
case "help":
printUsage()
continue
case "clear":
history = []openai.ChatCompletionMessage{}
fmt.Println("Chat history cleared.")
continue
default:
// handle other input cases
}
req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
MaxTokens: kMaxTokens,
Messages: history,
Stream: true,
}
req.Messages = append(req.Messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: text,
})
stream, err := c.CreateChatCompletionStream(ctx, req)
if err != nil {
printError(err)
continue
}
historyText := ""
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
stream.Close()
break
}
if err != nil {
printError(err)
stream.Close()
break
}
delta := response.Choices[0].Delta.Content
fmt.Print(delta)
historyText += delta
}
fmt.Println()
history = append(history, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: historyText,
})
}
}
func printUsage() {
fmt.Println("Available commands:")
fmt.Println(" help - show this message")
fmt.Println(" exit - exit the program")
fmt.Println(" clear - clear chat history")
}
func getAPIKey() (string, error) {
apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey != "" {
return apiKey, nil
}
file, err := os.Open("askai_config.yaml")
if err != nil {
return "", fmt.Errorf("failed to open config file: %w", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "api_key:") {
return strings.TrimSpace(strings.TrimPrefix(line, "api_key:")), nil
}
}
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("failed to read config file: %w", err)
}
return "", errors.New("API key not found")
}
func printError(err error) {
fmt.Fprintf(os.Stderr, "\x1b[31mError: %v\x1b[0m\n", err)
}
// simpleMode is a simple mode of askai that takes a prompt and prints the result to stdout.
func simpleMode(c *openai.Client, ctx context.Context, prompt string) {
req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
MaxTokens: kMaxTokens,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: prompt,
},
},
Stream: true,
}
stream, err := c.CreateChatCompletionStream(ctx, req)
if err != nil {
printError(fmt.Errorf("chatCompletionStream error: %v", err))
return
}
defer stream.Close()
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
return
}
if err != nil {
printError(fmt.Errorf("\nstream error: %v", err))
return
}
fmt.Printf(response.Choices[0].Delta.Content)
}
}