/
root.go
110 lines (97 loc) · 2.33 KB
/
root.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
package main
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"time"
"github.com/byebyebruce/chat2code"
"github.com/byebyebruce/chat2code/llm/openaillm"
"github.com/byebyebruce/chat2code/vectordb/localdb"
"github.com/fatih/color"
"github.com/manifoldco/promptui"
"github.com/sashabaranov/go-openai"
"github.com/spf13/cobra"
)
var (
vecDB *localdb.VectorDatabase
llm *openaillm.OpenAILLM
)
func RootCMD() *cobra.Command {
var (
model string
flagApiKey, flagApiBase string
)
rootCmd := &cobra.Command{
Use: "chat2code",
}
rootCmd.Flags().StringVarP(&flagApiKey, "api-key", "k", "", "openai api key")
rootCmd.Flags().StringVarP(&flagApiBase, "api-base", "b", "", "openai api base")
rootCmd.Flags().StringVarP(&model, "model", "m", openai.GPT3Dot5Turbo, "model name(gpt-3.5-turbo/gpt-4/)")
rootCmd.RunE = func(cmd *cobra.Command, args []string) error {
if len(flagApiKey) > 0 {
apiKey = flagApiKey
}
if len(flagApiBase) > 0 {
apiKey = flagApiBase
}
if len(apiKey) == 0 {
fmt.Println("please set env OPENAI_API_KEY. if azure also need to set env OPENAI_API_BASE")
return nil
}
t2c, err := chat2code.NewChat2Code(vecDB, openaillm.NewLLM(apiKey, apiBase, model))
if err != nil {
return err
}
repos, err := vecDB.ListRepos(cmd.Context())
if err != nil {
return err
}
if len(repos) == 0 {
fmt.Println("there is no repo. use 'chat2code load {dir}'")
return nil
}
prompt := promptui.Select{
Label: "Select a repo to Q&A",
Items: repos,
}
_, repo, err := prompt.Run()
if err != nil {
return nil
}
// loop
for {
fmt.Println()
reader := bufio.NewReader(os.Stdin)
color.Green("Enter question: ")
input, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("error reading input: %v\n", err)
fmt.Println()
continue
}
input = strings.TrimSpace(input)
if len(input) == 0 {
continue
}
func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
answer, err := t2c.Answer(ctx, repo, input, 0.7)
if err != nil {
color.Red("err:%v", err)
return
}
if answer == nil {
color.Red("no answer")
return
}
color.Cyan(answer.Answer)
fmt.Printf(`"reference: %s"`+"\n", color.RedString(answer.File))
}()
}
return nil
}
return rootCmd
}