-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
179 lines (140 loc) · 4.37 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"
"context"
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/alecthomas/kong"
"github.com/gosimple/slug"
"github.com/jtarchie/sqlc-gpt/parser"
"github.com/jtarchie/worker"
"github.com/sashabaranov/go-openai"
)
type CLI struct {
Glob string `help:"glob to look for *.sql files" required:""`
OutputDir string `help:"location to write the files to" required:""`
PackageName string `default:"main" help:"the package name to the file" required:""`
OpenAIAccessToken string `env:"OPENAI_ACCESS_TOKEN" help:"the API token for the OpenAI API" required:""`
BaseURL string `default:"https://api.openai.com/v1" help:"url of the OpenAI HTTP domain"`
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stderr, nil))
slog.SetDefault(logger)
cli := &CLI{}
ctx := kong.Parse(cli)
err := ctx.Run()
if err != nil {
slog.Error("could not execute", slog.String("error", err.Error()))
}
}
func (c *CLI) executePrompt(query *parser.ParsedQuery, prompt string) (string, error) {
config := openai.DefaultConfig(c.OpenAIAccessToken)
config.BaseURL = c.BaseURL
client := openai.NewClientWithConfig(config)
slog.Info("openai start", slog.String("name", query.Name))
response, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleAssistant,
Content: prompt,
},
},
},
)
slog.Info("open ai finished", slog.String("name", query.Name))
if err != nil {
return "", fmt.Errorf("could not translate: %w", err)
}
code := response.Choices[0].Message.Content
code = strings.TrimSpace(code)
code = strings.TrimPrefix(code, "```go")
code = strings.TrimSuffix(code, "```")
return code, nil
}
func logError(message string, err error, query *parser.ParsedQuery) {
slog.Error(message, slog.String("error", err.Error()), slog.String("name", query.Name))
}
//nolint:funlen,cyclop
func (c *CLI) Run() error {
queries, err := parser.Load(c.Glob)
if err != nil {
return fmt.Errorf("could not parse SQL files: %w", err)
}
err = queries.Validate()
if err != nil {
return fmt.Errorf("could not validate queries: %w", err)
}
err = os.MkdirAll(c.OutputDir, os.ModePerm)
if err != nil {
return fmt.Errorf("could not create output directory: %w", err)
}
queueSize := 2
workers := worker.New(queueSize, queueSize, func(index int, query *parser.ParsedQuery) {
filename := filepath.Join(c.OutputDir, fmt.Sprintf("%s.go", slug.Make(query.Name)))
slog.Info("executing prompt", slog.String("name", query.Name))
defer slog.Info("finished prompt", slog.String("name", query.Name))
data := map[string]interface{}{
"PackageName": c.PackageName,
"Query": query,
}
buffer := &bytes.Buffer{}
promptTemplate, err := template.New("promptTemplate").Parse(prompt)
if err != nil {
logError("could not parse template", err, query)
return
}
err = promptTemplate.Execute(buffer, data)
if err != nil {
logError("could execute template", err, query)
return
}
hasher := sha256.New()
_, _ = hasher.Write(buffer.Bytes())
promptHash := hasher.Sum(nil)
file, err := os.OpenFile(filename, os.O_RDWR, os.ModePerm)
if !errors.Is(err, os.ErrNotExist) {
_ = file.Close()
contents, err := os.ReadFile(filename)
if err != nil {
logError("could not read file", err, query)
return
}
if bytes.Contains(contents, []byte(fmt.Sprintf("%x", promptHash))) {
slog.Info("file is up to date", slog.String("filename", filename), slog.String("name", query.Name))
return
}
}
file, err = os.Create(filename)
if err != nil {
logError("could not create file", err, query)
return
}
defer file.Close()
result, err := c.executePrompt(query, strings.TrimSpace(buffer.String()))
if err != nil {
logError("could not execute prompt", err, query)
return
}
_, _ = fmt.Fprint(file, "// This is a generated file, do not touch\n")
_, _ = fmt.Fprintf(file, "// hash: %x\n\n", promptHash)
_, err = fmt.Fprintf(file, "\n%s\n", result)
if err != nil {
logError("could not write prompt to file", err, query)
return
}
})
defer workers.Close()
for _, query := range queries {
workers.Enqueue(query)
}
return nil
}