class PromptManager
A class that manages loading and accessing prompt templates from a specified directory, with automatic directory creation and error handling.
/tf/active/vicechatdev/QA_updater/core/prompt_manager.py
5 - 45
simple
Purpose
The PromptManager class provides a centralized way to load prompt templates from text files stored in a configurable directory. It handles file I/O operations, directory validation, and provides robust error handling for missing files or read errors. This is useful for applications that use templated prompts for LLMs or other text-based systems, allowing prompts to be stored externally and loaded dynamically at runtime.
Source Code
class PromptManager:
"""Manages loading and accessing prompt templates."""
def __init__(self, config: ConfigParser):
"""
Initializes the PromptManager with the prompt directory specified in the config.
Args:
config (ConfigParser): Configuration object containing path settings.
"""
self.logger = logging.getLogger(__name__)
self.prompt_dir = config.get('paths', 'prompt_dir', fallback='./prompts')
if not os.path.exists(self.prompt_dir):
self.logger.warning(f"Prompt directory not found: {self.prompt_dir}. "
"Ensure the directory exists or update the config.")
os.makedirs(self.prompt_dir, exist_ok=True) # Create if missing
self.logger.info(f"PromptManager initialized with prompt directory: {self.prompt_dir}")
def load_prompt_template(self, filename: str) -> str:
"""
Loads a prompt template from the specified file.
Args:
filename (str): The name of the file containing the prompt template.
Returns:
str: The prompt template as a string, or an empty string if the file could not be loaded.
"""
filepath = os.path.join(self.prompt_dir, filename)
try:
with open(filepath, 'r') as f:
return f.read()
except FileNotFoundError:
self.logger.error(f"Prompt file not found: {filepath}")
return ""
except Exception as e:
self.logger.exception(f"Error loading prompt file: {e}")
return ""
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
config: A ConfigParser object containing configuration settings. Must have a 'paths' section with an optional 'prompt_dir' key that specifies the directory path where prompt template files are stored. If 'prompt_dir' is not provided, defaults to './prompts'.
Return Value
Instantiation returns a PromptManager object configured with the specified prompt directory. The load_prompt_template method returns a string containing the contents of the requested prompt file, or an empty string if the file cannot be loaded due to errors.
Class Interface
Methods
__init__(self, config: ConfigParser) -> None
Purpose: Initializes the PromptManager with the prompt directory specified in the config, creates the directory if it doesn't exist, and sets up logging
Parameters:
config: ConfigParser object containing path settings with 'paths' section and optional 'prompt_dir' key
Returns: None (constructor)
load_prompt_template(self, filename: str) -> str
Purpose: Loads a prompt template from the specified file in the prompt directory and returns its contents as a string
Parameters:
filename: The name of the file containing the prompt template (e.g., 'system_prompt.txt'). Should be relative to the prompt directory, not an absolute path
Returns: The prompt template as a string if successfully loaded, or an empty string if the file could not be found or read due to errors
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
logger |
logging.Logger | Logger instance for the PromptManager class, used to log initialization, warnings, and errors | instance |
prompt_dir |
str | The directory path where prompt template files are stored, configured from the ConfigParser object or defaulting to './prompts' | instance |
Dependencies
osloggingconfigparser
Required Imports
import os
import logging
from configparser import ConfigParser
Usage Example
from configparser import ConfigParser
import logging
# Setup logging
logging.basicConfig(level=logging.INFO)
# Create configuration
config = ConfigParser()
config.add_section('paths')
config.set('paths', 'prompt_dir', './my_prompts')
# Instantiate PromptManager
prompt_manager = PromptManager(config)
# Load a prompt template
template = prompt_manager.load_prompt_template('system_prompt.txt')
if template:
print(f"Loaded template: {template[:100]}...")
else:
print("Failed to load template")
# Use the template
user_input = "Hello"
final_prompt = template.format(user_input=user_input)
Best Practices
- Always check if the returned template string is empty before using it, as this indicates a loading failure
- Ensure the prompt directory exists and has proper read permissions before instantiating the class
- Use descriptive filenames for prompt templates to make them easy to identify
- The class automatically creates the prompt directory if it doesn't exist, but it's better to create it beforehand with proper permissions
- Store prompt templates as plain text files with appropriate extensions (e.g., .txt, .prompt)
- The class is stateless after initialization, so a single instance can be reused throughout the application lifecycle
- Monitor logs for warnings about missing directories or errors loading files
- Consider implementing caching if loading the same templates repeatedly for performance optimization
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ReferenceManager_v2 46.1% similar
-
class ReferenceManager_v3 45.9% similar
-
class ReferenceManager_v5 45.8% similar
-
class ReferenceManager_v4 45.5% similar
-
function get_email_templates 42.4% similar