config.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/eryajf/chatgpt-dingtalk/public/logger"
  10. )
  11. // Configuration 项目配置
  12. type Configuration struct {
  13. // gtp apikey
  14. ApiKey string `json:"api_key"`
  15. // 会话超时时间
  16. SessionTimeout time.Duration `json:"session_timeout"`
  17. // GPT请求最大字符数
  18. MaxTokens uint `json:"max_tokens"`
  19. // GPT模型
  20. Model string `json:"model"`
  21. // 热度
  22. Temperature float64 `json:"temperature"`
  23. // 自定义清空会话口令
  24. SessionClearToken string `json:"session_clear_token"`
  25. }
  26. var config *Configuration
  27. var once sync.Once
  28. // LoadConfig 加载配置
  29. func LoadConfig() *Configuration {
  30. once.Do(func() {
  31. // 从文件中读取
  32. config = &Configuration{
  33. SessionTimeout: 60,
  34. MaxTokens: 512,
  35. Model: "text-davinci-003",
  36. Temperature: 0.9,
  37. SessionClearToken: "下一个问题",
  38. }
  39. f, err := os.Open("config.json")
  40. if err != nil {
  41. logger.Danger("open config err: %v", err)
  42. return
  43. }
  44. defer f.Close()
  45. encoder := json.NewDecoder(f)
  46. err = encoder.Decode(config)
  47. if err != nil {
  48. logger.Warning("decode config err: %v", err)
  49. return
  50. }
  51. // 如果环境变量有配置,读取环境变量
  52. // 有环境变量使用环境变量
  53. ApiKey := os.Getenv("APIKEY")
  54. SessionTimeout := os.Getenv("SESSION_TIMEOUT")
  55. Model := os.Getenv("MODEL")
  56. MaxTokens := os.Getenv("MAX_TOKENS")
  57. Temperature := os.Getenv("TEMPREATURE")
  58. SessionClearToken := os.Getenv("SESSION_CLEAR_TOKEN")
  59. if ApiKey != "" {
  60. config.ApiKey = ApiKey
  61. }
  62. if SessionTimeout != "" {
  63. duration, err := time.ParseDuration(SessionTimeout)
  64. if err != nil {
  65. logger.Danger(fmt.Sprintf("config session timeout err: %v ,get is %v", err, SessionTimeout))
  66. return
  67. }
  68. config.SessionTimeout = duration
  69. }
  70. if Model != "" {
  71. config.Model = Model
  72. }
  73. if MaxTokens != "" {
  74. max, err := strconv.Atoi(MaxTokens)
  75. if err != nil {
  76. logger.Danger(fmt.Sprintf("config MaxTokens err: %v ,get is %v", err, MaxTokens))
  77. return
  78. }
  79. config.MaxTokens = uint(max)
  80. }
  81. if Temperature != "" {
  82. temp, err := strconv.ParseFloat(Temperature, 64)
  83. if err != nil {
  84. logger.Danger(fmt.Sprintf("config Temperature err: %v ,get is %v", err, Temperature))
  85. return
  86. }
  87. config.Temperature = temp
  88. }
  89. if SessionClearToken != "" {
  90. config.SessionClearToken = SessionClearToken
  91. }
  92. })
  93. if config.ApiKey == "" {
  94. logger.Danger("config err: api key required")
  95. }
  96. return config
  97. }