The Instruction Hierarchy pattern structures prompts with explicit priority levels, ensuring model responses respect higher-priority instructions over lower-priority ones. This approach improves reliability, reduces prompt injection vulnerabilities, and creates more predictable model behavior by establishing clear instruction precedence.
Priority levels
System: Developer instructions (highest priority)
Task: User request (medium priority)
Context: Retrieved content (lower priority)
Output: Model response (lowest priority)
Key principles
System prompts override all other instructions
Task-level instructions take precedence over context
Explicitly mark instruction boundaries
Use separators to distinguish instruction layers
Validate that outputs respect hierarchy
Benefits
Improved security against prompt injection
More predictable model behavior
Clearer debugging of instruction conflicts
Better separation of concerns
Build This Pattern
Copy this prompt and paste it into Claude Code, OpenCode, Codex, or Cursor to implement this pattern.
Build me a prompt system with hierarchical instruction levels. Architecture: implement a prompt composer with four priority levels as separate data structures with metadata. Level 1 (System) for immutable rules and constraints, Level 2 (Task) for specific task instructions, Level 3 (Context) for background information, Level 4 (Output) for format and style requirements. Each level has a priority weight and an optional override policy. The composer merges levels into a final prompt, with higher-priority content taking precedence on conflict. Render the final prompt with visual level markers. Include a conflict detection module that scans for overlapping or contradictory instructions across levels. Error handling: on conflict detection, warn the user with the conflicting instructions and which level takes priority. Handle malformed level definitions by skipping with a warning. Edge cases: support levels with no content (empty level). Handle nested priorities within a single level. Support selectively disabling levels at runtime. Best practices: make level labels, priorities, and markers customizable. Store level definitions as structured objects. Log the composed prompt level breakdown. Testing: unit test conflict detection with various overlapping instructions. Test priority ordering when multiple levels address the same topic. Verify visual rendering produces correct markers. TypeScript.