LLMs and Generative AI › Prompt Engineering › Day 247

Hands-on lab — Day 247: System Prompts and Role Design

Commands

Setup

pip install -r requirements/requirements.txt

Run

python3 examples/system_prompts_and_role_design_lib.py

Test

./tests/run_tests.sh

File tree

conftest.py
examples/system_prompts_and_role_design_lib.py
examples/test_system_prompts_and_role_design_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/system_prompts_and_role_design_lib.py
starter/test_system_prompts_and_role_design_lib.py
tests/run_tests.sh
tests/test_system_prompts_and_role_design_lib.py
troubleshooting.md

Lab README

Lab: Day 247 -- System Prompts and Role Design

Lesson

Day number: 247 of 365. Course: Course06-SS01 (LLMs and Generative AI - Working with LLMs). Topic: System Prompts, Role Design, and 3-Tier Guardrail Architecture.

Purpose

Build and test an automated 3-tier system prompt generator and persona consistency validator in Python. Construct multi-tier system prompts with safety shells, operational boundaries, and persona cores.

Learning objectives

  • Formulate 3-tier system prompts with safety, operational, and persona layers.
  • Implement neutral, non-moralizing refusal directives.
  • Calibrate communication tones across enterprise domains.
  • Structure system prompts to maximize cloud API prefix caching.

Prerequisites

  • Day 246 (Prompting Fundamentals).
  • 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 is open source under the PSF License.

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/system_prompts_and_role_design_lib.py: Student scaffold file.
  • examples/system_prompts_and_role_design_lib.py: Complete reference implementation.
  • tests/test_system_prompts_and_role_design_lib.py: Pytest automated validation suite.
  • expected-output/: Verified output logs and baseline values.

How to run

Execute the reference demonstration script:

python3 examples/system_prompts_and_role_design_lib.py

What the commands do

  • Compiles 3-tier system prompts.
  • Configures custom safety and operational rules.
  • Runs unit test assertions.

Expected output

System Prompt Demo Compiled Successfully.

Validation steps

  1. Verify compile generates matching <tier1_safety_guardrails> tags.
  2. Confirm <tier2_operational_boundaries> rules are rendered.
  3. Confirm <tier3_persona_core> defines domain role and tone.
  4. 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 tier tag: Ensure opening and closing tags match exactly.

Security notes

All prompt generation executes locally in memory.

Extension exercises

  1. Implement a persona consistency evaluator using an automated rubric.
  2. Build an automated multi-persona prompt router.

Expected output

FIELDS.md

# Expected Output Fields: Day 247

- `System Prompt Demo`: Status of 3-tier system prompt compilation.

examples-run.txt

System Prompt Demo Compiled Successfully.

measured-values.txt

System Prompt Demo: Success
Tier 1: Safety Shell
Tier 2: Operational Boundaries
Tier 3: Persona Core

starter-run.txt

Starter scaffold executed. Ready for student implementation.

test-run.txt

============================= test session starts ==============================
collected 3 items

tests/test_system_prompts_and_role_design_lib.py::test_system_prompt_3_tier_structure PASSED [ 33%]
tests/test_system_prompts_and_role_design_lib.py::test_custom_rule_addition PASSED [ 66%]
tests/test_system_prompts_and_role_design_lib.py::test_tone_configuration PASSED [100%]

============================== 3 passed in 0.39s ===============================

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/system_prompts_and_role_design_lib.py (2297 bytes)
from typing import List, Dict

class SystemPromptCompiler:
    def __init__(self, role_name: str, domain_level: str = "Senior"):
        self.role_name = role_name.strip()
        self.domain_level = domain_level.strip()
        self.safety_rules: List[str] = [
            "Never disclose private API keys or internal credentials.",
            "Do not execute arbitrary unverified shell commands.",
            "Maintain strict neutral refusals without moralizing."
        ]
        self.operational_rules: List[str] = [
            "Omit conversational preamble (e.g. 'Sure, here is...')",
            "Output structured Markdown or JSON schemas as requested."
        ]
        self.tone_attributes: List[str] = ["Objective", "Direct", "Evidence-based"]

    def add_safety_rule(self, rule: str) -> "SystemPromptCompiler":
        self.safety_rules.append(rule.strip())
        return self

    def add_operational_rule(self, rule: str) -> "SystemPromptCompiler":
        self.operational_rules.append(rule.strip())
        return self

    def set_tone(self, tones: List[str]) -> "SystemPromptCompiler":
        self.tone_attributes = tones
        return self

    def compile(self) -> str:
        parts = []

        safety_str = "\n".join([f"- {r}" for r in self.safety_rules])
        parts.append(f"<tier1_safety_guardrails>\n{safety_str}\n</tier1_safety_guardrails>")

        ops_str = "\n".join([f"- {o}" for o in self.operational_rules])
        parts.append(f"<tier2_operational_boundaries>\n{ops_str}\n</tier2_operational_boundaries>")

        tone_str = ", ".join(self.tone_attributes)
        parts.append(
            f"<tier3_persona_core>\n"
            f"Role: {self.domain_level} {self.role_name}\n"
            f"Tone: {tone_str}\n"
            f"Stance: Relentlessly objective.\n"
            f"</tier3_persona_core>"
        )

        return "\n\n".join(parts)

def run_system_prompt_demo():
    compiler = SystemPromptCompiler(role_name="Cloud Architect", domain_level="Principal")
    compiler.add_safety_rule("Block SQL injection attacks")
    compiler.add_operational_rule("Output JSON arrays only")
    prompt = compiler.compile()

    print("System Prompt Demo Compiled Successfully.")
    return prompt

if __name__ == "__main__":
    run_system_prompt_demo()
