How to Build a Prompt Template with Variable Slots in Python
Create a reusable LLM prompt template with named variable slots using Python's string.Template class and fill them with render() calls.
Python code
22 linesfrom string import Template
class PromptTemplate:
def __init__(self, template_text):
self.template = Template(template_text)
def render(self, **kwargs):
return self.template.substitute(**kwargs)
if __name__ == "__main__":
template = PromptTemplate(
"You are a helpful assistant for {topic}. "
"Your task is to {task} while keeping the tone {tone}."
)
output = template.render(
topic="cooking",
task="explain how to make pasta",
tone="friendly and encouraging"
)
print(output)
Output
You are a helpful assistant for cooking. Your task is to explain how to make pasta while keeping the tone friendly and encouraging.
How it works
The string.Template class substitutes $-style placeholders, but here we've wrapped it in a class that exposes a clean render(**kwargs) API. The substitute() method replaces every named slot with its corresponding value passed as a keyword argument. Because substitution happens at render time, the same template object can be reused with different arguments across multiple calls, which keeps prompt-building code DRY. This pattern is ideal for LLM apps where you need consistent prompt structure with dynamic content inserted per request.
Common mistakes
- Forgetting that `substitute()` raises KeyError if a required slot is missing — use `safe_substitute()` to leave unfilled slots as-is
- Using `.format()` syntax (`{}`) instead of `$`-style placeholders expected by `string.Template`
- Passing positional arguments to `render()` instead of keyword arguments, which breaks the mapping to named slots
Variations
- Use f-strings with a pre-built dict: `template = f"...{data['topic']}..."` for simpler one-off cases
- Use `str.format_map()` with a defaultdict to allow missing keys without errors
Real-world use cases
- Generating LLM prompts for a chat assistant that feeds user input into a fixed system prompt structure.
- Creating reproducible prompt templates for batch evaluation of model outputs across many test cases.
- Building a multi-turn agent prompt where each turn's context is slotted into a shared instruction template.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.