Back to Prompting Recipes

Instruction Hierarchy

StructureSecurity

Structure

Structure prompts with clear priority levels to prevent conflicts and improve model compliance.

Summary

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
Code View

Instruction Hierarchy Implementation

// Instruction Hierarchy recipe using OpenAI
// Install: bun add openai

import OpenAI from "openai";

async function main() {
  const input = "Add your prompt here.";
  const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
  const system = "You are a senior AI engineer and technical writer. Use the prompting technique to answer the request clearly and precisely. Recipe: Instruction Hierarchy. Description: Structure prompts with clear priority levels to prevent conflicts and improve model compliance. Focus: Structure Provide actionable, implementation-ready guidance.";
  const user = `Request: ${input}`;

  const openaiResponse = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      { role: "system", content: system },
      { role: "user", content: user },
    ],
  });

  const openaiText = openaiResponse.choices[0]?.message?.content?.trim() ?? "";

  console.log(openaiText);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});