Cybersecurity

Category 1: Foundational Patterns

Python JavaScript Docker LLMs RAG Prompt Engineering Prompt Injection AI Agents Authentication JWT SQL Injection XSS CI/CD REST API Databases SQL MongoDB Java Classification
1,625 words Includes Code
Prompt engineering patterns showing 4 categories (Foundational, Multi-Step, Task-Specific, Quality) with pattern flow diagram from Role through Plan, Generate, Review, to Verify
📌 Key Takeaway

Prompt patterns are reusable templates for common AI tasks. Mastering 15 core patterns covers 90% of real-world use cases. Each pattern includes a purpose, template, beginner example, advanced example, and common mistake to avoid.

You know the basics of prompt engineering. Now it is time to build a pattern library — reusable templates you can apply to any task. This article covers 15 essential patterns organized into four categories, each with a purpose, template, beginner and advanced examples, and the most common mistake.

This is a companion to our Prompt Engineering Complete Tutorial. If you are new to prompting, start there. This article assumes you understand the fundamentals.

Table of Contents


Category 1: Foundational Patterns

These five patterns are the building blocks. Almost every effective prompt uses at least one.

Pattern 1: Role + Task + Context

Purpose: Set expertise level, define the task, and provide background.
Template: "You are a [ROLE]. TASK: [WHAT]. CONTEXT: [BACKGROUND]."
BEGINNER: "You are a Python tutor. Explain list comprehensions to a beginner who knows basic loops."

ADVANCED: "You are a senior security engineer reviewing a Flask API for OWASP Top 10 vulnerabilities. Focus on SQL injection and XSS. Return findings as JSON."
⚠️ COMMON MISTAKE: Vague role like "You are helpful." Be specific: "You are a senior Python developer with 10 years of experience."

Pattern 2: Few-Shot

Purpose: Show examples before the actual task so the model learns the pattern.
Template: "EXAMPLES:\nInput: [E1] → Output: [O1]\nInput: [E2] → Output: [O2]\nNOW: Input: [ACTUAL]"
BEGINNER: "Classify:\n'I love this product' → Positive\n'Terrible service' → Negative\n'It is okay' → ?"

ADVANCED: "Code review severity:\n'Unused import' → LOW\n'Missing validation on user_id' → HIGH\n'SQL injection vulnerability' → CRITICAL\n'No rate limiting on login' → ?"
⚠️ COMMON MISTAKE: Examples that are ambiguous or inconsistent. If example 1 and example 2 use different formats, the model will be confused.

Pattern 3: Zero-Shot

Purpose: Direct task without examples — rely on the model's pre-trained knowledge.
Template: "[Clear instruction about what to do]"
BEGINNER: "Summarize this article in 3 bullet points."

ADVANCED: "Analyze this Python code for performance bottlenecks. For each: location (line number), impact (H/M/L), and optimization suggestion."
⚠️ COMMON MISTAKE: Assuming the model knows your specific context. Zero-shot works for general tasks, but complex or domain-specific tasks need context.

Pattern 4: Structured Output

Purpose: Specify exact output format so results are predictable and parseable.
Template: "Return as [FORMAT]: [FIELD LIST]"
BEGINNER: "Return as a numbered list: 3 benefits of Docker."

ADVANCED: "Return as JSON with keys: {severity, location, description, fix, confidence}. One object per finding. Array of findings."
⚠️ COMMON MISTAKE: Not specifying format leads to unpredictable output. Always say "as a table," "as JSON," or "as bullet points."

Pattern 5: Delimiters

Purpose: Separate instructions from content to prevent confusion.
Template: "Analyze the following:\n--- BEGIN ---\n[CONTENT]\n--- END ---"
BEGINNER: "Summarize:\n---\nThe quick brown fox jumps over the lazy dog.\n---"

ADVANCED: "Review this code for security:\n```\n[CODE]\n```\nIgnore comments. Focus on input validation and SQL injection."
⚠️ COMMON MISTAKE: Without delimiters, the model may confuse your instructions with the content you want analyzed — especially with prompt injection risks.

