Spaces:
Sleeping
Sleeping
| from typing import Dict, Type, Set | |
| import importlib | |
| import os | |
| class AppName: | |
| """Enum for application names.""" | |
| NCSLM_LPD = 'NCSLM_LPD' | |
| SEL = 'SEL' | |
| SEL_COACH = 'SEL_COACH' | |
| # Define required attributes that must be present in config | |
| REQUIRED_ATTRIBUTES: Set[str] = { | |
| 'ASSISTANT_MODEL', | |
| 'ASSISTANT_NAME', | |
| 'ASSISTANT_OPENING', | |
| 'ASSISTANT_DESCRIPTION', | |
| 'ASSISTANT_INSTRUCTION', | |
| 'RESPONSE_FORMAT', | |
| 'SHOW_CANVAS', | |
| 'CONVERSATION_STARTER_SAMPLES' | |
| } | |
| # Mapping of app names to their config module paths | |
| CONFIG_MAPPING: Dict[str, str] = { | |
| AppName.NCSLM_LPD: 'NCSLM_LPD.assistant_config', | |
| AppName.SEL: 'SEL.assistant_config', | |
| AppName.SEL_COACH: 'SEL_COACH.assistant_config', | |
| 'default': 'assistant_config' | |
| } | |
| def validate_config(config: Type) -> tuple[bool, list[str]]: | |
| """ | |
| Validate that the config has all required attributes. | |
| Args: | |
| config: The configuration module to validate | |
| Returns: | |
| tuple[bool, list[str]]: (is_valid, list of missing attributes) | |
| """ | |
| missing_attrs = [attr for attr in REQUIRED_ATTRIBUTES if not hasattr(config, attr)] | |
| return len(missing_attrs) == 0, missing_attrs | |
| def get_app_name_and_config() -> tuple[str, Type]: | |
| """ | |
| Get the appropriate configuration module based on APP_NAME. | |
| Validates that the config has all required attributes. | |
| Returns: | |
| Type: The configuration module | |
| Raises: | |
| ImportError: If the config module cannot be imported | |
| ValueError: If the config is missing required attributes | |
| """ | |
| app_name = os.getenv('app_name') | |
| config_path = CONFIG_MAPPING.get(app_name, CONFIG_MAPPING['default']) | |
| try: | |
| config = importlib.import_module(config_path) | |
| except ImportError as e: | |
| print(f"Error importing config {config_path}: {e}") | |
| config = importlib.import_module(CONFIG_MAPPING['default']) | |
| # Validate the config | |
| is_valid, missing_attrs = validate_config(config) | |
| if not is_valid: | |
| error_msg = f"Config {config_path} is missing required attributes: {missing_attrs}" | |
| print(f"Warning: {error_msg}") | |
| # Try to load default config if current config is invalid | |
| if config_path != CONFIG_MAPPING['default']: | |
| print("Attempting to load default config...") | |
| default_config = importlib.import_module(CONFIG_MAPPING['default']) | |
| is_valid, missing_attrs = validate_config(default_config) | |
| if not is_valid: | |
| raise ValueError(f"Default config is also invalid. Missing: {missing_attrs}") | |
| return default_config | |
| else: | |
| raise ValueError(error_msg) | |
| return app_name, config | |