Claude
Skills
Sign in
Back

prompt-template

Included with Lifetime
$97 forever

Create and manage reusable prompt templates

AI Agents

What this skill does



# Prompt Template Skill

> Standardize prompt construction for agents with reusable, composable templates.

## Overview

Consistent, well-structured prompts lead to better agent behavior. This skill provides:
- Template patterns for common prompt structures
- Variable interpolation for dynamic content
- Composition patterns for building complex prompts
- Testing approaches for prompt quality

## Core Principles

1. **Separation of concerns** - Structure, content, and variables are separate
2. **Composability** - Small templates combine into larger ones
3. **Testability** - Templates can be validated before use
4. **Versioning** - Track prompt changes like code

## Template Structure

### Basic Template Format

```yaml
# prompts/templates/example.yaml
name: example_template
version: "1.0"
description: Brief description of this template's purpose

# Variables that must be provided
variables:
  - name: task_description
    required: true
    description: What the agent should do
  - name: context
    required: false
    default: ""
    description: Additional context

# The actual prompt template
template: |
  You are a helpful assistant.

  ## Task
  {task_description}

  ## Context
  {context}

  ## Instructions
  - Be concise
  - Cite sources when possible
```

### Template Directory Structure

```
prompts/
├── templates/           # Reusable templates
│   ├── base/           # Foundation templates
│   │   ├── researcher.yaml
│   │   ├── coder.yaml
│   │   └── writer.yaml
│   ├── components/     # Composable parts
│   │   ├── output_format.yaml
│   │   ├── safety_guidelines.yaml
│   │   └── tool_usage.yaml
│   └── agents/         # Full agent prompts
│       ├── research_agent.yaml
│       └── code_review_agent.yaml
├── rendered/           # Compiled prompts (git-ignored)
└── tests/              # Prompt tests
```

## Template Engine

### Implementation

```python
#!/usr/bin/env python3
"""Prompt template engine."""

import re
import yaml
from pathlib import Path
from typing import Dict, Any, Optional, List
from dataclasses import dataclass

@dataclass
class TemplateVariable:
    name: str
    required: bool
    default: Optional[str] = None
    description: str = ""


class PromptTemplate:
    """A reusable prompt template."""

    def __init__(self, path: str):
        with open(path) as f:
            data = yaml.safe_load(f)

        self.name = data["name"]
        self.version = data.get("version", "1.0")
        self.description = data.get("description", "")
        self.template = data["template"]
        self.path = path

        # Parse variables
        self.variables = []
        for var in data.get("variables", []):
            self.variables.append(TemplateVariable(
                name=var["name"],
                required=var.get("required", False),
                default=var.get("default"),
                description=var.get("description", "")
            ))

        # Parse includes
        self.includes = data.get("includes", [])

    def render(self, **kwargs) -> str:
        """Render the template with provided variables."""
        # Check required variables
        for var in self.variables:
            if var.required and var.name not in kwargs:
                raise ValueError(f"Missing required variable: {var.name}")

        # Apply defaults
        context = {}
        for var in self.variables:
            if var.name in kwargs:
                context[var.name] = kwargs[var.name]
            elif var.default is not None:
                context[var.name] = var.default
            else:
                context[var.name] = ""

        # Handle includes
        result = self.template
        for include in self.includes:
            include_template = PromptTemplate(include)
            include_content = include_template.render(**kwargs)
            result = result.replace(f"{{{{include:{include}}}}}", include_content)

        # Substitute variables
        for key, value in context.items():
            result = result.replace(f"{{{key}}}", str(value))

        return result.strip()

    def get_variable_names(self) -> List[str]:
        """Get all variable names in template."""
        # Find {variable_name} patterns
        pattern = r'\{(\w+)\}'
        found = set(re.findall(pattern, self.template))
        return list(found)

    def validate(self) -> List[str]:
        """Validate template structure."""
        errors = []

        # Check all referenced variables are defined
        referenced = set(self.get_variable_names())
        defined = {v.name for v in self.variables}

        undefined = referenced - defined
        if undefined:
            errors.append(f"Undefined variables: {undefined}")

        unused = defined - referenced
        if unused:
            errors.append(f"Unused variables: {unused}")

        # Check includes exist
        for include in self.includes:
            if not Path(include).exists():
                errors.append(f"Include not found: {include}")

        return errors


class TemplateRegistry:
    """Registry of all available templates."""

    def __init__(self, templates_dir: str = "prompts/templates"):
        self.templates_dir = Path(templates_dir)
        self.templates: Dict[str, PromptTemplate] = {}
        self._load_templates()

    def _load_templates(self):
        """Load all templates from directory."""
        for yaml_file in self.templates_dir.rglob("*.yaml"):
            try:
                template = PromptTemplate(str(yaml_file))
                self.templates[template.name] = template
            except Exception as e:
                print(f"Warning: Failed to load {yaml_file}: {e}")

    def get(self, name: str) -> Optional[PromptTemplate]:
        """Get a template by name."""
        return self.templates.get(name)

    def list(self) -> List[str]:
        """List all template names."""
        return list(self.templates.keys())

    def render(self, name: str, **kwargs) -> str:
        """Render a template by name."""
        template = self.get(name)
        if not template:
            raise ValueError(f"Template not found: {name}")
        return template.render(**kwargs)
```

## Template Patterns

### Pattern 1: Base Agent Template

```yaml
# prompts/templates/base/agent_base.yaml
name: agent_base
version: "1.0"
description: Base template for all agents

variables:
  - name: role
    required: true
    description: The agent's role (e.g., "researcher", "coder")
  - name: capabilities
    required: true
    description: What the agent can do
  - name: constraints
    required: false
    default: ""
    description: Limitations or rules

template: |
  You are a {role} agent.

  ## Capabilities
  {capabilities}

  ## Constraints
  {constraints}

  ## Response Format
  - Be concise and actionable
  - Structure responses with clear sections
  - Cite sources when making claims
```

### Pattern 2: Task-Specific Template

```yaml
# prompts/templates/tasks/code_review.yaml
name: code_review_task
version: "1.0"
description: Template for code review tasks

variables:
  - name: code
    required: true
    description: The code to review
  - name: language
    required: true
    description: Programming language
  - name: focus_areas
    required: false
    default: "security, performance, readability"
    description: Areas to focus on

template: |
  Review the following {language} code:

  ```{language}
  {code}
  ```

  ## Focus Areas
  {focus_areas}

  ## Review Checklist
  - [ ] Security vulnerabilities
  - [ ] Performance issues
  - [ ] Code style and readability
  - [ ] Error handling
  - [ ] Test coverage considerations

  Provide specific, actionable feedback with line references.
```

### Pattern 3: Composable Components

```yaml
# prompts/templates/components/output_json.yaml
name: output_json
version: "1.0"
description: JSON output format instructions

variables:
  - name: schema
    required: true
    description: JSON schema to follow

te

Related in AI Agents