|
| 1 | +"""Prompt handler for loading and managing prompts. |
| 2 | +
|
| 3 | +This module provides a class for loading prompts from files, managing |
| 4 | +language-specific prompts, and formatting prompts with variables. |
| 5 | +""" |
| 6 | + |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +import yaml |
| 10 | +from loguru import logger |
| 11 | + |
| 12 | +from .base_context import BaseContext |
| 13 | +from .service_context import C |
| 14 | + |
| 15 | + |
| 16 | +class PromptHandler(BaseContext): |
| 17 | + """Handler for loading, storing, and formatting prompts. |
| 18 | +
|
| 19 | + This class manages prompts loaded from YAML files, supports |
| 20 | + language-specific prompts, and provides formatting with variables |
| 21 | + and conditional flags. |
| 22 | +
|
| 23 | + Attributes: |
| 24 | + language: Language code for language-specific prompts. |
| 25 | + """ |
| 26 | + |
| 27 | + def __init__(self, language: str = "", **kwargs): |
| 28 | + """Initialize PromptHandler with language setting. |
| 29 | +
|
| 30 | + Args: |
| 31 | + language: Language code for language-specific prompts. |
| 32 | + If not provided, uses the language from service context. |
| 33 | + **kwargs: Additional context data to store. |
| 34 | + """ |
| 35 | + super().__init__(**kwargs) |
| 36 | + self.language: str = language or C.language |
| 37 | + |
| 38 | + def load_prompt_by_file(self, prompt_file_path: Path | str = None): |
| 39 | + """Load prompts from a YAML file. |
| 40 | +
|
| 41 | + Args: |
| 42 | + prompt_file_path: Path to the YAML file containing prompts. |
| 43 | + Can be a Path object or string. If None, does nothing. |
| 44 | +
|
| 45 | + Returns: |
| 46 | + Self for method chaining. |
| 47 | + """ |
| 48 | + if prompt_file_path is None: |
| 49 | + return self |
| 50 | + |
| 51 | + if isinstance(prompt_file_path, str): |
| 52 | + prompt_file_path = Path(prompt_file_path) |
| 53 | + |
| 54 | + if not prompt_file_path.exists(): |
| 55 | + return self |
| 56 | + |
| 57 | + with prompt_file_path.open(encoding="utf-8") as f: |
| 58 | + prompt_dict = yaml.load(f, yaml.FullLoader) |
| 59 | + self.load_prompt_dict(prompt_dict) |
| 60 | + return self |
| 61 | + |
| 62 | + def load_prompt_dict(self, prompt_dict: dict = None): |
| 63 | + """Load prompts from a dictionary. |
| 64 | +
|
| 65 | + Args: |
| 66 | + prompt_dict: Dictionary of prompt names to prompt strings. |
| 67 | + If None, does nothing. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + Self for method chaining. |
| 71 | + """ |
| 72 | + if not prompt_dict: |
| 73 | + return self |
| 74 | + |
| 75 | + for key, value in prompt_dict.items(): |
| 76 | + if isinstance(value, str): |
| 77 | + if key in self._data: |
| 78 | + self._data[key] = value |
| 79 | + logger.warning(f"prompt_dict key={key} overwrite!") |
| 80 | + |
| 81 | + else: |
| 82 | + self._data[key] = value |
| 83 | + logger.debug(f"add prompt_dict key={key}") |
| 84 | + return self |
| 85 | + |
| 86 | + def get_prompt(self, prompt_name: str): |
| 87 | + """Get a prompt by name, with language suffix if applicable. |
| 88 | +
|
| 89 | + Args: |
| 90 | + prompt_name: Base name of the prompt to retrieve. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + The prompt string. |
| 94 | +
|
| 95 | + Raises: |
| 96 | + AssertionError: If the prompt (with language suffix) is not found. |
| 97 | + """ |
| 98 | + key: str = prompt_name |
| 99 | + if self.language and not key.endswith(self.language.strip()): |
| 100 | + key += "_" + self.language.strip() |
| 101 | + |
| 102 | + assert key in self._data, f"prompt_name={key} not found." |
| 103 | + return self._data[key] |
| 104 | + |
| 105 | + def prompt_format(self, prompt_name: str, **kwargs) -> str: |
| 106 | + """Format a prompt with variables and conditional flags. |
| 107 | +
|
| 108 | + This method supports two types of formatting: |
| 109 | + 1. Boolean flags: Lines starting with [flag_name] are included |
| 110 | + only if the corresponding flag is True. |
| 111 | + 2. Variable substitution: Other kwargs are used for string |
| 112 | + formatting with {variable_name}. |
| 113 | +
|
| 114 | + Args: |
| 115 | + prompt_name: Name of the prompt to format. |
| 116 | + **kwargs: Variables and flags for formatting. |
| 117 | +
|
| 118 | + Returns: |
| 119 | + The formatted prompt string. |
| 120 | + """ |
| 121 | + prompt = self.get_prompt(prompt_name) |
| 122 | + |
| 123 | + flag_kwargs = {k: v for k, v in kwargs.items() if isinstance(v, bool)} |
| 124 | + other_kwargs = {k: v for k, v in kwargs.items() if not isinstance(v, bool)} |
| 125 | + |
| 126 | + if flag_kwargs: |
| 127 | + split_prompt = [] |
| 128 | + for line in prompt.strip().split("\n"): |
| 129 | + hit = False |
| 130 | + hit_flag = True |
| 131 | + for key, flag in kwargs.items(): |
| 132 | + if not line.startswith(f"[{key}]"): |
| 133 | + continue |
| 134 | + |
| 135 | + hit = True |
| 136 | + hit_flag = flag |
| 137 | + line = line.strip(f"[{key}]") |
| 138 | + break |
| 139 | + |
| 140 | + if not hit: |
| 141 | + split_prompt.append(line) |
| 142 | + elif hit_flag: |
| 143 | + split_prompt.append(line) |
| 144 | + |
| 145 | + prompt = "\n".join(split_prompt) |
| 146 | + |
| 147 | + if other_kwargs: |
| 148 | + prompt = prompt.format(**other_kwargs) |
| 149 | + |
| 150 | + return prompt |
0 commit comments