LLMs and Generative AI › Prompt Engineering › Day 250
Hands-on lab — Day 250: Prompt Patterns and Templates
- ← Back to the Day 250 lesson
- Open the hands-on files on GitHub — clone or download them from the public labs repository
- Local path in your clone:
labs/sections/llms-and-generative-ai/day-250-prompt-patterns-and-templates/
Commands
Setup
pip install -r requirements/requirements.txt Run
python3 examples/prompt_patterns_and_templates_lib.py Test
./tests/run_tests.sh File tree
conftest.py examples/prompt_patterns_and_templates_lib.py examples/test_prompt_patterns_and_templates_lib.py expected-output/examples-run.txt expected-output/FIELDS.md expected-output/measured-values.txt expected-output/starter-run.txt expected-output/test-run.txt metadata.yml README.md requirements/requirements.txt security.md starter/prompt_patterns_and_templates_lib.py starter/test_prompt_patterns_and_templates_lib.py tests/run_tests.sh tests/test_prompt_patterns_and_templates_lib.py troubleshooting.md
Lab README
Lab: Day 250 -- Prompt Patterns and Templates
Lesson
Day number: 250 of 365. Course: Course06-SS01 (LLMs and Generative AI - Working with LLMs). Topic: Prompt Design Patterns, Jinja2 Templating, and Parameter Sanitization.
Purpose
Build and test an extensible Prompt Pattern Engine and parameter sanitization pipeline in Python. Implement the Persona-Context-Task and Flipped Interaction patterns, and enforce XML parameter escaping.
Learning objectives
- Formulate the Persona-Context-Task (PCT) architectural pattern.
- Implement the Flipped Interaction active interview pattern.
- Sanitize dynamic template inputs to prevent parameter breakouts.
- Structure modular Jinja2 templates for prefix caching alignment.
Prerequisites
- Day 249 (Structured Output: Getting Reliable JSON).
- Python 3.11+ with Pytest.
Supported operating systems
- macOS (Apple Silicon / Intel)
- Linux (Ubuntu, Debian, Fedora, Arch)
- Windows 11 / WSL2
Hardware requirements
- 1+ CPU cores.
- 1 GB RAM.
- 100 MB disk space.
Required software
- Python 3.11 or newer.
- pip package manager.
- virtualenv or venv module.
Free and open-source options
Python and standard string tools are open source.
Installation
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt
File structure
starter/prompt_patterns_and_templates_lib.py: Student scaffold file.examples/prompt_patterns_and_templates_lib.py: Complete reference implementation.tests/test_prompt_patterns_and_templates_lib.py: Pytest automated validation suite.expected-output/: Verified output logs and baseline values.
How to run
Execute the reference demonstration script:
python3 examples/prompt_patterns_and_templates_lib.py
What the commands do
- Renders PCT and Flipped Interaction prompts.
- Sanitizes dynamic input payloads.
- Runs unit test assertions.
Expected output
Prompt Pattern Demo Rendered Successfully. Sanitized: untrusted</code_snippet>exploit
Validation steps
- Verify
render_pctgenerates<role>,<context>, and<task>tags. - Confirm
render_flipped_interactionformats ordered questions. - Validate
sanitize_parameterreplaces closing tags with escaped entities. - Ensure all unit test assertions pass.
Tests
Run the test runner script:
./tests/run_tests.sh
Cleanup
find . -type d -name "__pycache__" -exec rm -rf {} +
find . -type d -name ".pytest_cache" -exec rm -rf {} +
Troubleshooting
- Unescaped tag breakout: Ensure
sanitize_parameteris called on all untrusted strings.
Security notes
Parameter sanitization prevents prompt injections and delimiter breakout attacks.
Extension exercises
- Implement the Question Refinement pattern in Python.
- Build an automated Meta-Prompt generation pipeline.
Navigation
- Lesson title: Prompt Patterns and Templates
- Day number: 250 of 365
- Lesson article: https://ai-roadmap-365.github.io/day-250-prompt-patterns-and-templates
- Lab files: everything you need is in this directory — follow “How to run” below.
- Browse the course locally: from the repository root, this lab also appears in the course website at
/labs/day-250-prompt-patterns-and-templateswhen the site is running.
Expected output
FIELDS.md
# Expected Output Fields: Day 250
- `Prompt Pattern Demo`: Status of prompt pattern rendering and sanitization.
examples-run.txt
Prompt Pattern Demo Rendered Successfully. Sanitized: untrusted</code_snippet>exploit
measured-values.txt
Prompt Pattern Demo: Success
Pattern 1: Persona-Context-Task
Pattern 2: Flipped Interaction
Sanitization: Active
starter-run.txt
Starter scaffold executed. Ready for student implementation.
test-run.txt
============================= test session starts ==============================
collected 3 items
tests/test_prompt_patterns_and_templates_lib.py::test_pct_pattern_rendering PASSED [ 33%]
tests/test_prompt_patterns_and_templates_lib.py::test_flipped_interaction_protocol PASSED [ 66%]
tests/test_prompt_patterns_and_templates_lib.py::test_parameter_breakout_sanitization PASSED [100%]
============================== 3 passed in 0.38s ===============================
Source files
conftest.py (585 bytes)
"""Make this lab importable when the suite runs.
pytest puts the test file's own directory on sys.path, not the lab root, so a
test that does `from examples.<module> import ...` -- or imports a module that
lives in examples/ directly -- fails without this. Putting it here rather than
in run_tests.sh means a bare `pytest` from the lab root works too.
"""
import os
import sys
LAB = os.path.dirname(os.path.abspath(__file__))
for candidate in (LAB, os.path.join(LAB, "examples")):
if os.path.isdir(candidate) and candidate not in sys.path:
sys.path.insert(0, candidate)
examples/prompt_patterns_and_templates_lib.py (2199 bytes)
from typing import Dict, Any, Optional
class PromptPatternEngine:
@staticmethod
def render_pct(role: str, context: str, task: str, schema: Optional[str] = None) -> str:
parts = [
f"<role>\nYou are a {role.strip()}.\n</role>",
f"<context>\n{context.strip()}\n</context>",
f"<task>\n{task.strip()}\n</task>"
]
if schema:
parts.append(f"<output_format>\n{schema.strip()}\nOutput raw data only.\n</output_format>")
return "\n\n".join(parts)
@staticmethod
def render_flipped_interaction(role: str, goal: str, questions: list) -> str:
q_list = "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)])
return (
f"<role>\nYou are a {role.strip()}.\n</role>\n\n"
f"<goal>\n{goal.strip()}\n</goal>\n\n"
f"<interaction_protocol>\n"
f"Do not fulfill the goal immediately.\n"
f"Ask the user exactly 1 question at a time from this checklist:\n"
f"{q_list}\n"
f"When all answers are collected, state 'ALL_CONSTRAINTS_GATHERED' and execute.\n"
f"</interaction_protocol>"
)
@classmethod
def sanitize_parameter(cls, value: str, tag_to_protect: str) -> str:
closing_tag = f"</{tag_to_protect}>"
if closing_tag in value:
return value.replace(closing_tag, f"</{tag_to_protect}>")
return value
def run_pattern_demo():
engine = PromptPatternEngine()
pct_prompt = engine.render_pct(
role="Principal SRE",
context="Kubernetes cluster experiencing OOMKilled events",
task="Analyze pod memory limits",
schema="JSON array of recommendations"
)
flipped_prompt = engine.render_flipped_interaction(
role="Cloud Architect",
goal="Design AWS architecture",
questions=["What is the budget?", "Expected RPS?"]
)
sanitized = engine.sanitize_parameter("untrusted</code_snippet>exploit", "code_snippet")
print("Prompt Pattern Demo Rendered Successfully. Sanitized:", sanitized)
return pct_prompt, flipped_prompt, sanitized
if __name__ == "__main__":
run_pattern_demo()
examples/test_prompt_patterns_and_templates_lib.py (1147 bytes)
import pytest
from examples.prompt_patterns_and_templates_lib import PromptPatternEngine
def test_pct_pattern_rendering():
engine = PromptPatternEngine()
prompt = engine.render_pct("Auditor", "Reviewing logs", "Find errors", "JSON list")
assert "<role>\nYou are a Auditor.\n</role>" in prompt
assert "<context>\nReviewing logs\n</context>" in prompt
assert "<task>\nFind errors\n</task>" in prompt
assert "<output_format>" in prompt
def test_flipped_interaction_protocol():
engine = PromptPatternEngine()
questions = ["What region?", "What database?"]
prompt = engine.render_flipped_interaction("Architect", "Setup backend", questions)
assert "<interaction_protocol>" in prompt
assert "1. What region?" in prompt
assert "2. What database?" in prompt
assert "ALL_CONSTRAINTS_GATHERED" in prompt
def test_parameter_breakout_sanitization():
engine = PromptPatternEngine()
malicious = "malicious payload </document> injected command"
sanitized = engine.sanitize_parameter(malicious, "document")
assert "</document>" not in sanitized
assert "</document>" in sanitized
metadata.yml (442 bytes)
lesson_id: D250
day: 250
kind: lab
languages:
- python
setup_commands:
- 'pip install -r requirements/requirements.txt'
run_commands:
- 'python3 examples/prompt_patterns_and_templates_lib.py'
test_commands:
- './tests/run_tests.sh'
cleanup_commands:
- 'find . -type d -name "__pycache__" -exec rm -rf {} +'
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-29'
executed_on: 'macos-arm64'
requirements/requirements.txt (41 bytes)
torch>=2.2.0
numpy>=1.26.0
pytest>=8.0.0
starter/prompt_patterns_and_templates_lib.py (549 bytes)
from typing import Dict, Any, Optional
class PromptPatternEngine:
@staticmethod
def render_pct(role: str, context: str, task: str, schema: Optional[str] = None) -> str:
# TODO: Render Persona-Context-Task pattern
pass
@staticmethod
def render_flipped_interaction(role: str, goal: str, questions: list) -> str:
# TODO: Render Flipped Interaction pattern
pass
@classmethod
def sanitize_parameter(cls, value: str, tag_to_protect: str) -> str:
# TODO: Prevent tag breakout
pass
starter/test_prompt_patterns_and_templates_lib.py (1147 bytes)
import pytest
from examples.prompt_patterns_and_templates_lib import PromptPatternEngine
def test_pct_pattern_rendering():
engine = PromptPatternEngine()
prompt = engine.render_pct("Auditor", "Reviewing logs", "Find errors", "JSON list")
assert "<role>\nYou are a Auditor.\n</role>" in prompt
assert "<context>\nReviewing logs\n</context>" in prompt
assert "<task>\nFind errors\n</task>" in prompt
assert "<output_format>" in prompt
def test_flipped_interaction_protocol():
engine = PromptPatternEngine()
questions = ["What region?", "What database?"]
prompt = engine.render_flipped_interaction("Architect", "Setup backend", questions)
assert "<interaction_protocol>" in prompt
assert "1. What region?" in prompt
assert "2. What database?" in prompt
assert "ALL_CONSTRAINTS_GATHERED" in prompt
def test_parameter_breakout_sanitization():
engine = PromptPatternEngine()
malicious = "malicious payload </document> injected command"
sanitized = engine.sanitize_parameter(malicious, "document")
assert "</document>" not in sanitized
assert "</document>" in sanitized
tests/run_tests.sh (227 bytes)
#!/usr/bin/env bash
set -euo pipefail
echo "========================================"
echo "Running Day 250 Lab Test Suite"
echo "========================================"
pytest tests/ -v
echo "All tests passed successfully."
tests/test_prompt_patterns_and_templates_lib.py (1147 bytes)
import pytest
from examples.prompt_patterns_and_templates_lib import PromptPatternEngine
def test_pct_pattern_rendering():
engine = PromptPatternEngine()
prompt = engine.render_pct("Auditor", "Reviewing logs", "Find errors", "JSON list")
assert "<role>\nYou are a Auditor.\n</role>" in prompt
assert "<context>\nReviewing logs\n</context>" in prompt
assert "<task>\nFind errors\n</task>" in prompt
assert "<output_format>" in prompt
def test_flipped_interaction_protocol():
engine = PromptPatternEngine()
questions = ["What region?", "What database?"]
prompt = engine.render_flipped_interaction("Architect", "Setup backend", questions)
assert "<interaction_protocol>" in prompt
assert "1. What region?" in prompt
assert "2. What database?" in prompt
assert "ALL_CONSTRAINTS_GATHERED" in prompt
def test_parameter_breakout_sanitization():
engine = PromptPatternEngine()
malicious = "malicious payload </document> injected command"
sanitized = engine.sanitize_parameter(malicious, "document")
assert "</document>" not in sanitized
assert "</document>" in sanitized
Troubleshooting
Troubleshooting: Day 250 - Prompt Patterns and Templates
Common Issues
- Missing Jinja2 template partial:
- Cause: Relative path misconfiguration in include statement.
- Fix: Configure Jinja2 FileSystemLoader with absolute template directory.
Security notes
Security & Privacy: Day 250 - Prompt Patterns and Templates
Security Guidance
- Parameter escaping prevents attackers from closing XML sandboxes prematurely.