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-
71from pathlib import Path
82
93import yaml
148
159
1610class 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-
2711 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- """
3512 super ().__init__ (** kwargs )
3613 self .language : str = language or C .language
3714
3815 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- """
4816 if prompt_file_path is None :
4917 return self
5018
@@ -60,64 +28,27 @@ def load_prompt_by_file(self, prompt_file_path: Path | str = None):
6028 return self
6129
6230 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- """
7231 if not prompt_dict :
7332 return self
7433
7534 for key , value in prompt_dict .items ():
7635 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-
36+ if key in self :
37+ logger .warning (f"Overwriting prompt key={ key } , old_value={ self [key ]} , new_value={ value } " )
8138 else :
82- self . _data [ key ] = value
83- logger . debug ( f"add prompt_dict key= { key } " )
39+ logger . debug ( f"Adding new prompt key= { key } , value= { value } " )
40+ self [ key ] = value
8441 return self
8542
8643 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- """
9844 key : str = prompt_name
9945 if self .language and not key .endswith (self .language .strip ()):
10046 key += "_" + self .language .strip ()
10147
102- assert key in self . _data , f"prompt_name={ key } not found."
103- return self . _data [key ]
48+ assert key in self , f"prompt_name={ key } not found."
49+ return self [key ]
10450
10551 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- """
12152 prompt = self .get_prompt (prompt_name )
12253
12354 flag_kwargs = {k : v for k , v in kwargs .items () if isinstance (v , bool )}
@@ -128,7 +59,7 @@ def prompt_format(self, prompt_name: str, **kwargs) -> str:
12859 for line in prompt .strip ().split ("\n " ):
12960 hit = False
13061 hit_flag = True
131- for key , flag in kwargs .items ():
62+ for key , flag in flag_kwargs .items ():
13263 if not line .startswith (f"[{ key } ]" ):
13364 continue
13465
0 commit comments