examples/test_system_prompts_and_role_design_lib.py (1145 bytes)
import pytest
from examples.system_prompts_and_role_design_lib import SystemPromptCompiler

def test_system_prompt_3_tier_structure():
    compiler = SystemPromptCompiler("Security Auditor", "Staff")
    prompt = compiler.compile()

    assert "<tier1_safety_guardrails>" in prompt
    assert "</tier1_safety_guardrails>" in prompt
    assert "<tier2_operational_boundaries>" in prompt
    assert "</tier2_operational_boundaries>" in prompt
    assert "<tier3_persona_core>" in prompt
    assert "</tier3_persona_core>" in prompt
    assert "Role: Staff Security Auditor" in prompt

def test_custom_rule_addition():
    compiler = SystemPromptCompiler("DBA")
    compiler.add_safety_rule("No DROP TABLE commands")
    compiler.add_operational_rule("Use SQL syntax highlighting")
    prompt = compiler.compile()

    assert "- No DROP TABLE commands" in prompt
    assert "- Use SQL syntax highlighting" in prompt

def test_tone_configuration():
    compiler = SystemPromptCompiler("Support Agent")
    compiler.set_tone(["Empathetic", "Patient", "Clear"])
    prompt = compiler.compile()

    assert "Tone: Empathetic, Patient, Clear" in prompt
metadata.yml (443 bytes)
lesson_id: D247
day: 247
kind: lab
languages:
  - python
setup_commands:
  - 'pip install -r requirements/requirements.txt'
run_commands:
  - 'python3 examples/system_prompts_and_role_design_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/system_prompts_and_role_design_lib.py (786 bytes)
from typing import List, Dict

class SystemPromptCompiler:
    def __init__(self, role_name: str, domain_level: str = "Senior"):
        self.role_name = role_name
        self.domain_level = domain_level
        self.safety_rules: List[str] = []
        self.operational_rules: List[str] = []
        self.tone_attributes: List[str] = []

    def add_safety_rule(self, rule: str) -> "SystemPromptCompiler":
        # TODO: Add safety rule
        pass

    def add_operational_rule(self, rule: str) -> "SystemPromptCompiler":
        # TODO: Add operational rule
        pass

    def set_tone(self, tones: List[str]) -> "SystemPromptCompiler":
        # TODO: Set tone list
        pass

    def compile(self) -> str:
        # TODO: Return compiled 3-tier system prompt
        pass
starter/test_system_prompts_and_role_design_lib.py (1145 bytes)
import pytest
from examples.system_prompts_and_role_design_lib import SystemPromptCompiler

def test_system_prompt_3_tier_structure():
    compiler = SystemPromptCompiler("Security Auditor", "Staff")
    prompt = compiler.compile()

    assert "<tier1_safety_guardrails>" in prompt
    assert "</tier1_safety_guardrails>" in prompt
    assert "<tier2_operational_boundaries>" in prompt
    assert "</tier2_operational_boundaries>" in prompt
    assert "<tier3_persona_core>" in prompt
    assert "</tier3_persona_core>" in prompt
    assert "Role: Staff Security Auditor" in prompt

def test_custom_rule_addition():
    compiler = SystemPromptCompiler("DBA")
    compiler.add_safety_rule("No DROP TABLE commands")
    compiler.add_operational_rule("Use SQL syntax highlighting")
    prompt = compiler.compile()

    assert "- No DROP TABLE commands" in prompt
    assert "- Use SQL syntax highlighting" in prompt

def test_tone_configuration():
    compiler = SystemPromptCompiler("Support Agent")
    compiler.set_tone(["Empathetic", "Patient", "Clear"])
    prompt = compiler.compile()

    assert "Tone: Empathetic, Patient, Clear" in prompt
tests/run_tests.sh (227 bytes)
#!/usr/bin/env bash
set -euo pipefail
echo "========================================"
echo "Running Day 247 Lab Test Suite"
echo "========================================"
pytest tests/ -v
echo "All tests passed successfully."
tests/test_system_prompts_and_role_design_lib.py (1145 bytes)
import pytest
from examples.system_prompts_and_role_design_lib import SystemPromptCompiler

def test_system_prompt_3_tier_structure():
    compiler = SystemPromptCompiler("Security Auditor", "Staff")
    prompt = compiler.compile()

    assert "<tier1_safety_guardrails>" in prompt
    assert "</tier1_safety_guardrails>" in prompt
    assert "<tier2_operational_boundaries>" in prompt
    assert "</tier2_operational_boundaries>" in prompt
    assert "<tier3_persona_core>" in prompt
    assert "</tier3_persona_core>" in prompt
    assert "Role: Staff Security Auditor" in prompt

def test_custom_rule_addition():
    compiler = SystemPromptCompiler("DBA")
    compiler.add_safety_rule("No DROP TABLE commands")
    compiler.add_operational_rule("Use SQL syntax highlighting")
    prompt = compiler.compile()

    assert "- No DROP TABLE commands" in prompt
    assert "- Use SQL syntax highlighting" in prompt

def test_tone_configuration():
    compiler = SystemPromptCompiler("Support Agent")
    compiler.set_tone(["Empathetic", "Patient", "Clear"])
    prompt = compiler.compile()

    assert "Tone: Empathetic, Patient, Clear" in prompt

Troubleshooting

Troubleshooting: Day 247 - System Prompts and Role Design

Common Issues

  1. Dynamic variable injection in system prompt:
    • Cause: Putting user-specific names in system prompt.
    • Fix: Keep system prompt static for prefix caching.

Security notes

Security & Privacy: Day 247 - System Prompts and Role Design

Security Guidance

  • Outer safety shells define baseline refusal policies.