]> git.giacomolli.uk - onechat/blob - config.go
Order daemon and storage declarations
[onechat] / config.go
1 package main
2
3 import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "path/filepath"
11 )
12
13 const (
14 // configEndpointChatGPT names the ChatGPT backend with the subscription
15 // login.
16 configEndpointChatGPT = "chatgpt"
17
18 // configEndpointAPI names the OpenAI API with an API key.
19 configEndpointAPI = "api"
20 )
21
22 // Config holds the settings of config.json in the data directory.
23 type Config struct {
24 Endpoint string `json:"endpoint"`
25 Voice VoiceConfig `json:"voice"`
26 Compactor ModelConfig `json:"compactor"`
27 }
28
29 // ModelConfig names a model and its reasoning effort.
30 type ModelConfig struct {
31 Model string `json:"model"`
32 Effort string `json:"effort"`
33 }
34
35 // loadConfig reads config.json in dir over the defaults. A missing file gives
36 // the defaults. An unknown field is an error, so a typo does not become a
37 // silent default.
38 func loadConfig(dir string) (Config, error) {
39 config := defaultConfig()
40 data, err := os.ReadFile(filepath.Join(dir, "config.json"))
41 if errors.Is(err, os.ErrNotExist) {
42 return config, nil
43 }
44
45 if err != nil {
46 return Config{}, fmt.Errorf("read config: %w", err)
47 }
48
49 decoder := json.NewDecoder(bytes.NewReader(data))
50 decoder.DisallowUnknownFields()
51
52 err = decoder.Decode(&config)
53 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
54 err = errors.New("data after the JSON object")
55 }
56
57 if err == nil {
58 err = config.validate()
59 }
60
61 if err != nil {
62 return Config{}, fmt.Errorf("config.json: %w", err)
63 }
64
65 return config, nil
66 }
67
68 // validate makes sure that each setting has a valid value.
69 func (c Config) validate() error {
70 if c.Endpoint != configEndpointChatGPT && c.Endpoint != configEndpointAPI {
71 return fmt.Errorf("endpoint %q is not %q or %q", c.Endpoint, configEndpointChatGPT, configEndpointAPI)
72 }
73
74 if c.Compactor.Model == "" || c.Compactor.Effort == "" {
75 return errors.New("compactor needs a model and an effort")
76 }
77
78 return nil
79 }
80
81 // defaultConfig returns the settings that apply when config.json does not
82 // set them.
83 func defaultConfig() Config {
84 return Config{
85 Endpoint: configEndpointChatGPT,
86 Compactor: ModelConfig{
87 Model: "gpt-6.1-sol",
88 Effort: "high",
89 },
90 }
91 }