DEV Community

Phil IPS
Phil IPS

Posted on

Prompt Engineering Masterclass: From Basics to Advanced Techniques

Prompt Engineering Masterclass: From Basics to Advanced Techniques

Master the art of communicating with LLMs — systematic patterns that work across models.

Introduction

Prompt engineering isn't magic — it's structured communication. This guide covers proven patterns from basic to advanced, with templates you can copy-paste.

The Prompt Formula

Every effective prompt has 4 components:

ROLE + CONTEXT + INSTRUCTION + CONSTRAINTS = GOOD OUTPUT
Enter fullscreen mode Exit fullscreen mode

Example:

ROLE: You are a senior Python developer
CONTEXT: Building a REST API for a todo app with FastAPI
INSTRUCTION: Create a POST /todos endpoint with validation
CONSTRAINTS: Use Pydantic models, return 201 on success, 422 on validation error
Enter fullscreen mode Exit fullscreen mode

Level 1: Basic Patterns

1. Zero-Shot (Direct Instruction)

prompt = """Write a Python function to calculate compound interest.
Parameters: principal, rate, years, compounds_per_year
Return: final amount"""
Enter fullscreen mode Exit fullscreen mode

2. Few-Shot (Examples)

prompt = """Convert natural language to SQL.

Examples:
Input: "Show all users from New York"
Output: SELECT * FROM users WHERE city = 'New York';

Input: "Count orders per customer"
Output: SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id;

Input: "Find products under $50 with stock > 10"
Output:"""
Enter fullscreen mode Exit fullscreen mode

3. Chain-of-Thought (Reasoning)

prompt = """Solve this step by step:

Problem: A train leaves NYC at 60 mph. Another leaves LA at 70 mph. Distance is 2800 miles. When do they meet?

Think through:
1. Combined speed = 60 + 70 = 130 mph
2. Time = Distance / Speed = 2800 / 130
3. Time = 21.54 hours
4. They meet after ~21 hours 32 minutes

Answer: 21 hours 32 minutes after departure"""
Enter fullscreen mode Exit fullscreen mode

Level 2: Structured Patterns

4. Persona + Context Pattern

def build_prompt(role, context, task, constraints=None, examples=None):
    parts = [
        f"ROLE: {role}",
        f"CONTEXT: {context}",
        f"TASK: {task}"
    ]
    if constraints:
        parts.append(f"CONSTRAINTS:\n" + "\n".join(f"- {c}" for c in constraints))
    if examples:
        parts.append("EXAMPLES:\n" + "\n\n".join(examples))
    return "\n\n".join(parts)

prompt = build_prompt(
    role="Expert code reviewer",
    context="Reviewing a PR for a payment processing module",
    task="Find security vulnerabilities and performance issues",
    constraints=[
        "Focus on OWASP Top 10",
        "Check for SQL injection, XSS, auth bypass",
        "Flag any hardcoded secrets",
        "Suggest specific fixes with code"
    ]
)
Enter fullscreen mode Exit fullscreen mode

5. Step-by-Step Decomposition

prompt = """Break this complex task into steps, then execute each:

TASK: Build a complete user authentication system

STEPS:
1. Design database schema (users, sessions, roles)
2. Implement password hashing (bcrypt/argon2)
3. Create registration endpoint with validation
4. Build login with JWT tokens
5. Add refresh token rotation
6. Implement password reset flow
7. Add rate limiting on auth endpoints
8. Write integration tests

Execute step 1 now. Output only the SQL schema."""
Enter fullscreen mode Exit fullscreen mode

6. Output Format Specification

prompt = """Analyze this code and return ONLY valid JSON:

{
  "issues": [
    {"line": 15, "severity": "high", "type": "security", "message": "...", "fix": "..."}
  ],
  "summary": {"high": 2, "medium": 5, "low": 3},
  "approved": false
}

Code to analyze:
[PASTE CODE HERE]

No markdown, no explanation — just the JSON object."""
Enter fullscreen mode Exit fullscreen mode

Level 3: Advanced Patterns

7. ReAct (Reasoning + Acting)

prompt = """You have access to tools. Use this format:

Thought: [your reasoning]
Action: [tool_name]
Action Input: [arguments]
Observation: [result]
... (repeat)
Final Answer: [conclusion]

Tools: web_search, calculate, execute_python

Question: What's the current market cap of Apple, and what would 0.1% of it be in billions?"""
Enter fullscreen mode Exit fullscreen mode

8. Self-Consistency (Multiple Paths)

prompt = """Solve this problem 3 different ways, then compare:

Problem: Estimate the number of piano tuners in Chicago.

Method 1: Fermi estimation (population → households → pianos → tuners)
Method 2: Labor statistics approach (BLS data → ratio)
Method 3: Market size approach (piano sales → tuning frequency → tuners needed)

Show all 3 calculations, then give your best estimate with confidence."""
Enter fullscreen mode Exit fullscreen mode

9. Tree of Thoughts (Exploration)

