> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mutagent.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Template Variables

> Dynamic content in prompts with type-safe variables

# 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 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?
```

<Warning>
  MutagenT uses **single curly braces** `{variable}` for template variables. If you accidentally use double braces `{{variable}}`, the CLI will warn you and suggest the correct syntax.
</Warning>

## Defining Variables with Input Schema

When creating a prompt, define your variables using `inputSchema` -- a JSON Schema object that describes expected input parameters:

<CodeGroup>
  ```typescript SDK theme={null}
  const prompt = await client.prompt.createPrompt({
    name: 'Personalized Greeting',
    rawPrompt: `Hello {user_name}, welcome to {company}!

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

  How can I assist you today?`,
    inputSchema: {
      user_name: { type: 'string', description: 'Customer name' },
      company: { type: 'string', description: 'Company name' },
      account_type: { type: 'string', enum: ['free', 'pro', 'enterprise'] },
      credits: { type: 'number', description: 'Remaining credits' },
    },
  });
  ```

  ```bash CLI theme={null}
  # Variables are embedded in prompt text using {variable} syntax
  mutagent prompts create \
    --name "Personalized Greeting" \
    --raw "Hello {user_name}, welcome to {company}!"

  # Or use system/human with output schema
  mutagent prompts create --name "Greeting" --system "You greet users" --human "Hello {user_name}" --output-schema '{"type":"object","properties":{"greeting":{"type":"string"}}}'
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.mutagent.io/api/prompt \
    -H "x-api-key: mt_xxxx" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Personalized Greeting",
      "rawPrompt": "Hello {user_name}, welcome to {company}!...",
      "inputSchema": {
        "user_name": {"type": "string"},
        "company": {"type": "string"},
        "account_type": {"type": "string"},
        "credits": {"type": "number"}
      }
    }'
  ```
</CodeGroup>

## Using Variables at Runtime

When executing a prompt in the playground, provide variable values as the `input` object:

```typescript theme={null}
// Use playground.playgroundCall to execute a prompt with variable values
const result = await client.playground.playgroundCall({
  promptId: 'prompt_id',
  input: {
    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?"
```

## Input and Output Schemas

MutagenT uses JSON Schema objects for both input and output validation:

### Input Schema

Defines the variables your prompt expects. Each key maps to a JSON Schema type definition:

```json theme={null}
{
  "inputSchema": {
    "customer_name": {
      "type": "string",
      "description": "Full name of the customer"
    },
    "order_id": {
      "type": "string",
      "pattern": "^ORD-[0-9]+$"
    },
    "is_vip": {
      "type": "boolean",
      "default": false
    },
    "order_history": {
      "type": "array",
      "items": { "type": "string" }
    }
  }
}
```

### Output Schema

Optionally defines the expected structure of the LLM's response:

```json theme={null}
{
  "outputSchema": {
    "action": {
      "type": "string",
      "enum": ["refund", "replace", "escalate", "resolve"]
    },
    "response": {
      "type": "string",
      "description": "Response message to send to customer"
    },
    "confidence": {
      "type": "number",
      "minimum": 0,
      "maximum": 1
    }
  }
}
```

## Variables in Different Content Types

### Raw Prompt

```bash theme={null}
mutagent prompts create \
  --name "summarizer" \
  --raw "Summarize the following text in {language}: {text}"
```

### System + Human Prompts

```bash theme={null}
mutagent prompts create \
  --name "support-bot" \
  --system "You are a {role} for {company}. Always respond in {language}." \
  --human "Customer question: {question}"
```

### Messages Array

```bash theme={null}
mutagent prompts create \
  --name "chat-bot" \
  --messages '[
    {"role": "system", "content": "You are a helpful {role} assistant."},
    {"role": "user", "content": "Help me with: {question}"}
  ]'
```

## Advanced Variable Patterns

### Conditional Content

While variables don't support conditionals directly, you can use boolean variables to control LLM behavior:

```typescript theme={null}
const prompt = await client.prompt.createPrompt({
  name: 'Conditional Response',
  rawPrompt: `User: {user_name}
Is VIP: {is_vip}

If the user is a VIP, provide premium support with priority handling.
If not, provide standard support.

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

### List Formatting

Format arrays as readable lists before substitution:

```typescript theme={null}
const items = ['Item 1', 'Item 2', 'Item 3'];
const formattedList = items.map((item, i) => `${i + 1}. ${item}`).join('\n');

// Use as input variable when executing the prompt
const result = await client.playground.playgroundCall({
  promptId,
  input: {
    items_list: formattedList,
  },
});
```

### JSON Stringification

For complex objects, stringify before substitution:

```typescript theme={null}
const userData = {
  name: 'Alice',
  preferences: { theme: 'dark' },
  history: ['action1', 'action2'],
};

const result = await client.playground.playgroundCall({
  promptId,
  input: {
    user_context: JSON.stringify(userData, null, 2),
  },
});
```

## Best Practices

<Warning>
  Variables are substituted as-is. Always validate and sanitize inputs to prevent prompt injection attacks.
</Warning>

<AccordionGroup>
  <Accordion title="Use descriptive variable names">
    Good: `customer_question`, `product_description`, `support_context`

    Bad: `q`, `desc`, `ctx`
  </Accordion>

  <Accordion title="Document expected formats in inputSchema">
    Use JSON Schema descriptions and constraints:

    ```json theme={null}
    {
      "date": {
        "type": "string",
        "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
        "description": "Date in YYYY-MM-DD format"
      },
      "amount": {
        "type": "number",
        "minimum": 0,
        "description": "Dollar amount with 2 decimal places"
      }
    }
    ```
  </Accordion>

  <Accordion title="Validate inputs before substitution">
    ```typescript theme={null}
    function sanitizeInput(input: string): string {
      // Remove potential injection patterns
      return input
        .replace(/[{}]/g, '')
        .slice(0, 10000); // Limit length
    }
    ```
  </Accordion>

  <Accordion title="Test with edge cases">
    Test your prompts with:

    * Empty strings
    * Very long inputs
    * Special characters
    * Unicode content
    * Potential injection attempts
  </Accordion>

  <Accordion title="Set default values">
    Handle optional variables gracefully:

    ```typescript theme={null}
    const input = {
      user_name: rawInput.userName || 'Guest',
      context: rawInput.context || 'No additional context provided',
    };
    ```
  </Accordion>
</AccordionGroup>

## Security Considerations

<Note>
  Prompt injection is a real risk. Never trust user input without validation.
</Note>

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
