-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
120 lines (99 loc) · 2.58 KB
/
config.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/PullRequestInc/go-gpt3"
"github.com/kirsle/configdir"
)
const defaultConfigFilename = "configuration.json"
type config struct {
OpenAIAPIKey string `json:"openai_api_key"`
OpenaiAPIEndpoint string `json:"endpoint,omitempty"`
DefaultModel string `json:"model,omitempty"`
fileName string
}
func (c *config) Model() string {
if c.DefaultModel == "" {
return "gpt-4o-mini"
}
return c.DefaultModel
}
func (c *config) Client() gpt3.Client {
httpClient := &http.Client{
Timeout: 0,
}
opts := []gpt3.ClientOption{
gpt3.WithHTTPClient(httpClient),
gpt3.WithDefaultEngine(c.Model()),
}
if c.OpenaiAPIEndpoint != "" {
opts = append(opts, gpt3.WithBaseURL(c.OpenaiAPIEndpoint))
}
client := gpt3.NewClient(c.OpenAIAPIKey, opts...)
return client
}
func getConfigPath() string {
// A common use case is to get a private config folder for your app to
// place its settings files into, that are specific to the local user.
return configdir.LocalConfig("hlp")
}
func (c *config) Write() error {
fileName := c.fileName
if fileName == "" {
fileName = defaultConfigFilename
}
configPath := getConfigPath()
err := configdir.MakePath(configPath) // Ensure it exists.
if err != nil {
return fmt.Errorf("cannot read path: %w", err)
}
// Deal with a JSON configuration file in that folder.
configFile := filepath.Join(configPath, fileName)
fh, err := os.Create(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
encoder := json.NewEncoder(fh)
return encoder.Encode(c)
}
func ReadConfig(fileName string) (config, error) {
fileName = strings.TrimSpace(fileName)
if fileName == "" {
fileName = defaultConfigFilename
}
c := config{}
// A common use case is to get a private config folder for your app to
// place its settings files into, that are specific to the local user.
configPath := getConfigPath()
err := os.MkdirAll(configPath, 0755) // Ensure it exists.
if err != nil {
return config{}, fmt.Errorf("cannot read path: %w", err)
}
// Deal with a JSON configuration file in that folder.
configFile := filepath.Join(configPath, fileName)
if _, err = os.Stat(configFile); err != nil {
if os.IsNotExist(err) {
return config{
fileName: fileName,
}, nil
}
return config{}, err
}
// Load the existing file.
fh, err := os.Open(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
decoder := json.NewDecoder(fh)
if err := decoder.Decode(&c); err != nil {
return config{}, err
}
c.fileName = fileName
return c, nil
}