Create prompt_template.py
Browse files- prompt_template.py +86 -0
prompt_template.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import yaml
|
3 |
+
from dataclasses import dataclass, field
|
4 |
+
from typing import Dict, List, Set, Optional
|
5 |
+
|
6 |
+
from openai import OpenAI
|
7 |
+
|
8 |
+
@dataclass
|
9 |
+
class PromptTemplate:
|
10 |
+
"""
|
11 |
+
A template class for managing and validating LLM prompts.
|
12 |
+
|
13 |
+
This class handles:
|
14 |
+
- Storing system and user prompts
|
15 |
+
- Validating required template variables
|
16 |
+
- Formatting prompts with provided variables
|
17 |
+
|
18 |
+
Attributes:
|
19 |
+
system_prompt (str): The system-level instructions for the LLM
|
20 |
+
user_template (str): Template string with variables in {variable} format
|
21 |
+
"""
|
22 |
+
system_prompt: str
|
23 |
+
user_template: str
|
24 |
+
|
25 |
+
def __post_init__(self):
|
26 |
+
"""Initialize the set of required variables from the template."""
|
27 |
+
self.required_variables: Set[str] = self._get_required_variables()
|
28 |
+
|
29 |
+
def _get_required_variables(self) -> set:
|
30 |
+
"""
|
31 |
+
Extract required variables from the template using regex.
|
32 |
+
|
33 |
+
Returns:
|
34 |
+
set: Set of variable names found in the template
|
35 |
+
|
36 |
+
Example:
|
37 |
+
Template "Write about {topic} in {style}" returns {'topic', 'style'}
|
38 |
+
"""
|
39 |
+
return set(re.findall(r'\{(\w+)\}', self.user_template))
|
40 |
+
|
41 |
+
def _validate_variables(self, provided_vars: Dict):
|
42 |
+
"""
|
43 |
+
Ensure all required template variables are provided.
|
44 |
+
|
45 |
+
Args:
|
46 |
+
provided_vars: Dictionary of variable names and values
|
47 |
+
|
48 |
+
Raises:
|
49 |
+
ValueError: If any required variables are missing
|
50 |
+
"""
|
51 |
+
provided_keys = set(provided_vars.keys())
|
52 |
+
missing_vars = self.required_variables - provided_keys
|
53 |
+
if missing_vars:
|
54 |
+
error_msg = (
|
55 |
+
f"\nPrompt Template Error:\n"
|
56 |
+
f"Missing required variables: {', '.join(missing_vars)}\n"
|
57 |
+
f"Template requires: {', '.join(self.required_variables)}\n"
|
58 |
+
f"You provided: {', '.join(provided_keys)}\n"
|
59 |
+
f"Template string: '{self.user_template}'"
|
60 |
+
)
|
61 |
+
raise ValueError(error_msg)
|
62 |
+
|
63 |
+
def format(self, **kwargs) -> List[Dict[str, str]]:
|
64 |
+
"""
|
65 |
+
Format the prompt template with provided variables.
|
66 |
+
|
67 |
+
Args:
|
68 |
+
**kwargs: Key-value pairs for template variables
|
69 |
+
|
70 |
+
Returns:
|
71 |
+
List[Dict[str, str]]: Formatted messages ready for LLM API
|
72 |
+
|
73 |
+
Example:
|
74 |
+
template.format(topic="AI", style="academic")
|
75 |
+
"""
|
76 |
+
self._validate_variables(kwargs)
|
77 |
+
|
78 |
+
try:
|
79 |
+
formatted_user_message = self.user_template.format(**kwargs)
|
80 |
+
except Exception as e:
|
81 |
+
raise ValueError(f"Error formatting template: {str(e)}")
|
82 |
+
|
83 |
+
return [
|
84 |
+
{"role": "system", "content": self.system_prompt},
|
85 |
+
{"role": "user", "content": formatted_user_message}
|
86 |
+
]
|