prompt = """Explore multiple solution paths for this problem:

Problem: Design a rate limiter for a distributed API gateway

Paths to explore:
A. Token bucket (per-client, in-memory)
B. Sliding window log (Redis sorted sets)
C. Fixed window counter (Redis INCR + TTL)
D. Sliding window counter (hybrid)
E. Distributed token bucket (Consul/etcd)

For each: pros, cons, complexity, scalability, consistency.
Then recommend best for: 10K req/s, 100K clients, multi-region."""
Enter fullscreen mode Exit fullscreen mode

10. Meta-Prompting (Prompt Improving Prompts)

prompt = """Improve this prompt for better results:

ORIGINAL: "Write a blog post about AI"

IMPROVED VERSION:
- Target audience: Technical founders
- Length: 1500 words
- Tone: Authoritative but accessible
- Structure: Problem → Solution → Implementation → Results
- Include: 3 code examples, 1 comparison table, actionable checklist
- SEO keywords: LLM fine-tuning, RAG, vector databases
- Call to action: Sign up for newsletter

Generate 3 variations optimized for different models (GPT-4, Claude, Llama)."""
Enter fullscreen mode Exit fullscreen mode

Model-Specific Tips

GPT-4 / Claude

  • Excellent at following complex instructions
  • Handles long context well
  • Good at structured output (JSON, YAML)
  • Prefers explicit constraints

Llama / Mistral (Open Weights)

  • Benefits from more examples
  • Needs clearer step-by-step
  • Sometimes ignores negative constraints ("don't do X")
  • Better with XML tags than markdown

Small Models (7B and below)

  • Few-shot critical
  • Keep prompts short
  • One task per prompt
  • Explicit output format required

Prompt Templates Library

Code Generation

CODE_GEN_TEMPLATE = """
ROLE: Senior {language} developer
CONTEXT: {project_context}
TASK: {specific_task}

REQUIREMENTS:
- {req_1}
- {req_2}
- {req_3}

STYLE: {style_guide} (e.g., "Google Python Style Guide")
TESTS: Include pytest tests for happy path + edge cases
OUTPUT: Complete file(s) only, no explanation
"""
Enter fullscreen mode Exit fullscreen mode

Code Review

CODE_REVIEW_TEMPLATE = """
ROLE: Staff engineer code reviewer
CONTEXT: {project_type} codebase, {team_size} developers
TASK: Review this PR for correctness, security, performance, maintainability

CHECKLIST:
□ Logic correctness
□ Error handling
□ Security (input validation, auth, secrets)
□ Performance (N+1, caching, algorithms)
□ Readability (naming, comments, structure)
□ Tests (coverage, edge cases)
□ Documentation updates

OUTPUT FORMAT:
## Summary: [Approve / Request Changes / Comment]
## Issues:
### High: [...]
### Medium: [...]
### Low: [...]
## Suggestions: [...]
"""
Enter fullscreen mode Exit fullscreen mode

Debugging Assistant

DEBUG_TEMPLATE = """
ROLE: Expert debugger
CONTEXT: {language} {framework} application
ERROR: {error_message}
STACK_TRACE: {stack_trace}
RELEVANT_CODE: {code_snippet}

TASK: Diagnose root cause and provide fix

APPROACH:
1. Identify the exact failure point
2. Explain why it fails
3. Provide minimal fix
4. Suggest prevention

OUTPUT:
ROOT CAUSE: [one sentence]
FIX: [code diff]
PREVENTION: [one actionable tip]
"""
Enter fullscreen mode Exit fullscreen mode

Anti-Patterns to Avoid

❌ Bad ✅ Good
"Write code" "Write a FastAPI endpoint for user registration with Pydantic validation"
"Make it better" "Optimize this query: reduce from 500ms to <50ms, add index suggestion"
"Fix bugs" "Fix the race condition in lines 45-52 where concurrent writes corrupt state"
"Explain this" "Explain this regex to a junior dev: break down each capture group"
No format "Return ONLY valid JSON matching this schema: {...}"

Prompt Evaluation Checklist

Before sending, verify:

  • [ ] Role defined? (expert, reviewer, teacher, etc.)
  • [ ] Context provided? (project, constraints, background)
  • [ ] Task specific and measurable?
  • [ ] Constraints explicit? (format, length, style, forbidden)
  • [ ] Examples included for few-shot?
  • [ ] Output format specified? (JSON, markdown, code only)
  • [ ] Step-by-step requested for complex tasks?
  • [ ] Edge cases mentioned?

Iterative Refinement Loop

1. Write prompt
2. Test on 3-5 examples
3. Analyze failures
4. Add constraint/example to fix failure
5. Repeat until 90%+ success
6. Save as template
Enter fullscreen mode Exit fullscreen mode

Conclusion

Prompt engineering = clear thinking + structured communication. The best prompts are:

  • Specific (not vague)
  • Constrained (not open-ended)
  • Structured (role, context, task, format)
  • Iterative (test → refine → template)

Build your prompt library. Version control it. Share with your team. Treat prompts as code.


Part of the Prompt Engineering series on Dev.to

Top comments (0)