-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (55 loc) · 1.29 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
type prompt string
func (p prompt) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"model": "text-davinci-002",
"temperature": 0,
"prompt": `Convert this text to a programmatic command:
` + string(p),
})
}
type answer struct {
Choices []struct {
Text string `json:"text"`
} `json:"choices"`
}
func main() {
token := os.Getenv("OPENAI_API_TOKEN")
if token == "" {
panic(`env variable "OPENAI_API_TOKEN" is required`)
}
body, err := json.Marshal(prompt(strings.Join(os.Args[1:], " ")))
if err != nil {
panic(err)
}
request, err := http.NewRequest(http.MethodPost, "https://api.openai.com/v1/completions", bytes.NewReader(body))
if err != nil {
panic(err)
}
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
var result answer
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
panic(err)
}
if err := response.Body.Close(); err != nil {
panic(err)
}
if len(result.Choices) > 0 {
fmt.Println(strings.TrimSpace(result.Choices[0].Text))
return
}
panic("can not find choice in response")
}