-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgptcmd.go
253 lines (221 loc) · 5.54 KB
/
gptcmd.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
/*
gptcmd.go
command-line access for Gpt Chat default format
Requires 2 Env Variables:
GPTKEY="your OpenAI key" (required)
GPTMOD="engine model" (required)
GPTWRAP="line wrap length" (optional)
GPTTMP=temperature (optional)
Type your prompt on the command-line.
log of requests is kept in file $HOME/gptcmd.log
*/
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"time"
)
const (
YEL = "\033[33;1m"
GRN = "\033[0;32m"
BLU = "\033[34;1m" // bright: blue
ORG = "\033[0;33m" // kind of brown
DFT = "\033[0m\n" // reset to default color
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Data struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Temperature float32 `json:"temperature"`
}
/*
This is the struct that corresponds to the JSON
return object. The JSON is "unmarshaled" into it.
*/
type Completion struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
SystemFingerprint string `json:"system_fingerprint"`
Choices []struct {
Index int `json:"index"`
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
func wrap(input string, limit int) string {
/* Create and return a new string by
limiting substrings at word boundaries*/
fields := strings.Fields(input)
if limit <= 0 {
return strings.Join(fields, " ")
}
format, count, result := "", 0, make([]string, len(fields))
for index, word := range fields {
if count+len(word) > limit {
format = "\n"
count = 0
}
count += len(word) + 1
result[index] = format + word
format = " "
}
return strings.Join(result, "")
}
func logRequest(prompt string, text string) {
// Open file in append mode.
var filepath string
if runtime.GOOS == "windows" {
filepath = os.Getenv("USERPROFILE") + "\\"
} else {
filepath = os.Getenv("HOME") + "/" // linux
}
if filepath == "" {
return // don't write to log file
}
file, err := os.OpenFile(filepath+"gptcmd.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
defer file.Close()
// get the datetime string
t := time.Now()
layout := "Mon 01/02/2006 03:04 pm"
tstr := t.Format(layout)
// Write new data to file
newData := "\n" + tstr + "\n> " + prompt + "\n>> " + text + "\n"
writer := bufio.NewWriter(file)
_, _ = writer.WriteString(newData)
// Save the changes
err = writer.Flush()
if err != nil {
log.Fatalf("failed saving file: %s", err)
}
}
/***
* __ __ _
* | \/ | __ _ (_) _ __
* | |\/| | / _` | | | | '_ \
* | | | | | (_| | | | | | | |
* |_| |_| \__,_| |_| |_| |_|
*
*/
func main() {
// Join all arguments with space as separator
args := os.Args[1:]
userprompt := strings.Join(args, " ")
// set up data for the Gpt Chat request
url := "https://api.openai.com/v1/chat/completions"
// collect the Environment values
openAPIKey := os.Getenv("GPTKEY")
openAPIModel := os.Getenv("GPTMOD")
wraplength := os.Getenv("GPTWRAP")
var temp float32 // json value must be numeric
f64, err := strconv.ParseFloat(os.Getenv("GPTTMP"), 32)
if err != nil {
temp = 0.7
} else {
temp = float32(f64)
}
// print HELP if no arguments (promt)
if len(os.Args) < 2 {
helpstr := `
gptcmd v1.0 2023
Type your prompt on the command-line.
Requires 2 Env Variables:
`
fmt.Printf("%s%s", GRN, helpstr)
if openAPIKey == "" {
fmt.Println("GPTKEY (required):", "NOT set!")
} else {
fmt.Println("GPTKEY (required):", "Set")
}
fmt.Println(GRN+"GPTMOD (required):", openAPIModel)
fmt.Println("GPTWRAP:", wraplength)
fmt.Println("GPTTMP:", temp)
fmt.Println(DFT)
os.Exit(0)
}
// JSON for the Chat POST request data
data := Data{
Model: openAPIModel,
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: userprompt,
},
},
Temperature: temp,
}
jsonData, err := json.Marshal(data)
if err != nil {
panic(err)
}
// build the request object
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+openAPIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// Handle the response ...
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
// bodyBytes is in Byte format
// fmt.Println(string(bodyBytes)) // debug the json response
var completion Completion
err = json.Unmarshal(bodyBytes, &completion)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("\n%s%s says:\n", YEL, openAPIModel)
fmt.Println("Model:", completion.Model)
fmt.Println("Total Tokens:", completion.Usage.TotalTokens)
respstr := completion.Choices[0].Message.Content
if wraplength != "" {
num, err := strconv.Atoi(wraplength)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Content:\n", wrap(respstr, num))
} else {
fmt.Println("Content:\n", respstr)
}
fmt.Println(DFT)
logRequest(userprompt, respstr)
}