Prompt templates with Jinja

By Ryze AI Team

Managing prompts as template files instead of inline strings makes them versionable, reviewable, and testable. This tutorial uses Jinja2.

1. Install

pip install jinja2

2. Create a template

Save as prompts/summarize.jinja:

You are a helpful assistant.

Context:
{{ context }}

Task: Summarize the above in {{ num_bullets }} bullet points.
Style: {{ style | default("concise") }}.

3. Render

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader("prompts"))
template = env.get_template("summarize.jinja")
prompt = template.render(context=ctx, num_bullets=3, style="technical")
print(prompt)

4. Version control

Store templates in a prompts/ directory and review changes like code. Tag prompts with versions so you can attribute eval results.

5. Validation

Validate required variables before rendering. Jinja raises UndefinedError for missing variables by default; catch it and report clearly. Use {{ var | default("x") }} for optional inputs.

6. Testing

Render templates in unit tests with sample variables and assert the output contains expected fragments. This catches typos and missing variables before deployment.

7. Tips

Keep templates focused; one template per task. Avoid logic in templates; do computation in Python. And document each variable's purpose in a comment at the top of the file.