-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot.go
84 lines (68 loc) · 1.48 KB
/
bot.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
package main
import (
_ "embed"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
)
//go:embed prompt_prefix.txt
var promptPrefix string
const promptStartText = "\n[EXAMPLES]\n"
func main() {
args := parseArgs()
if len(args.Prompt) == 0 {
usage()
os.Exit(1)
}
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Error retrieving home directory: %v", err)
os.Exit(1)
}
configPath := filepath.Join(homeDir, configFilename)
config, err := loadConfig(configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading config: %v", err)
os.Exit(1)
}
respCh := make(chan string)
var wg sync.WaitGroup
wg.Add(2)
client := &OpenAIAdapter{APIKey: config.APIKey}
go func() {
defer wg.Done()
err := client.FetchCompletionStream(CreateRequest(args.Prompt), respCh)
if err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(1)
}
}()
go func() {
defer wg.Done()
RenderCompletionStreamResponse(os.Stdout, respCh)
}()
wg.Wait()
}
type Args struct {
Interactive bool
Prompt string
}
func parseArgs() *Args {
interactive := flag.Bool("i", false, "Enter interactive mode (optional)")
flag.Parse()
prompt := strings.Join(flag.Args(), " ")
return &Args{Interactive: *interactive, Prompt: prompt}
}
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s [prompt]", os.Args[0])
}
func RenderCompletionStreamResponse(w io.Writer, respCh <-chan string) {
for token := range respCh {
fmt.Fprint(w, token)
}
fmt.Fprintln(w, "")
}