forked from eryajf/chatgpt-dingtalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
103 lines (97 loc) · 2.46 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
package config
import (
"encoding/json"
"fmt"
"os"
"strconv"
"sync"
"time"
"github.com/eryajf/chatgpt-dingtalk/public/logger"
)
// Configuration 项目配置
type Configuration struct {
// gtp apikey
ApiKey string `json:"api_key"`
// 会话超时时间
SessionTimeout time.Duration `json:"session_timeout"`
// GPT请求最大字符数
MaxTokens uint `json:"max_tokens"`
// GPT模型
Model string `json:"model"`
// 热度
Temperature float64 `json:"temperature"`
// 自定义清空会话口令
SessionClearToken string `json:"session_clear_token"`
}
var config *Configuration
var once sync.Once
// LoadConfig 加载配置
func LoadConfig() *Configuration {
once.Do(func() {
// 从文件中读取
config = &Configuration{
SessionTimeout: 60,
MaxTokens: 512,
Model: "text-davinci-003",
Temperature: 0.9,
SessionClearToken: "下一个问题",
}
f, err := os.Open("config.json")
if err != nil {
logger.Danger("open config err: %v", err)
return
}
defer f.Close()
encoder := json.NewDecoder(f)
err = encoder.Decode(config)
if err != nil {
logger.Warning("decode config err: %v", err)
return
}
// 如果环境变量有配置,读取环境变量
// 有环境变量使用环境变量
ApiKey := os.Getenv("APIKEY")
SessionTimeout := os.Getenv("SESSION_TIMEOUT")
Model := os.Getenv("MODEL")
MaxTokens := os.Getenv("MAX_TOKENS")
Temperature := os.Getenv("TEMPREATURE")
SessionClearToken := os.Getenv("SESSION_CLEAR_TOKEN")
if ApiKey != "" {
config.ApiKey = ApiKey
}
if SessionTimeout != "" {
duration, err := time.ParseDuration(SessionTimeout)
if err != nil {
logger.Danger(fmt.Sprintf("config session timeout err: %v ,get is %v", err, SessionTimeout))
return
}
config.SessionTimeout = duration
}
if Model != "" {
config.Model = Model
}
if MaxTokens != "" {
max, err := strconv.Atoi(MaxTokens)
if err != nil {
logger.Danger(fmt.Sprintf("config MaxTokens err: %v ,get is %v", err, MaxTokens))
return
}
config.MaxTokens = uint(max)
}
if Temperature != "" {
temp, err := strconv.ParseFloat(Temperature, 64)
if err != nil {
logger.Danger(fmt.Sprintf("config Temperature err: %v ,get is %v", err, Temperature))
return
}
config.Temperature = temp
}
if SessionClearToken != "" {
config.SessionClearToken = SessionClearToken
}
})
if config.ApiKey == "" {
logger.Danger("config err: api key required")
}
return config
}