Create reusable prompt templates with variables
✓Works with OpenClaudeYou are a prompt engineering specialist. The user wants to create reusable prompt templates with variables that can be filled dynamically for different use cases.
What to check first
- Identify what variables will change between prompt invocations (e.g.,
{topic},{tone},{length}) - Decide on template syntax — curly braces
{}, double braces{{}}, or environment-style$VAR - Verify your LLM API supports streaming or batch requests if using templates at scale
Steps
- Define your template string with placeholder variables using
{variable_name}syntax - Create a function that accepts the template and a dictionary of variable values
- Use Python's
.format()method or f-strings to substitute variables into the template - Add validation to check that all required variables are provided before rendering
- Store templates in a separate file (JSON or YAML) for easy management and reuse
- Build a template loader function that reads template files and caches them in memory
- Create a wrapper function that combines template loading, variable validation, and API calls
- Test the rendered prompt with sample variables to ensure quality before sending to the LLM
Code
import json
import re
from typing import Dict, List
class PromptTemplate:
def __init__(self, template: str, required_vars: List[str] = None):
self.template = template
self.required_vars = required_vars or self._extract_variables()
def _extract_variables(self) -> List[str]:
"""Extract variable names from template using regex."""
return re.findall(r'\{([^}]+)\}', self.template)
def validate(self, variables: Dict[str, str]) -> bool:
"""Check that all required variables are provided."""
missing = set(self.required_vars) - set(variables.keys())
if missing:
raise ValueError(f"Missing required variables: {missing}")
return True
def render(self, variables: Dict[str, str]) -> str:
"""Render template with provided variables."""
self.validate(variables)
return self.template.format(**variables)
class TemplateLibrary:
def __init__(self, filepath: str = None):
self.templates = {}
if filepath:
self.load_from_file(filepath)
def load_from_file(self, filepath: str):
"""Load templates from JSON file."""
with open(filepath, 'r') as f:
data = json.load(f)
for name, template_str in data.items():
self.templates[name] = PromptTemplate(template_str)
def register(self, name: str, template: str):
"""Register a new template."""
self.templates[name] = PromptTemplate(template)
def get(self, name: str) -> Prom
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Forgetting to handle rate limits — Anthropic returns 429 errors that need exponential backoff
- Hardcoding the model name in 50 places — use a single config so you can swap models in one place
- Not setting a timeout on API calls — a hanging request can lock your worker indefinitely
- Logging API responses with sensitive data — PII can end up in your logs without realizing
- Treating the API as deterministic — same prompt, different output. Test on multiple runs
When NOT to Use This Skill
- For deterministic tasks where regex or rule-based code would work — LLMs add cost and latency for no benefit
- When you need 100% accuracy on a known schema — use structured output APIs or fine-tuning instead
- For real-time low-latency applications under 100ms — even the fastest LLM is too slow
How to Verify It Worked
- Test with malformed inputs, empty strings, and edge cases — APIs often behave differently than docs suggest
- Verify your error handling on all 4xx and 5xx responses — most code only handles the happy path
- Run a load test with 10x your expected traffic — rate limits hit fast
- Check token usage matches your estimate — surprises here become surprises on your bill
Production Considerations
- Set a daily spend cap on your Anthropic console — prevents runaway costs from bugs or attacks
- Use prompt caching for static parts of your prompts — can cut costs by 50-90%
- Stream responses for any user-facing output — perceived latency drops by 70%
- Have a fallback model ready — if Claude is down, you should be able to swap to a backup with one config change
Related AI/ML Integration Skills
Other Claude Code skills in the same category — free to download.
OpenAI Integration
Integrate OpenAI API with best practices
Claude API Setup
Set up Claude/Anthropic API integration
Embedding Search
Implement vector embedding search
RAG Pipeline
Build Retrieval-Augmented Generation pipeline
AI Streaming
Implement streaming AI responses
LangChain Setup
Set up LangChain for AI workflows
Model Comparison
Compare responses from multiple AI models
AI Rate Limiter
Implement rate limiting for AI API calls
Want a AI/ML Integration skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.