Category 2: Multi-Step Patterns

These patterns chain multiple steps to produce higher-quality output.

Pattern 6: Critic Pattern

Purpose: Ask the model to evaluate and improve its own output.
Template: "After generating, review for: [CRITERIA]. List issues, then provide corrected version."
BEGINNER: "Write a poem about rain. Then review it for rhyme and rhythm. Fix any issues."

ADVANCED: "Generate a REST API design for user management. Then review for: RESTful compliance, error handling, pagination, authentication. List issues numbered, then provide corrected design."

Pattern 7: Generator → Reviewer

Purpose: Two-step process: create first, then evaluate with specific criteria.
Template: "STEP 1: Create [OUTPUT].\nSTEP 2: Review for [CRITERIA]. Provide final version."
BEGINNER: "Step 1: Write a function to calculate average.\nStep 2: Review for edge cases (empty list, None values) and fix."

ADVANCED: "Step 1: Design a database schema for an e-commerce platform with users, products, orders, and reviews.\nStep 2: Review for normalization (3NF), indexing strategy, and scalability. Provide final schema with SQL CREATE statements."

Pattern 8: Plan → Execute

Purpose: Force the model to plan before acting — prevents incomplete solutions.
Template: "PLAN: List steps.\nEXECUTE: Carry out each step.\nVERIFY: Check against requirements."
BEGINNER: "PLAN: How to clean a messy CSV file.\nEXECUTE: Write Python code for each step.\nVERIFY: Test with sample data."

ADVANCED: "PLAN: Implement JWT authentication with refresh tokens.\nEXECUTE: Write middleware, login/logout routes, token refresh, and tests.\nVERIFY: Check token expiry, refresh flow, CSRF protection, and error handling."

Pattern 9: Extract → Transform → Validate

Purpose: Three-stage data processing pipeline.
Template: "EXTRACT: Pull out [FIELDS].\nTRANSFORM: Convert to [FORMAT].\nVALIDATE: Check [RULES]."
BEGINNER: "EXTRACT: Names from this list.\nTRANSFORM: To uppercase.\nVALIDATE: No empty entries."

ADVANCED: "EXTRACT: PII fields (name, email, phone, SSN) from this log entry.\nTRANSFORM: Replace with redacted format (name → [REDACTED]).\nVALIDATE: All PII removed, no original values in output, format preserved."

Category 3: Task-Specific Patterns

These patterns are optimized for common task types.

Pattern 10: Classification

Purpose: Categorize input into predefined classes.
Template: "Classify into [CATEGORIES].\nInput: [TEXT]\nOutput: category + confidence."
BEGINNER: "Classify as positive, negative, or neutral:\n'I love this product'"

ADVANCED: "Classify this code review comment by type (bug, security, performance, style, docs) and severity (LOW/MEDIUM/HIGH/CRITICAL):\n'Missing rate limiting on login endpoint — allows brute force attacks'"

Pattern 11: Summarization

Purpose: Condense information while preserving key elements.
Template: "Summarize [LENGTH] for [AUDIENCE]. Preserve [KEY ELEMENTS]."
BEGINNER: "Summarize in 3 sentences for a high school student."

ADVANCED: "Summarize this 50-page research paper in 500 words for a data scientist. Preserve: methodology, key findings, limitations, and practical implications. Exclude: related work, proofs, and appendix."

Pattern 12: Comparison

Purpose: Structured side-by-side comparison for decision-making.
Template: "Compare [A] vs [B] for [USE CASE]. Table with: Feature, A, B, Winner."
BEGINNER: "Compare Python vs JavaScript for web development. Use a table."

ADVANCED: "Compare PostgreSQL vs MongoDB for a real-time analytics platform processing 10M events/day. Table columns: scalability, query performance, schema flexibility, ACID compliance, operational cost, ecosystem. Include a recommendation with reasoning."

