Course
AI · Module 02: Production Prompt EngineeringTutorial 4 of 21
AI Course·~1.5 hrs

2.1 System Prompts, Role Hierarchy & Instruction Design

Replace fragile 'Act as a genius' prompt folklore with engineering discipline: master the System/Developer/User instruction hierarchy, the 5-Block System Spec, XML structuring, and prompt versioning.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Prompt Engineering Is Interface Design, Not "Magic Spells"

Social media ruined the reputation of prompt engineering by framing it as magic incantations ("Take a deep breath, you are a 200-IQ world-class wizard, I will tip $200..."). In production software engineering, a System Prompt is an executable API specification written in unambiguous natural language.

Every modern frontier model (OpenAI GPT-4o / o-series, Anthropic Claude 4, Google Gemini 2.5) is post-trained via Instruction Hierarchy alignment to assign strict privilege levels to different message roles:

TRUST & INSTRUCTION AUTHORITY HIERARCHY1. SYSTEM / DEVELOPER (HIGHEST)2. AUTHENTICATED USER MESSAGE3. UNTRUSTED DATA (RAG / WEB / EMAILS = ZERO AUTHORITY)5-BLOCK PRODUCTION SYSTEM PROMPT SPEC01 Role & Objective → Exact job + success criteria02 Hard Guardrails → Never invent facts; abstain rule03 Output Contract → JSON schema / tone / max length04 Few-Shot Examples → 2–3 tricky edge-case pairs05 Delimited Context → <docs>...</docs> + User task
Figure: Lower-trust messages can never override higher-trust constraints when roles and delimiters are cleanly separated.
  1. system / developer Role (Root Privilege): Written exclusively by your backend server. Defines immutable identity, tool policies, safety boundaries, and output schemas.
  2. user Role (Authenticated Caller): Expresses the end-user's goal within the boundaries allowed by system.
  3. Untrusted Data (tool results, RAG docs, scraped HTML, emails): Zero instruction authority — must be wrapped in explicit data delimiters (<retrieved_doc>...</retrieved_doc>) so the model never confuses external text with commands.

OpenAI developer vs system Note: In newer OpenAI reasoning models (o3, o4-mini, Responses API instructions), the system role was renamed developer to reflect its exact place in the privilege hierarchy (platform > developer > user > tool). Both Claude (system="...") and Gemini (system_instruction="...") expose dedicated top-level parameters rather than mixing system instructions into messages[0].


2. The 5-Block Production System Prompt Architecture

Whenever an AI feature behaves unpredictably in production, 90% of the time its system prompt is a wall of contradictory prose edited by five teammates over six months. Structure every production prompt into five clean, XML-tagged sections:

XML
<role_and_objective>
You are BigOSlate's SQL Query Reviewer. Your sole job is to inspect a PostgreSQL query
and identify missing indexes, non-sargable predicates, or N+1 risks.
</role_and_objective>

<hard_constraints>
- Base findings strictly on the provided <schema> and <query>.
- Never invent table or column names not present in <schema>.
- If <query> is already optimal, return issues: [] — do NOT invent nitpicks.
</hard_constraints>

<output_contract>
Respond with valid JSON matching:
{"is_optimal": boolean, "issues": [{"line": int, "problem": str, "fix_sql": str}]}
</output_contract>

<examples>
Input: SELECT * FROM users WHERE LOWER(email) = 'a@b.com';
Output: {"is_optimal": false, "issues": [{"line": 1, "problem": "LOWER(email) bypasses B-Tree index on email.", "fix_sql": "CREATE INDEX idx_users_lower_email ON users (LOWER(email));"}]}
</examples>

Why XML Tags (<hard_constraints>, <schema>) Work So Well

Models like Claude, Gemini, and GPT are heavily trained on XML/HTML-like boundaries. Wrapping distinct sections in descriptive tags (<customer_profile>, <refund_policy>, <output_contract>) eliminates structural ambiguity far better than Markdown # headings when user inputs themselves contain Markdown!


3. Four High-Leverage Instruction Design Rules

Rule 1: Prefer Positive Actionable Rules Over "Pink Elephant" Negations

Telling an LLM "Don't mention competitors, don't apologize, don't write long paragraphs" activates those exact concepts in attention weights — and leaves the model guessing what to do instead. Pair every prohibition with a concrete positive action:

  • Weak: "Do not guess if the refund window isn't mentioned."
  • Strong: "If the exact refund window is absent from <policy>, respond exclusively with: 'Please contact billing@company.com for plan-specific refund eligibility.'"

Rule 2: Eliminate Vague Adjectives — Quantify Everything!

