]> git.giacomolli.uk - onechat/blob - config.go
Wait until the view has no pending summary
[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 // loadConfig reads config.json in dir over the defaults. A missing file gives
23 // the defaults. An unknown field is an error, so a typo does not become a
24 // silent default.
25 func loadConfig(dir string) (Config, error) {
26         config := defaultConfig()
27         data, err := os.ReadFile(filepath.Join(dir, "config.json"))
28         if errors.Is(err, os.ErrNotExist) {
29                 return config, nil
30         }
31
32         if err != nil {
33                 return Config{}, fmt.Errorf("read config: %w", err)
34         }
35
36         decoder := json.NewDecoder(bytes.NewReader(data))
37         decoder.DisallowUnknownFields()
38         err = decoder.Decode(&config)
39         if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
40                 err = errors.New("data after the JSON object")
41         }
42
43         if err == nil {
44                 err = config.validate()
45         }
46
47         if err != nil {
48                 return Config{}, fmt.Errorf("config.json: %w", err)
49         }
50
51         return config, nil
52 }
53
54 // Config holds the settings of config.json in the data directory.
55 type Config struct {
56         Endpoint  string      `json:"endpoint"`
57         Compactor ModelConfig `json:"compactor"`
58 }
59
60 // validate makes sure that each setting has a valid value.
61 func (c Config) validate() error {
62         if c.Endpoint != configEndpointChatGPT && c.Endpoint != configEndpointAPI {
63                 return fmt.Errorf("endpoint %q is not %q or %q", c.Endpoint, configEndpointChatGPT, configEndpointAPI)
64         }
65
66         if c.Compactor.Model == "" || c.Compactor.Effort == "" {
67                 return errors.New("compactor needs a model and an effort")
68         }
69
70         return nil
71 }
72
73 // ModelConfig names a model and its reasoning effort.
74 type ModelConfig struct {
75         Model  string `json:"model"`
76         Effort string `json:"effort"`
77 }
78
79 // defaultConfig returns the settings that apply when config.json does not
80 // set them.
81 func defaultConfig() Config {
82         return Config{
83                 Endpoint: configEndpointChatGPT,
84                 Compactor: ModelConfig{
85                         Model:  "gpt-6.1-sol",
86                         Effort: "high",
87                 },
88         }
89 }