monoai.conf

1from .conf import Conf
2
3__all__ = ["Conf"]
class Conf:
  8class Conf:
  9    """
 10    A singleton class for managing configuration in a programmatic way.
 11    Configuration defined here overrides the configuration in monoai.yaml file.
 12
 13    Examples
 14    --------
 15    ```
 16    from monoai.conf import Conf
 17    
 18    # override the base model
 19    Conf()["base_model"] = {
 20        "provider": "openai",
 21        "model": "gpt-4o-mini"
 22    }
 23    
 24    # set prompts path programmatically
 25    Conf()["prompts_path"] = "prompts"
 26    ```
 27    """
 28    
 29    _instance = None
 30    _DEFAULT_CONFIG = {
 31        'keysfile_path': "providers.keys",
 32        'supported_files': {
 33            "text": ["txt", "py", "md"],
 34            "image": ["png", "jpg", "jpeg", "gif", "webp"]
 35        },
 36        'prompts_path': "",
 37        'default_prompt': {
 38            "rag": "Use also the following information to answer the question: ",
 39            "summary":"Here is the summary of the conversation so far:\n\n",
 40            "file":"Here is the content of the file:\n\n"
 41        }
 42    }
 43    
 44    def __new__(cls):
 45        """
 46        Create or return the singleton instance.
 47
 48        Returns
 49        -------
 50        Config
 51            The singleton instance
 52        """
 53        if cls._instance is None:
 54            cls._instance = super(Conf, cls).__new__(cls)
 55            cls._instance._initialize()
 56        return cls._instance
 57    
 58    def _initialize(self):
 59        """
 60        Initialize the Config instance.
 61        
 62        Loads and validates the configuration file, setting up defaults
 63        and performing environment variable interpolation.
 64        """
 65        self._config_path = Path('monoai.yaml')
 66        self._config = self._DEFAULT_CONFIG.copy()
 67        self._load_config()
 68    
 69    def _load_config(self) -> None:
 70        """
 71        Load configuration from the YAML file.
 72        
 73        Handles file reading, YAML parsing, environment variable interpolation,
 74        and configuration validation.
 75
 76        Raises
 77        ------
 78        FileNotFoundError
 79            If the configuration file doesn't exist
 80        yaml.ParserError
 81            If the YAML syntax is invalid
 82        ValueError
 83            If the configuration structure is invalid
 84        """
 85        try:
 86            if self._config_path.exists():
 87                with open(self._config_path, 'r') as f:
 88                    file_config = yaml.safe_load(f)
 89                if file_config:
 90                    self._merge_config(self._config, file_config)            
 91            
 92        except ParserError as e:
 93            raise ValueError(f"Invalid YAML syntax in {self._config_path}: {e}")
 94        except Exception as e:
 95            raise ValueError(f"Error loading configuration: {e}")
 96    
 97    def _merge_config(self, base: Dict, override: Dict) -> None:
 98        """
 99        Recursively merge override configuration into base configuration.
100
101        Parameters
102        ----------
103        base : Dict
104            The base configuration dictionary
105        override : Dict
106            The override configuration dictionary
107        """
108        for key, value in override.items():
109            if (
110                key in base and 
111                isinstance(base[key], dict) and 
112                isinstance(value, dict)
113            ):
114                self._merge_config(base[key], value)
115            else:
116                base[key] = value
117        
118        
119    def __getitem__(self, key: str) -> Any:
120        return self._config[key]
121    
122    def __setitem__(self, key: str, value: Any) -> None:
123        self._config[key] = value

A singleton class for managing configuration in a programmatic way. Configuration defined here overrides the configuration in monoai.yaml file.

Examples
from monoai.conf import Conf

# override the base model
Conf()["base_model"] = {
    "provider": "openai",
    "model": "gpt-4o-mini"
}

# set prompts path programmatically
Conf()["prompts_path"] = "prompts"
Conf()
44    def __new__(cls):
45        """
46        Create or return the singleton instance.
47
48        Returns
49        -------
50        Config
51            The singleton instance
52        """
53        if cls._instance is None:
54            cls._instance = super(Conf, cls).__new__(cls)
55            cls._instance._initialize()
56        return cls._instance

Create or return the singleton instance.

Returns
  • Config: The singleton instance