Skip to main content

Template Variables

Variables allow you to create reusable prompt templates with dynamic content. Instead of creating separate prompts for each use case, define a template once and substitute different values at runtime.

Syntax

Use double curly braces for variables:
Hello {{user_name}}, how can I help you with {{topic}} today?
Variables are replaced with actual values when the prompt is executed:
Hello Alice, how can I help you with billing today?

Defining Variables

When creating a prompt, declare variables with their types:
const prompt = await client.prompts.create({
  name: 'Personalized Greeting',
  content: `Hello {{user_name}}, welcome to {{company}}!

Your account type is: {{account_type}}
You have {{credits}} credits remaining.

How can I assist you today?`,
  variables: {
    user_name: 'string',
    company: 'string',
    account_type: 'string',
    credits: 'number',
  },
});

Using Variables

When executing a prompt, provide variable values:
const result = await client.prompts.execute('prompt_xxxx', {
  variables: {
    user_name: 'Alice',
    company: 'Acme Inc',
    account_type: 'Premium',
    credits: 150,
  },
});

// Result: "Hello Alice, welcome to Acme Inc!
// Your account type is: Premium
// You have 150 credits remaining.
// How can I assist you today?"

Variable Types

TypeDescriptionExample Usage
stringText contentNames, descriptions, questions
numberNumeric valuesCounts, IDs, amounts
booleanTrue/false valuesFeature flags, conditions
jsonComplex objectsUser profiles, configuration
arrayList of itemsTags, options, history

Type Examples

const prompt = await client.prompts.create({
  name: 'Complex Template',
  content: `User: {{user_name}}
Premium: {{is_premium}}
Order count: {{order_count}}
Recent orders: {{recent_orders}}
Preferences: {{preferences}}`,
  variables: {
    user_name: 'string',
    is_premium: 'boolean',
    order_count: 'number',
    recent_orders: 'array',
    preferences: 'json',
  },
});

// Execute with typed values
await client.prompts.execute(prompt.id, {
  variables: {
    user_name: 'Bob',
    is_premium: true,
    order_count: 42,
    recent_orders: ['Order #123', 'Order #124', 'Order #125'],
    preferences: {
      theme: 'dark',
      notifications: true,
      language: 'en',
    },
  },
});

Advanced Variable Patterns

Conditional Content

While variables don’t support conditionals directly, you can use boolean variables to control LLM behavior:
const prompt = await client.prompts.create({
  name: 'Conditional Response',
  content: `User: {{user_name}}
Is VIP: {{is_vip}}

{{#if is_vip is true, provide premium support with priority handling}}
{{#if is_vip is false, provide standard support}}

Question: {{question}}`,
  variables: {
    user_name: 'string',
    is_vip: 'boolean',
    question: 'string',
  },
});

List Formatting

Format arrays as readable lists:
const items = ['Item 1', 'Item 2', 'Item 3'];
const formattedList = items.map((item, i) => `${i + 1}. ${item}`).join('\n');

await client.prompts.execute(promptId, {
  variables: {
    items_list: formattedList,
  },
});

JSON Stringification

For complex objects, stringify before substitution:
const userData = {
  name: 'Alice',
  preferences: { theme: 'dark' },
  history: ['action1', 'action2'],
};

await client.prompts.execute(promptId, {
  variables: {
    user_context: JSON.stringify(userData, null, 2),
  },
});

Variable Validation

MutagenT validates variables at execution time:
try {
  await client.prompts.execute(promptId, {
    variables: {
      // Missing required variable 'company'
      user_name: 'Alice',
    },
  });
} catch (error) {
  // Error: Missing required variable: company
  console.error(error.message);
}

Best Practices

Variables are substituted as-is. Always validate and sanitize inputs to prevent prompt injection attacks.
Good: customer_question, product_description, support_contextBad: q, desc, ctx
Add comments in your prompt or description:
{{date}} - Expected format: YYYY-MM-DD
{{amount}} - Expected: number with 2 decimal places
function sanitizeInput(input: string): string {
  // Remove potential injection patterns
  return input
    .replace(/\{\{/g, '{')
    .replace(/\}\}/g, '}')
    .slice(0, 10000); // Limit length
}
Test your prompts with:
  • Empty strings
  • Very long inputs
  • Special characters
  • Unicode content
  • Potential injection attempts
Handle optional variables gracefully:
const variables = {
  user_name: input.userName || 'Guest',
  context: input.context || 'No additional context provided',
};

Security Considerations

Prompt injection is a real risk. Never trust user input without validation.
  1. Sanitize all user inputs before using as variables
  2. Limit input length to prevent context overflow
  3. Use allowlists for enumerated values when possible
  4. Monitor outputs for unexpected behavior
  5. Log variable values for debugging and auditing