-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
194 lines (173 loc) · 4.75 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
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/sashabaranov/go-openai"
)
const (
defaultModel = openai.GPT4oMini
sessionFile = "/tmp/chatgpt-cli-last-session.json"
)
type params struct {
maxTokens int
systemMsg string
includeFile string
temperature float64
continueSession bool
msg string
}
func main() {
p := parseArgs()
client := getClient()
model := os.Getenv("OPENAI_MODEL")
if model == "" {
model = defaultModel
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
req := getCompletionRequest(p, model)
req = appendMessages(req, p)
fullResponse, err := streamCompletion(ctx, client, req, func(chunk string) error {
_, err := fmt.Print(chunk)
return err
})
fmt.Println()
if err != nil {
panic(err)
}
req.Messages = append(req.Messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleAssistant, Content: fullResponse})
err = saveCompletion(req)
if err != nil {
panic(err)
}
}
func parseArgs() params {
// var versions of flags from main, returning a params struct
var p params
flag.IntVar(&p.maxTokens, "maxTokens", 500, "Maximum number of tokens to generate")
flag.StringVar(&p.systemMsg, "systemMsg", "", "System message to include with the prompt")
flag.StringVar(&p.includeFile, "includeFile", "", "File to include with the prompt")
flag.Float64Var(&p.temperature, "temperature", 0, "ChatGPT temperature")
flag.BoolVar(&p.continueSession, "c", false, "Continue last session (ignores other flags)")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] message\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
msg := strings.TrimSpace(strings.Join(flag.Args(), " "))
if msg == "" {
flag.Usage()
os.Exit(1)
} else if msg == "-" {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
msg += scanner.Text() + "\n"
}
}
p.msg = msg
return p
}
func getClient() *openai.Client {
apiKey := os.Getenv("OPENAI_API_KEY")
url := os.Getenv("OPENAI_AZURE_ENDPOINT")
if url != "" {
deployment := os.Getenv("OPENAI_AZURE_MODEL")
config := openai.DefaultAzureConfig(apiKey, url)
config.AzureModelMapperFunc = func(model string) string {
if deployment != "" {
return deployment
}
return model
}
return openai.NewClientWithConfig(config)
}
return openai.NewClient(apiKey)
}
func getCompletionRequest(p params, model string) openai.ChatCompletionRequest {
if p.continueSession {
req := loadLastCompletion()
if req != nil {
return *req
}
fmt.Println("WARN: failed to load previous session, starting a new one")
}
return newCompletionRequest(p, model)
}
func loadLastCompletion() *openai.ChatCompletionRequest {
var req openai.ChatCompletionRequest
session, err := os.ReadFile(sessionFile)
if err != nil {
return nil
}
err = json.Unmarshal(session, &req)
if err != nil {
return nil
}
return &req
}
func saveCompletion(req openai.ChatCompletionRequest) error {
resJson, err := json.Marshal(req)
if err != nil {
return err
}
return os.WriteFile(sessionFile, resJson, 0644)
}
func newCompletionRequest(p params, model string) openai.ChatCompletionRequest {
msgs := []openai.ChatCompletionMessage{}
if p.systemMsg != "" {
msgs = append(msgs, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleSystem, Content: p.systemMsg})
}
return openai.ChatCompletionRequest{
Model: model,
MaxTokens: p.maxTokens,
Temperature: float32(p.temperature),
Stream: true,
Messages: msgs,
}
}
func appendMessages(req openai.ChatCompletionRequest, p params) openai.ChatCompletionRequest {
req.Messages = append(req.Messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser, Content: p.msg})
if p.includeFile != "" {
contents, err := os.ReadFile(p.includeFile)
if err != nil {
panic(err)
}
req.Messages = append(
req.Messages,
openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser, Content: string(contents)},
)
}
return req
}
func streamCompletion(ctx context.Context, client *openai.Client, req openai.ChatCompletionRequest, callback func(chunk string) error) (fullResponse string, err error) {
stream, err := client.CreateChatCompletionStream(ctx, req)
if err != nil {
return "", fmt.Errorf("ChatCompletionStream error: %v\n", err)
}
defer stream.Close()
responseChunks := []string{}
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return "", fmt.Errorf("stream error: %v\n", err)
}
chunk := response.Choices[0].Delta.Content
err = callback(chunk)
if err != nil {
return "", fmt.Errorf("callback error: %v\n", err)
}
responseChunks = append(responseChunks, chunk)
}
return strings.Join(responseChunks, ""), nil
}