config.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # encoding:utf-8
  2. import argparse
  3. import json
  4. import logging
  5. import os
  6. import pickle
  7. from common.log import logger
  8. # 将所有可用的配置项写在字典里, 请使用小写字母
  9. # 此处的配置值无实际意义,程序不会读取此处的配置,仅用于提示格式,请将配置加入到config.json中
  10. available_setting = {
  11. "debug":False,
  12. "api_base": "http://fastgpt.ascrm.cn/api/v1",
  13. "api_key": "fastgpt-sKABkv3PTHxlFZYPn9Mo35HHsZSdzdFNBH4XeWIRn5CwdkG7aXqEDmXwDwK",
  14. "token":"",
  15. "open_ai_model": "gpt-4o",
  16. "open_ai_temperature": 0.7,
  17. "open_ai_max_tokens": 1024,
  18. "open_ai_top_p": 1,
  19. "open_ai_frequency_penalty": 0,
  20. "open_ai_presence_penalty": 0,
  21. "open_ai_stop": ["<|im_end|>"],
  22. "open_ai_stream": True,
  23. "contacts_white_list": [],
  24. "appdata_dir":"."
  25. }
  26. class Config(dict):
  27. def __init__(self, d=None):
  28. super().__init__()
  29. if d is None:
  30. d = {}
  31. for k, v in d.items():
  32. self[k] = v
  33. # user_datas: 用户数据,key为用户名,value为用户数据,也是dict
  34. self.user_datas = {}
  35. def __getitem__(self, key):
  36. if key not in available_setting:
  37. raise Exception("key {} not in available_setting".format(key))
  38. return super().__getitem__(key)
  39. def __setitem__(self, key, value):
  40. if key not in available_setting:
  41. raise Exception("key {} not in available_setting".format(key))
  42. return super().__setitem__(key, value)
  43. def get(self, key, default=None):
  44. try:
  45. return self[key]
  46. except KeyError as e:
  47. return default
  48. except Exception as e:
  49. raise e
  50. # Make sure to return a dictionary to ensure atomic
  51. def get_user_data(self, user) -> dict:
  52. if self.user_datas.get(user) is None:
  53. self.user_datas[user] = {}
  54. return self.user_datas[user]
  55. def load_user_datas(self):
  56. try:
  57. with open(os.path.join(get_appdata_dir(), "user_datas.pkl"), "rb") as f:
  58. self.user_datas = pickle.load(f)
  59. logger.info("[Config] User datas loaded.")
  60. except FileNotFoundError as e:
  61. logger.info("[Config] User datas file not found, ignore.")
  62. except Exception as e:
  63. logger.info("[Config] User datas error: {}".format(e))
  64. self.user_datas = {}
  65. def save_user_datas(self):
  66. try:
  67. with open(os.path.join(get_appdata_dir(), "user_datas.pkl"), "wb") as f:
  68. pickle.dump(self.user_datas, f)
  69. logger.info("[Config] User datas saved.")
  70. except Exception as e:
  71. logger.info("[Config] User datas error: {}".format(e))
  72. config = Config()
  73. # parser = argparse.ArgumentParser(description='消息中间处理程序')
  74. # parser.add_argument('-c', '--config', help='设置配置文件,默认值是 ./config.json')
  75. def load_config():
  76. global config, parser
  77. # args = parser.parse_args()
  78. # parser.print_help()
  79. # if args.config:
  80. # config_path = args.config
  81. # else:
  82. config_path = "./config.json"
  83. if not os.path.exists(config_path):
  84. logger.info("配置文件不存在,将使用config-template.json模板")
  85. config_path = "./config-template.json"
  86. config_str = read_file(config_path)
  87. logger.debug("[INIT] config str: {}".format(config_str))
  88. # 将json字符串反序列化为dict类型
  89. config = Config(json.loads(config_str))
  90. # override config with environment variables.
  91. # Some online deployment platforms (e.g. Railway) deploy project from github directly. So you shouldn't put your secrets like api key in a config file, instead use environment variables to override the default config.
  92. for name, value in os.environ.items():
  93. name = name.lower()
  94. if name in available_setting:
  95. logger.info("[INIT] override config by environ args: {}={}".format(name, value))
  96. try:
  97. config[name] = eval(value)
  98. except:
  99. if value == "false":
  100. config[name] = False
  101. elif value == "true":
  102. config[name] = True
  103. else:
  104. config[name] = value
  105. if config.get("debug", False):
  106. logger.setLevel(logging.DEBUG)
  107. logger.debug("[INIT] set log level to DEBUG")
  108. logger.info("[INIT] load config: {}".format(config))
  109. # config.load_user_datas()
  110. #
  111. # logger.info("[INIT] load user datas: {}".format(config.get_user_data("api_base")))
  112. def get_root():
  113. return os.path.dirname(os.path.abspath(__file__))
  114. def read_file(path):
  115. with open(path, mode="r", encoding="utf-8") as f:
  116. return f.read()
  117. def conf():
  118. return config
  119. def get_appdata_dir():
  120. data_path = os.path.join(get_root(), conf().get("appdata_dir", ""))
  121. if not os.path.exists(data_path):
  122. logger.info("[INIT] data path not exists, create it: {}".format(data_path))
  123. os.makedirs(data_path)
  124. return data_path
  125. def subscribe_msg():
  126. trigger_prefix = conf().get("single_chat_prefix", [""])[0]
  127. msg = conf().get("subscribe_msg", "")
  128. return msg.format(trigger_prefix=trigger_prefix)
  129. # global plugin config
  130. plugin_config = {}
  131. def write_plugin_config(pconf: dict):
  132. """
  133. 写入插件全局配置
  134. :param pconf: 全量插件配置
  135. """
  136. global plugin_config
  137. for k in pconf:
  138. plugin_config[k.lower()] = pconf[k]
  139. def pconf(plugin_name: str) -> dict:
  140. """
  141. 根据插件名称获取配置
  142. :param plugin_name: 插件名称
  143. :return: 该插件的配置项
  144. """
  145. return plugin_config.get(plugin_name.lower())
  146. # 全局配置,用于存放全局生效的状态
  147. global_config = {
  148. "admin_users": []
  149. }