/
main.go
431 lines (347 loc) · 8.74 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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/alexflint/go-arg"
"github.com/atotto/clipboard"
"github.com/sashabaranov/go-openai"
"github.com/hayeah/pls/promptstr"
)
type Chat struct {
client *openai.Client
baseRequest openai.ChatCompletionRequest
}
type ChatOptions func(*Chat)
func toMessages(role string, messages []string) []openai.ChatCompletionMessage {
var result []openai.ChatCompletionMessage
for _, message := range messages {
result = append(result, openai.ChatCompletionMessage{
Role: role,
Content: message,
})
}
return result
}
func SetMaxTokens(maxTokens int) ChatOptions {
return func(c *Chat) {
c.baseRequest.MaxTokens = maxTokens
}
}
// AppendUserMessages sets context messages
func AppendUserMessages(messages ...string) ChatOptions {
return func(c *Chat) {
c.baseRequest.Messages = append(c.baseRequest.Messages, toMessages(openai.ChatMessageRoleUser, messages)...)
}
}
func NewChat(client *openai.Client, opts ...ChatOptions) *Chat {
c := &Chat{
client: client,
baseRequest: openai.ChatCompletionRequest{
// Temperature: 0.5,
// Temperature: 1.5. seems bad
// Model: openai.GPT3Dot5Turbo,
// Model: openai.GPT3Dot5Turbo0301,
// MaxTokens: 1000,
Model: openai.GPT3Dot5Turbo0301,
},
}
for _, opt := range opts {
opt(c)
}
return c
}
func (c *Chat) cloneRequest() openai.ChatCompletionRequest {
return c.baseRequest
}
func (rs *ResponseStream) Close() error {
rs.cancel()
rs.stream.Close()
return nil
}
func (c *Chat) Stream(message string, opts *TemplateFrontMatter) (io.ReadCloser, error) {
ctx, cancel := context.WithCancel(context.Background())
req := c.cloneRequest()
if opts != nil {
req.Temperature = float32(opts.Temperature)
}
req.Messages = append(req.Messages,
// openai.ChatCompletionMessage{
// Role: openai.ChatMessageRoleSystem,
// Content: "please be as helpful as possible, and give detailed, informative response. it's good to produce long output to be extra helpful.",
// },
openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: message,
})
req.Stream = true
stream, err := c.client.CreateChatCompletionStream(ctx, req)
if err != nil {
cancel()
return nil, err
}
rs := &ResponseStream{
stream: stream,
cancel: cancel,
}
return rs, nil
}
type ResponseStream struct {
stream *openai.ChatCompletionStream
cancel context.CancelFunc
stopped bool
}
// Read streams the completion stream, and append a newline at the end. Not threadsafe.
func (rs *ResponseStream) Read(p []byte) (int, error) {
if rs.stopped {
return 0, io.EOF
}
// the base stream is not threadsafe...
response, err := rs.stream.Recv()
if errors.Is(err, io.EOF) {
p[0] = '\n'
rs.stopped = true
return 1, io.EOF
}
if err != nil {
return 0, err
}
n := copy(p, response.Choices[0].Delta.Content)
return n, nil
}
type TemplateData struct {
Input string
}
type TemplateFrontMatter struct {
// note: quirk of the openai library doesn't make it possible to use 0.0 for these options floats.
Temperature float32 `json:"temperature"`
}
func RenderTemplate(promptTemplate string, data TemplateData) (string, *TemplateFrontMatter, error) {
// this is my prompt yo
// ---
// END_OF_PROMPT. BEGIN INPUT.
// ---
// {{.Input}}`
var fm TemplateFrontMatter
promptBody, err := promptstr.ParseFrontMatter(promptTemplate, &fm)
if err != nil {
return "", nil, err
}
tmpl, err := template.New("template").Parse(promptBody)
if err != nil {
return "", nil, err
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
return "", nil, err
}
return buf.String(), &fm, nil
}
type Args struct {
PromptFile string `arg:"positional,required" help:"prompt template file"`
InputFile string `arg:"positional" help:"input file to embed into the prompt"`
PrintPrompt bool `arg:"-p,--prompt" help:"print the rendered prompt for copy-paste"`
OutputFile string `arg:"positional" help:"output file. Use - for stdout"`
ReplaceInputFile bool `arg:"-r,--replace" help:"inplace rewrite of the input file"`
NoInput bool `arg:"-n,--no-input" help:"use the prompt directly with no input"`
}
// TemplatePaths returns the paths to search for templates
func TemplatePaths() ([]string, error) {
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
// default paths
paths := []string{
path.Join(home, "pls"),
path.Join(home, ".pls"),
}
// add paths in PLS_PATH
if plsPath := os.Getenv("PLS_PATH"); plsPath != "" {
// prepend paths
paths = append(strings.Split(plsPath, ":"), paths...)
}
return paths, nil
}
type Runner struct {
args Args
chat *Chat
templatePaths []string
}
func (r *Runner) RenderPrompt() (string, *TemplateFrontMatter, error) {
var err error
templateName := r.args.PromptFile
// search for template
templatePath, err := MatchNameInPaths(r.templatePaths, templateName)
if err != nil {
return "", nil, err
}
// read prompt file
prompt, err := os.ReadFile(templatePath)
if err != nil {
return "", nil, err
}
var input []byte
if !r.args.NoInput {
if r.args.InputFile == "" {
// read from stdin as input
input, err = io.ReadAll(os.Stdin)
if err != nil {
return "", nil, err
}
} else {
input, err = os.ReadFile(r.args.InputFile)
if err != nil {
return "", nil, err
}
}
}
return RenderTemplate(string(prompt), TemplateData{
Input: string(input),
})
}
// OutputStream produces the output stream of rendered prompt
func (r *Runner) OutputStream(renderedPrompt string, frontMatter *TemplateFrontMatter) (io.ReadCloser, error) {
stream, err := r.chat.Stream(renderedPrompt, frontMatter)
if err != nil {
return nil, err
}
return stream, nil
}
// backupFile backups by making a copy suffixed with timestamp
func backupFile(filename string) error {
// Open the original file for reading
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
// Create the backup filename with the timestamp
backupFilename := fmt.Sprintf("%s.%s", filename, time.Now().Format(time.RFC3339))
// Create the backup file for writing
backupFile, err := os.Create(backupFilename)
if err != nil {
return err
}
defer backupFile.Close()
// Copy the contents of the original file to the backup file
_, err = io.Copy(backupFile, file)
if err != nil {
return err
}
return nil
}
// ReplaceFile replaces the output file with the output stream, makeing a backupt of the output file first.
func (r *Runner) ReplaceFile(stream io.Reader, outputfile string) error {
// read output file
err := backupFile(outputfile)
if err != nil {
return err
}
// open output file
f, err := os.OpenFile(outputfile, os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
// tee the output to stdout
stream = io.TeeReader(stream, os.Stdout)
_, err = io.Copy(f, stream)
return err
}
func (r *Runner) Run() error {
prompt, frontMatter, err := r.RenderPrompt()
if err != nil {
return err
}
if r.args.PrintPrompt {
fmt.Println(prompt)
err := clipboard.WriteAll(prompt)
if err != nil {
return err
}
fmt.Println("[copied to clipboard]")
return nil
}
stream, err := r.OutputStream(prompt, frontMatter)
if err != nil {
return err
}
defer stream.Close()
outputFile := r.args.OutputFile
if r.args.ReplaceInputFile && outputFile == "" {
outputFile = r.args.InputFile
}
if outputFile == "" {
_, err = io.Copy(os.Stdout, stream)
return err
}
return r.ReplaceFile(stream, outputFile)
}
var ErrNotFound = errors.New("no template found")
// MatchNameInPaths returns the first file that exactly matches "name" in the list of paths
func MatchNameInPaths(paths []string, name string) (matchedFile string, err error) {
if name == "" {
return "", errors.New("name cannot be empty")
}
for _, path := range paths {
err := filepath.WalkDir(path, func(curPath string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
log.Println("match", curPath, d.Name())
if curPath == path {
// continue walking
return nil
}
if d.IsDir() {
return filepath.SkipDir
}
if dname := d.Name(); dname == name {
matchedFile = curPath
return filepath.SkipAll
}
return nil
})
if err != nil {
return "", err
}
if matchedFile != "" {
return matchedFile, nil
}
}
return "", ErrNotFound
}
func run() error {
var args Args
arg.MustParse(&args)
c := openai.NewClient(os.Getenv("OPENAI_SECRET"))
chat := NewChat(c)
templatePaths, err := TemplatePaths()
if err != nil {
return err
}
runner := &Runner{
args: args,
chat: chat,
templatePaths: templatePaths,
}
return runner.Run()
}
func main() {
err := run()
if err != nil {
log.Fatalln(err)
}
}