Pattern 13: Chain Decomposition

Purpose: Break complex tasks into sequential, manageable steps.
Template: "Break into [N] steps:\n1. [STEP 1]\n2. [STEP 2]\nFor each: explanation + example."
BEGINNER: "Break 'deploy to Heroku' into 5 steps. For each: what to do and an example command."

ADVANCED: "Break 'implement CI/CD pipeline' into: linting, unit testing, integration testing, security scanning, building, deploying. For each step: recommended tools, configuration example, and common pitfalls."

Category 4: Quality Patterns

These patterns ensure correctness and completeness.

Pattern 14: Verification

Purpose: Force self-checking of output against specific criteria.
Template: "After generating, verify: [CHECKLIST]. Report any issues found."
BEGINNER: "Write a function to validate email addresses. Then verify: does it handle empty input? Does it return a boolean? Does it work with test@example.com?"

ADVANCED: "Generate a SQL query to find users who logged in in the last 30 days. Then verify: uses indexed column, no N+1 queries, handles NULL last_login, no SQL injection (parameterized), correct date arithmetic."

Pattern 15: Role Rotation

Purpose: Get multiple expert perspectives on the same problem.
Template: "As a [ROLE 1], analyze [ASPECT 1].\nAs a [ROLE 2], analyze [ASPECT 2].\nCombine insights."
BEGINNER: "As a teacher, explain this concept clearly. As a student, what questions would you ask? Address those questions."

ADVANCED: "As a security engineer, review for vulnerabilities. As a performance engineer, review for bottlenecks. As a code reviewer, review for maintainability. Combine all findings into a prioritized list."

Pattern Chaining

The real power comes from combining patterns. Here is how they chain together:

ROLEPLANGENERATEREVIEWVERIFY↻ ITERATE

Example chain for code review:

  1. Role: "You are a senior Python developer"
  2. Delimiters: "Review this code: ```[CODE]```"
  3. Classification: "For each issue, classify as security/performance/style"
  4. Structured Output: "Return as JSON: {type, severity, line, description, fix}"
  5. Verification: "Verify your findings are accurate before presenting"

When to Use Which Pattern

Task TypeRecommended PatternWhy
Domain-specific questionRole + Task + ContextSets expertise level
CategorizationFew-Shot + ClassificationExamples teach the pattern
Code generationPlan → Execute → VerifyForces completeness
API/JSON outputStructured OutputPredictable format
Processing external textDelimitersPrevents instruction confusion
Quality improvementCritic or Generator → ReviewerSelf-evaluation loop
Data processingExtract → Transform → ValidateThree-stage pipeline
Decision-makingComparisonStructured side-by-side
Complex projectChain DecompositionBreaks into manageable steps
Ensuring correctnessVerificationForces self-checking

FAQ

Which pattern should I use most often?
Role + Task + Context is the most universally useful. It sets the foundation for every other pattern. Add Structured Output when you need predictable formats, and Plan → Execute for complex tasks.
Can I combine multiple patterns?
Yes, and you should. A strong prompt often uses 3-4 patterns together: Role + Structured Output + Delimiters + Verification. See the "Pattern Chaining" section above.
When should I use Few-Shot vs Zero-Shot?
Zero-shot works for simple, well-defined tasks. Use Few-Shot when: the output format is unusual, the task is ambiguous, or you need consistent classification. More examples generally improve consistency.
Does the Critic pattern actually improve output?
Research shows that asking models to review their own output can improve quality by 10-30% on complex tasks. The improvement is most noticeable for code, analysis, and multi-step reasoning. For simple tasks, the overhead may not be worth it.

Try These BestWordz Tools

Continue Learning

Try the JSON Formatter

Put what you've learned into practice with this free BestWordz tool.

Open Tool →

💬 Discuss on BestWordz Community

Join the conversation about Python, JavaScript, Docker on the BestWordz Community forum.

Visit Forum →