Prompt
How do I create reusable prompt templates with variables?
Latest observation
A good way to create reusable prompt templates is to use placeholders for the parts that change, then fill them in at runtime.
Basic idea
Instead of writing:
Summarize this article about climate change for a 5th grader.
Write a template like:
Summarize this article about {topic} for a {audience}.
Then you can reuse it by substituting values for topic and audience.
Simple examples
1) Plain text template
Write a {tone} email to {recipient} about {subject}.
Filled in:
Write a friendly email to the team about the project deadline.
2) JSON-style template
{
"task": "Translate the following text into {language}",
"text": "{input_text}"
}
3) Chat prompt template
System:
You are a helpful assistant that writes concise product descriptions.
User:
Write a {style} description for {product} targeted at {audience}.
Best practices
1) Use clear variable names
Good:
{topic}{tone}{audience}
Less clear:
{x}{value1}
2) Keep instructions separate from data
This reduces confusion and makes templates easier to maintain.
Instruction: Analyze the sentiment.
Text: {text}
3) Provide defaults when helpful
Example:
- tone =
professional - language =
English
4) Validate inputs
Make sure required variables are present before rendering the template.
5) Escape user content if needed
If user-provided text may contain braces or special formatting, sanitize it before substitution.
Example in Python
template = "Write a {tone} summary of {article_topic} for {audience}."
filled_prompt = template.format(
tone="friendly",
article_topic="renewable energy",
audience="high school students"
)
print(filled_prompt)
Output:
Write a friendly summary of renewable energy for high school students.
Example with a reusable function
def render_prompt(template, **kwargs):
return template.format(**kwargs)
template = "Classify this text as {label_type}: {text}"
prompt = render_prompt(
template,
label_type="positive or negative",
text="I loved the movie."
)
print(prompt)
If you’re using an LLM framework
Many frameworks support prompt templates directly:
- LangChain:
PromptTemplate - Jinja2: more advanced templating with conditionals/loops
- Handlebars/Mustache: lightweight templating systems
Example with Jinja2:
Write a {{ tone }} review of {{ product }}.
{% if include_pros %}
Pros: {{ pros }}
{% endif %}
A useful template pattern
Role: {role}
Task: {task}
Context: {context}
Constraints: {constraints}
Output format: {output_format}
This makes prompts easier to reuse and debug.
If you want, I can also show you:
- a Python/Jinja2 version,
- a JavaScript version, or
- a best-practice prompt template structure for LLM apps.