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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 14 views 0 copies

Python code

22 lines
Python 3.9+
from 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

stdout
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

  1. Use f-strings with a pre-built dict: `template = f"...{data['topic']}..."` for simpler one-off cases
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.