import os
import yaml
class Config:
_instance = None
def __new__(cls, file_path: str, file_name: str = "config.yml"):
if cls._instance is None:
cls._instance = super(Config, cls).__new__(cls)
cls._instance._load_config(file_path, file_name)
return cls._instance
def _load_config(self, file_path, file_name):
config_path = f"{file_path}/{file_name}"
try:
with open(config_path, 'r', encoding='utf-8') as f:
self._config = yaml.safe_load(f)
except FileNotFoundError:
raise RuntimeError(f"配置文件 {config_path} 不存在")
except yaml.YAMLError as e:
raise RuntimeError(f"配置文件解析失败: {e}")
def __getattr__(self, name):
if name in self._config:
return self._config[name]
raise AttributeError(f"配置项 {name} 不存在")
def get(self, key, default=None):
return self._config.get(key, default)
yaml_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config = Config(yaml_path, "config.yml")
if __name__ == '__main__':
print(config.get('LLM').get('BASE_URL'))
print(config.get('LLM').get('APP_KEY'))
print(config.get('LLM').get('MODEL'))