LLMs and Generative AI › Prompt Engineering › Day 246
Hands-on lab — Day 246: Prompting Fundamentals
- ← Back to the Day 246 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-246-prompting-fundamentals/
Commands
Setup
pip install -r requirements/requirements.txt Run
python3 examples/prompting_fundamentals_lib.py Test
./tests/run_tests.sh File tree
conftest.py examples/prompting_fundamentals_lib.py examples/test_prompting_fundamentals_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/prompting_fundamentals_lib.py starter/test_prompting_fundamentals_lib.py tests/run_tests.sh tests/test_prompting_fundamentals_lib.py troubleshooting.md
Lab README
Lab: Day 246 -- Prompting Fundamentals
Lesson
Day number: 246 of 365. Course: Course06-SS01 (LLMs and Generative AI - Working with LLMs). Topic: Prompting Fundamentals, 6-Part Anatomy, and Delimiter Sandboxing.
Purpose
Build and test a modular, template-driven prompt compiler and validation engine in Python. Construct structured production prompts, enforce XML delimiter sandboxing, and validate recency ordering.
Learning objectives
- Formulate prompts using the 6 canonical architectural components.
- Enforce XML delimiter sandboxing to isolate untrusted input payloads.
- Apply recency positioning for output formatting and constraints.
- Implement programmatic validation assertions for prompt structures.
Prerequisites
- Day 245 (Benchmarking Models Yourself).
- 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 manipulation tools are free and open source.
Installation
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt
File structure
starter/prompting_fundamentals_lib.py: Student scaffold file.examples/prompting_fundamentals_lib.py: Complete reference implementation.tests/test_prompting_fundamentals_lib.py: Pytest automated validation suite.expected-output/: Verified output logs and baseline values.
How to run
Execute the reference demonstration script:
python3 examples/prompting_fundamentals_lib.py
What the commands do
- Compiles modular prompts with XML delimiter tags.
- Verifies primacy and recency positioning.
- Runs unit test assertions.
Expected output
Prompt Demo Compiled Successfully.
Validation steps
- Verify
compilegenerates matching opening and closing XML tags. - Confirm
<role_and_task>appears at index 0 (Primacy). - Confirm
<output_format>appears at the end (Recency). - 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
- Missing tag closure: Ensure every tag opened with
<tag>has a corresponding</tag>.
Security notes
All prompt compilation runs locally in memory.
Extension exercises
- Implement a prompt linter that flags negative constraint keywords.
- Build an automated prompt caching token boundary calculator.
Navigation
- Lesson title: Prompting Fundamentals
- Day number: 246 of 365
- Lesson article: https://ai-roadmap-365.github.io/day-246-prompting-fundamentals
- 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-246-prompting-fundamentalswhen the site is running.
Expected output
FIELDS.md
# Expected Output Fields: Day 246
- `Prompt Demo`: Status of prompt compilation and delimiter encapsulation.
examples-run.txt
Prompt Demo Compiled Successfully.
measured-values.txt
Prompt Demo: Success
Primacy Tag: <role_and_task>
Recency Tag: <output_format>
starter-run.txt
Starter scaffold executed. Ready for student implementation.
test-run.txt
============================= test session starts ==============================
collected 3 items
tests/test_prompting_fundamentals_lib.py::test_prompt_compilation_structure PASSED [ 33%]
tests/test_prompting_fundamentals_lib.py::test_recency_ordering PASSED [ 66%]
tests/test_prompting_fundamentals_lib.py::test_empty_steps_and_constraints 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/prompting_fundamentals_lib.py (2121 bytes)
from typing import List, Optional
class PromptCompiler:
def __init__(self, role: str, task: str):
self.role = role.strip()
self.task = task.strip()
self.steps: List[str] = []
self.constraints: List[str] = []
self.output_schema: Optional[str] = None
def add_step(self, step: str) -> "PromptCompiler":
self.steps.append(step.strip())
return self
def add_constraint(self, constraint: str) -> "PromptCompiler":
self.constraints.append(constraint.strip())
return self
def set_output_schema(self, schema: str) -> "PromptCompiler":
self.output_schema = schema.strip()
return self
def compile(self, input_payload: str, tag: str = "input_data") -> str:
parts = []
parts.append(f"<role_and_task>\nRole: {self.role}\nTask: {self.task}\n</role_and_task>")
parts.append(f"<{tag}>\n{input_payload.strip()}\n</{tag}>")
if self.steps:
steps_str = "\n".join([f"{i+1}. {s}" for i, s in enumerate(self.steps)])
parts.append(f"<execution_steps>\n{steps_str}\n</execution_steps>")
if self.constraints:
c_str = "\n".join([f"- {c}" for c in self.constraints])
parts.append(f"<constraints>\n{c_str}\n</constraints>")
if self.output_schema:
parts.append(f"<output_format>\n{self.output_schema}\nOutput raw data only.\n</output_format>")
return "\n\n".join(parts)
def run_prompt_demo():
compiler = PromptCompiler(
role="Senior Code Reviewer",
task="Audit database query for security vulnerabilities"
)
compiler.add_step("Identify injection vulnerabilities")
compiler.add_step("Propose parameterized query fix")
compiler.add_constraint("Focus strictly on SQL security")
compiler.set_output_schema("Return JSON array with keys: ['vulnerability', 'fix']")
prompt = compiler.compile("SELECT * FROM users WHERE id = '" + "1' OR '1'='1", tag="code_snippet")
print("Prompt Demo Compiled Successfully.")
return prompt
if __name__ == "__main__":
run_prompt_demo()
examples/test_prompting_fundamentals_lib.py (1448 bytes)
import pytest
from examples.prompting_fundamentals_lib import PromptCompiler
def test_prompt_compilation_structure():
compiler = PromptCompiler(role="Auditor", task="Review code")
compiler.add_step("Check auth")
compiler.add_constraint("Output concisely")
compiler.set_output_schema("JSON object")
prompt = compiler.compile("print('hello')", tag="code")
assert "<role_and_task>" in prompt
assert "Role: Auditor" in prompt
assert "<code>" in prompt
assert "print('hello')" in prompt
assert "</code>" in prompt
assert "<execution_steps>" in prompt
assert "1. Check auth" in prompt
assert "<constraints>" in prompt
assert "- Output concisely" in prompt
assert "<output_format>" in prompt
def test_recency_ordering():
compiler = PromptCompiler(role="Writer", task="Summarize")
compiler.set_output_schema("Markdown list")
prompt = compiler.compile("Document body", tag="doc")
# Verify <role_and_task> comes first and <output_format> comes last
idx_role = prompt.find("<role_and_task>")
idx_doc = prompt.find("<doc>")
idx_out = prompt.find("<output_format>")
assert idx_role < idx_doc < idx_out
def test_empty_steps_and_constraints():
compiler = PromptCompiler(role="Bot", task="Echo")
prompt = compiler.compile("Input text")
assert "<execution_steps>" not in prompt
assert "<constraints>" not in prompt
assert "<input_data>" in prompt
metadata.yml (435 bytes)
lesson_id: D246
day: 246
kind: lab
languages:
- python
setup_commands:
- 'pip install -r requirements/requirements.txt'
run_commands:
- 'python3 examples/prompting_fundamentals_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/prompting_fundamentals_lib.py (738 bytes)
from typing import List, Optional
class PromptCompiler:
def __init__(self, role: str, task: str):
self.role = role
self.task = task
self.steps: List[str] = []
self.constraints: List[str] = []
self.output_schema: Optional[str] = None
def add_step(self, step: str) -> "PromptCompiler":
# TODO: Add execution step
pass
def add_constraint(self, constraint: str) -> "PromptCompiler":
# TODO: Add constraint
pass
def set_output_schema(self, schema: str) -> "PromptCompiler":
# TODO: Set schema
pass
def compile(self, input_payload: str, tag: str = "input_data") -> str:
# TODO: Return full compiled XML prompt
pass
starter/test_prompting_fundamentals_lib.py (1448 bytes)
import pytest
from examples.prompting_fundamentals_lib import PromptCompiler
def test_prompt_compilation_structure():
compiler = PromptCompiler(role="Auditor", task="Review code")
compiler.add_step("Check auth")
compiler.add_constraint("Output concisely")
compiler.set_output_schema("JSON object")
prompt = compiler.compile("print('hello')", tag="code")
assert "<role_and_task>" in prompt
assert "Role: Auditor" in prompt
assert "<code>" in prompt
assert "print('hello')" in prompt
assert "</code>" in prompt
assert "<execution_steps>" in prompt
assert "1. Check auth" in prompt
assert "<constraints>" in prompt
assert "- Output concisely" in prompt
assert "<output_format>" in prompt
def test_recency_ordering():
compiler = PromptCompiler(role="Writer", task="Summarize")
compiler.set_output_schema("Markdown list")
prompt = compiler.compile("Document body", tag="doc")
# Verify <role_and_task> comes first and <output_format> comes last
idx_role = prompt.find("<role_and_task>")
idx_doc = prompt.find("<doc>")
idx_out = prompt.find("<output_format>")
assert idx_role < idx_doc < idx_out
def test_empty_steps_and_constraints():
compiler = PromptCompiler(role="Bot", task="Echo")
prompt = compiler.compile("Input text")
assert "<execution_steps>" not in prompt
assert "<constraints>" not in prompt
assert "<input_data>" in prompt
tests/run_tests.sh (227 bytes)
#!/usr/bin/env bash
set -euo pipefail
echo "========================================"
echo "Running Day 246 Lab Test Suite"
echo "========================================"
pytest tests/ -v
echo "All tests passed successfully."
tests/test_prompting_fundamentals_lib.py (1448 bytes)
import pytest
from examples.prompting_fundamentals_lib import PromptCompiler
def test_prompt_compilation_structure():
compiler = PromptCompiler(role="Auditor", task="Review code")
compiler.add_step("Check auth")
compiler.add_constraint("Output concisely")
compiler.set_output_schema("JSON object")
prompt = compiler.compile("print('hello')", tag="code")
assert "<role_and_task>" in prompt
assert "Role: Auditor" in prompt
assert "<code>" in prompt
assert "print('hello')" in prompt
assert "</code>" in prompt
assert "<execution_steps>" in prompt
assert "1. Check auth" in prompt
assert "<constraints>" in prompt
assert "- Output concisely" in prompt
assert "<output_format>" in prompt
def test_recency_ordering():
compiler = PromptCompiler(role="Writer", task="Summarize")
compiler.set_output_schema("Markdown list")
prompt = compiler.compile("Document body", tag="doc")
# Verify <role_and_task> comes first and <output_format> comes last
idx_role = prompt.find("<role_and_task>")
idx_doc = prompt.find("<doc>")
idx_out = prompt.find("<output_format>")
assert idx_role < idx_doc < idx_out
def test_empty_steps_and_constraints():
compiler = PromptCompiler(role="Bot", task="Echo")
prompt = compiler.compile("Input text")
assert "<execution_steps>" not in prompt
assert "<constraints>" not in prompt
assert "<input_data>" in prompt
Troubleshooting
Troubleshooting: Day 246 - Prompting Fundamentals
Common Issues
- Unclosed XML tags:
- Cause: Manually formatting strings without f-string closing tags.
- Fix: Use template helper functions that automatically close tags.
Security notes
Security & Privacy: Day 246 - Prompting Fundamentals
Security Guidance
- Delimiter sandboxing prevents untrusted payloads from executing as instructions.