Coverage for presidio_analyzer / llm_utils / prompt_loader.py: 89%

19 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-03-29 09:03 +0000

1"""Prompt loading and rendering utilities for LLM recognizers.""" 

2import logging 

3 

4from .config_loader import resolve_config_path 

5 

6logger = logging.getLogger("presidio-analyzer") 

7 

8__all__ = [ 

9 "load_file_from_conf", 

10 "load_prompt_file", 

11 "render_jinja_template", 

12] 

13 

14 

15def load_file_from_conf(filename: str, conf_subdir: str = "conf") -> str: 

16 """Load text file from configuration directory. 

17 

18 :param filename: Path to file to load (can be repo-root-relative). 

19 :param conf_subdir: Configuration subdirectory (deprecated, kept for compatibility). 

20 :return: File contents as string. 

21 :raises FileNotFoundError: If file doesn't exist. 

22 """ 

23 file_path = resolve_config_path(filename) 

24 

25 if not file_path.exists(): 

26 raise FileNotFoundError(f"File not found: {file_path}") 

27 

28 with open(file_path, "r") as f: 

29 return f.read() 

30 

31 

32def load_prompt_file(prompt_file: str, conf_subdir: str = "conf") -> str: 

33 """Load prompt template file from configuration directory. 

34 

35 :param prompt_file: Path to prompt template file (can be repo-root-relative). 

36 :param conf_subdir: Configuration subdirectory (deprecated, kept for compatibility). 

37 :return: Prompt template contents as string. 

38 :raises FileNotFoundError: If file doesn't exist. 

39 """ 

40 return load_file_from_conf(prompt_file, conf_subdir) 

41 

42 

43def render_jinja_template(template_str: str, **kwargs) -> str: 

44 """Render Jinja2 template with provided variables. 

45 

46 :param template_str: Jinja2 template string. 

47 :param kwargs: Variables to pass to template rendering. 

48 :return: Rendered template as string. 

49 :raises ImportError: If Jinja2 is not installed. 

50 """ 

51 try: 

52 from jinja2 import Template 

53 except ImportError: 

54 raise ImportError( 

55 "Jinja2 is not installed. " 

56 "Install it with: poetry install --extras langextract" 

57 ) 

58 

59 template = Template(template_str) 

60 return template.render(**kwargs)