Skip to main content

PROMPT TEMPLATE

prompt-template.ts

Versioned prompts with variable injection, testing.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to treat prompts as versioned artifacts: variable injection with validation, safety guardrails injected automatically, registry pattern for managing versions. Prompt changes tracked like code changes.

WHEN TO USE THIS

Any application with AI prompts — templates prevent string-concatenation bugs and enable A/B testing of prompt versions.

AT A GLANCE

const template = new PromptTemplate({
  version: '1.2',
  text: 'Classify this {{category}}: {{input}}',
  variables: ['category', 'input'],
});

FRAMEWORK IMPLEMENTATIONS

TypeScript
class PromptTemplate {
  constructor(
    private version: string,
    private template: string,
    private variables: string[],
  ) {}

  render(vars: Record<string, string>): string {
    for (const v of this.variables) {
      if (!(v in vars)) throw new Error(`Missing: ${v}`);
    }
    let result = this.template;
    for (const [k, v] of Object.entries(vars)) {
      result = result.replaceAll(`{{${k}}}`, v);
    }
    return result;
  }
}
← All Patterns