@callmedayz/ai-prompt-toolkit
Version:
Professional AI prompt engineering toolkit with advanced template features, real-time dashboards, conditional logic, template inheritance, live monitoring, OpenRouter integration, and 310+ model support
86 lines • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromptTemplate = void 0;
/**
* A flexible prompt template system for AI applications
*/
class PromptTemplate {
constructor(options) {
this.template = options.template;
this.variables = options.variables || {};
this.escapeHtml = options.escapeHtml || false;
this.preserveWhitespace = options.preserveWhitespace || true;
}
/**
* Render the template with provided variables
*/
render(variables) {
const allVariables = { ...this.variables, ...variables };
let result = this.template;
// Replace variables in the format {{variable}} or {variable}
result = result.replace(/\{\{(\w+)\}\}|\{(\w+)\}/g, (match, p1, p2) => {
const key = p1 || p2;
const value = allVariables[key];
if (value === undefined) {
throw new Error(`Variable '${key}' not found in template variables`);
}
let stringValue = String(value);
if (this.escapeHtml) {
stringValue = this.escapeHtmlChars(stringValue);
}
return stringValue;
});
// Handle whitespace preservation
if (!this.preserveWhitespace) {
result = result.replace(/\s+/g, ' ').trim();
}
return result;
}
/**
* Get all variable names used in the template
*/
getVariables() {
const matches = this.template.match(/\{\{(\w+)\}\}|\{(\w+)\}/g) || [];
const uniqueVars = new Set();
matches.forEach(match => {
const cleaned = match.replace(/[{}]/g, '');
uniqueVars.add(cleaned);
});
return Array.from(uniqueVars);
}
/**
* Validate that all required variables are provided
*/
validate(variables) {
const allVariables = { ...this.variables, ...variables };
const requiredVars = this.getVariables();
const missing = requiredVars.filter(varName => allVariables[varName] === undefined);
return {
isValid: missing.length === 0,
missing
};
}
/**
* Create a new template with updated variables
*/
withVariables(variables) {
return new PromptTemplate({
template: this.template,
variables: { ...this.variables, ...variables },
escapeHtml: this.escapeHtml,
preserveWhitespace: this.preserveWhitespace
});
}
escapeHtmlChars(text) {
const htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, char => htmlEscapes[char]);
}
}
exports.PromptTemplate = PromptTemplate;
//# sourceMappingURL=prompt-template.js.map