-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
179 lines (157 loc) · 4.07 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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/fatih/color"
"github.com/manifoldco/promptui"
"github.com/mattn/go-isatty"
"github.com/tidwall/pretty"
"moul.io/http2curl"
)
const usage = "plz [OPTS] PROMPT..."
type config struct {
apiBase string
apiKey string
force bool
prompt string
model string
quiet bool
debug bool
}
func main() {
err := doMain(os.Args)
switch err {
case nil:
// continue
case flag.ErrHelp:
fmt.Fprintf(os.Stderr, usage, err)
flag.Usage()
os.Exit(1)
default:
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func doMain(args []string) error {
cfg := config{}
flag.StringVar(&cfg.apiBase, "api-base", "https://api.openai.com/v1", "API base URL")
flag.StringVar(&cfg.apiKey, "api-key", os.Getenv("OPENAI_APIKEY"), "API key ($OPENAI_APIKEY)")
flag.StringVar(&cfg.model, "model", "gpt-3.5-turbo-instruct", "Model to use")
flag.BoolVar(&cfg.force, "f", false, "Run the generated program without asking for confirmation")
flag.BoolVar(&cfg.quiet, "q", false, "Minimal output")
flag.BoolVar(&cfg.debug, "debug", false, "Additional debug")
flag.Parse()
cfg.prompt = strings.TrimSpace(strings.Join(flag.Args(), " "))
if cfg.prompt == "" {
return flag.ErrHelp
}
if !isatty.IsTerminal(os.Stdout.Fd()) {
cfg.quiet = true
}
start := time.Now()
if cfg.debug {
defer func() {
log.Println("execution time: ", time.Since(start))
}()
}
s := spinner.New(spinner.CharSets[14], 100)
s.Start()
if cfg.quiet {
s.Stop()
}
defer s.Stop()
client := &http.Client{}
requestBody, _ := json.Marshal(map[string]interface{}{
"top_p": 1,
"stop": "```",
"temperature": 0,
"suffix": "\n```",
"max_tokens": 1000,
"presence_penalty": 0,
"frequency_penalty": 0,
"model": cfg.model,
"prompt": buildPrompt(cfg.prompt),
})
apiAddr := fmt.Sprintf("%s/completions", cfg.apiBase)
req, _ := http.NewRequest("POST", apiAddr, bytes.NewBuffer(requestBody))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", cfg.apiKey))
req.Header.Set("Content-Type", "application/json")
if cfg.debug {
debug, _ := http2curl.GetCurlCommand(req)
fmt.Println(debug)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
if resp.StatusCode >= 400 {
fmt.Println(color.RedString("API error: %v", err))
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("http code>=400: %s", pretty.Color(body, nil))
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
code := strings.TrimSpace(result["choices"].([]interface{})[0].(map[string]interface{})["text"].(string))
s.Stop()
if !cfg.quiet {
fmt.Println(color.GreenString("Got some code!"))
}
if !cfg.quiet || !cfg.force {
fmt.Println(color.RedString(code))
}
shouldRun := cfg.force
if !shouldRun {
prompt := promptui.Select{
Label: "Run the generated program? [Y/n]",
Items: []string{"Yes", "No"},
}
_, result, err := prompt.Run()
if err != nil {
return fmt.Errorf("prompt failed: %v", err)
}
shouldRun = result == "Yes"
}
if shouldRun {
s = spinner.New(spinner.CharSets[14], 100)
s.Start()
if cfg.quiet {
s.Stop()
}
defer s.Stop()
cmd := exec.Command("bash", "-c", code)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to execute the generated program: %v", err)
}
if cmd.ProcessState.ExitCode() != 0 {
return fmt.Errorf("the program threw an error:\n%s", string(output))
}
s.Stop()
if !cfg.quiet {
fmt.Println(color.GreenString("Command ran successfully"))
}
fmt.Println(string(output))
}
return nil
}
func buildPrompt(prompt string) string {
osHint := ""
if strings.Contains(strings.ToLower(os.Getenv("OS")), "windows") {
osHint = " (on Windows)"
} else if strings.Contains(strings.ToLower(os.Getenv("OS")), "darwin") {
osHint = " (on macOS)"
} else {
osHint = " (on Linux)"
}
return fmt.Sprintf("%s%s:\n```bash\n#!/bin/bash\n", prompt, osHint)
}