Words like "brief", "concise", "professional", or "high priority" mean completely different things across model snapshots. Replace adjectives with testable rubrics:

  • Instead of "Write a brief summary" → "Write at most 3 bullet points, each under 18 words, starting with an action verb."
  • Instead of "Flag urgent bugs" → "Classify as P0 if and only if checkout, login, or data integrity is failing for >1 user."

Rule 3: Give the Model an Explicit "Escape Hatch"

Most hallucinations happen because the prompt corners the model into answering questions its context cannot support. Always define a deterministic fallback state ("status": "NEEDS_CLARIFICATION" or "answer": null) for ambiguous, out-of-scope, or missing-context inputs.

Rule 4: Version Prompts Like Source Code (Never Hardcode Inline Strings!)

Changing 1 sentence in a prompt can improve edge case A by +20% while silently breaking edge case B by -15%. Store prompts as versioned .yaml or .py specs in Git, pin exact dated model snapshots (gpt-4o-2024-11-20 or claude-sonnet-4-20250514 instead of floating aliases in critical paths), and gate every prompt PR behind an automated eval suite (Module 07).


4. Wire-Level Trace: Refactoring a Fragile Prompt Into a Production Spec

Click Next to watch how vague instructions fail on edge cases — and how the 5-Block Spec fixes every ambiguity:

Tracing Fragile Prose vs. Structured 5-Block System Spec
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Vague Prompt Hits Uncovered Question)
Wire Telemetry:in=42 tokout=78 tokcost=$0.00089
1→# ❌ v0 Fragile Prompt:
2→"Be a helpful support bot. Keep it short and dont make stuff up."
3# ✅ v1 Production 5-Block Spec:
4system = ROLE + CONSTRAINTS + ESCAPE_HATCH + OUTPUT_SCHEMA
5user = f"<policy>{policy_doc}</policy>\n<question>{q}</question>"
User Question (Not in Knowledge Base)
"Do you offer HIPAA BAA agreements on the $19 Starter plan?"
v0 Model FailureHALLUCINATED POLICY
"Yes! While our Starter plan includes standard encryption, you can request a HIPAA BAA add-on by emailing support..."
What's Happening: 'Be helpful' conflicted with 'dont make stuff up', and with no explicit escape hatch or grounded <policy> block, helpfulness won — creating legal liability!

5. Production SDK Code: Clean Role Separation Across Providers

Notice how none of the three major SDKs stuff system instructions inside the user message — each provides a dedicated high-authority channel:

SDK:
from openai import OpenAI

client = OpenAI()

SYSTEM_SPEC = """<role>You are a senior PostgreSQL code reviewer.</role>
<rules>
1. Cite exact SQL clauses from <query>.
2. Max 3 bullet points, each <= 20 words.
3. If no performance bugs exist, reply exactly: LGTM
</rules>"""

resp = client.responses.create(
  model="gpt-4o-mini",
  temperature=0.0,
  instructions=SYSTEM_SPEC,  # Dedicated developer/system authority channel!
  input="<query>SELECT id, email FROM users WHERE email = 'a@b.com' LIMIT 1;</query>",
)
print(resp.output_text)

6. What Breaks in Production (War Stories)

  1. Contradictory Committee Prompts: Rule #2 says "Never exceed 40 words", while Rule #19 (added 3 months later) says "Always include a step-by-step code example and 3 edge cases." Contradictory rules make output wildly unstable across slight input phrasing changes. Audit prompts quarterly and delete dead rules!
  2. Floating Model Aliases Breaking Formatting Overnight: Pointing production traffic to an unpinned alias when a provider updates instruction-following strictness can suddenly wrap responses in Markdown json code fences where your parser expected raw JSON braces. Pin dated model IDs and pair with Strict Structured Outputs (Lesson 3.1).
  3. Putting Dynamic User Data Inside system: Injecting f"You are assisting {user_bio}" directly into the system channel both busts KV prefix caching AND grants untrusted user_bio text root system-level authority! Keep untrusted user profile fields inside XML tags in the user turn.

Module 2.1 Mastery Check — System Prompts & Role Hierarchy

Q1.In modern Instruction-Hierarchy-aligned LLMs, which rank order reflects true trust authority from HIGHEST to LOWEST?
Q2.Why is injecting `user_submitted_bio` directly into the `system` prompt dangerous?
Q3.Which instruction is better engineered for consistent production behavior?
Q4.Why are XML tags (`<policy>...</policy>`, `<ticket>...</ticket>`) preferred over `###` Markdown headers for delimiting user inputs?

Keep Exploring: Related Lessons & Tools

All Courses →