Prompt Templates
Prompt templates are reusable prompts with placeholders for the parts that change, like the user question or a document. Templates keep prompts consistent across your app and make them easy to test and improve.
A Simple Template in Python
TEMPLATE = """You are a friendly product copywriter.
Write a {length}-word description of the product below for {audience}.
Highlight: {highlights}.
<product>
{product}
</product>"""
prompt = TEMPLATE.format(
length=50,
audience="busy parents",
highlights="dishwasher safe, BPA free",
product="Kids' lunch box with 4 compartments",
)
print(prompt)You are a friendly product copywriter. Write a 50-word description of the product below for busy parents. Highlight: dishwasher safe, BPA free. <product> Kids' lunch box with 4 compartments </product>
A Template in JavaScript
const reviewPrompt = ({ language, code }) => `Review this ${language} code.
List bugs first, then style issues. Max 5 bullets.
<code>
${code}
</code>`;
console.log(reviewPrompt({ language: 'Python', code: 'print(1/0)' }));Review this Python code. List bugs first, then style issues. Max 5 bullets. <code> print(1/0) </code>
Good Template Practices
- Keep templates in their own files, not scattered across the codebase.
- Version them (v1, v2) and record which version produced each output.
- Wrap inserted user content in delimiters so it is clearly data.
- Trim or limit variable content to stay inside the context window.
- Test every template change against a fixed set of examples (see Evaluation).
Templates for Chat APIs
For chat models, a template is usually a list of messages: a fixed system message, optional few-shot turns, and a user message built from variables.
messages = [
{"role": "system", "content": SYSTEM_PROMPT_V3},
{"role": "user", "content": f"<question>{question}</question>"},
](sent to any chat-completion style API)
Frequently asked questions
Do I need a library for prompt templates?
No. String formatting is enough for most apps. Frameworks add features like versioning and tracing if you need them.
How should I store prompts?
In version control alongside your code, or in a prompt management tool with versions and change history.
Is it safe to insert user input into a template?
It is necessary, but treat it as untrusted: use delimiters and defend against prompt injection.