Coverage for agentlib/utils/load_config.py: 100%

14 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2025-04-07 16:27 +0000

1import json 

2from pathlib import Path 

3from typing import Union, TypeVar, Type 

4 

5from pydantic import FilePath, BaseModel 

6 

7from agentlib.core.errors import ConfigurationError 

8 

9ConfigT = TypeVar("ConfigT", bound=BaseModel) 

10 

11 

12def load_config( 

13 config: Union[ConfigT, FilePath, str, dict], config_type: Type[ConfigT] 

14) -> ConfigT: 

15 """Generic config loader, either accepting a path to a json file, a json string, a 

16 dict or passing through a valid config object.""" 

17 

18 if isinstance(config, (str, Path)): 

19 # if we have a str / path, we need to check whether it is a file or a json string 

20 if Path(config).is_file(): 

21 # if we have a valid file pointer, we load it 

22 with open(config, "r") as f: 

23 config = json.load(f) 

24 else: 

25 # since the str is not a file path, we assume it is json and try to load it 

26 try: 

27 config = json.loads(config) 

28 except json.JSONDecodeError as e: 

29 # if we failed, we raise an error notifying the user of possibilities 

30 raise ConfigurationError( 

31 f"The config '{config:.100}' is neither an existing file path, nor a " 

32 f"valid json document." 

33 ) from e 

34 return config_type.model_validate(config)