The 7 Components of a Perfect Prompt:
1. ROLE DEFINITION
"You are a senior software engineer specializing in..."
2. CONTEXT
"The user is building a REST API for e-commerce..."
3. TASK STATEMENT
"Generate a FastAPI endpoint for user authentication..."
4. CONSTRAINTS
"- Use async/await
- Include rate limiting
- Add request/response schemas
- Maximum 50 lines of code"
5. EXAMPLES (Few-shot)
Example input → expected output
6. OUTPUT FORMAT SPECIFICATION
"Return in JSON format with fields: code, explanation, dependencies, test examples"
7. META-INSTRUCTIONS
"Explain your reasoning before showing code. If multiple approaches exist, mention trade-offs."
Complete Example:
ROLE:
You are a senior DevOps engineer with expertise in AWS, Docker, and GitHub Actions.
CONTEXT:
A startup is deploying a Python FastAPI application that uses Claude API.
Current setup: manual deployment to an EC2 instance.
Goal: automated CI/CD pipeline with zero-downtime deployments.
TASK:
Design a GitHub Actions workflow that:
1. Runs tests on every push
2. Builds a Docker image on main branch pushes
3. Deploys to AWS ECS Fargate with blue/green deployment
4. Sends Slack notifications on deployment status
CONSTRAINTS:
- Use AWS secrets from GitHub Secrets (not hardcoded)
- Include a rollback step if health checks fail
- Cache Docker layers for faster builds
- Maximum workflow runtime: 10 minutes
OUTPUT FORMAT:
<explanation>[Brief overview]</explanation>
<workflow>[Complete YAML]</workflow>
<cost_estimate>[Monthly AWS cost]</cost_estimate>
<alternatives>[2 alternatives with trade-offs]</alternatives>
META:
- List any assumptions you're making
- Include security best practices
- Add comments in the YAML file
Why Role Prompting Works:
Assigning a role activates specific knowledge patterns in Claude's training data. A "lawyer" prompt produces different language, reasoning, and caution than a "creative writer" prompt.
Technical Expert Template:
"You are a {specialty} engineer with {X} years of experience at {company type}.
You prioritize {value1}, {value2}, and {value3}.
You are skeptical of {technology} and prefer {alternative}."
Example:
"You are a security-focused backend engineer with 10 years of experience
at fintech companies. You prioritize auditability, encryption at rest,
and principle of least privilege. You are skeptical of ORMs and prefer
raw SQL with query builders."
Creative Professional Template:
"You are a {genre} {role} who has won {awards}. Your style is characterized
by {trait1}, {trait2}, and {trait3}. You avoid {cliche1} and {cliche2}."
Example:
"You are a hard science fiction author who has won the Hugo and Nebula awards.
Your style is characterized by technical accuracy, political realism, and
pessimistic outcomes. You avoid deus ex machina and faster-than-light travel
without explanation."
Consultant/Analyst Template:
"You are a {industry} consultant from {firm}. Your methodology involves {framework}.
You communicate with {tone} and always include {element}."
Example:
"You are a supply chain consultant from McKinsey. Your methodology involves
value stream mapping and theory of constraints. You communicate with
data-driven precision and always include a 'risk factors' section."
Role Prompt Comparison:
| User Query | No Role | With Role (Cybersecurity Expert) |
|---|---|---|
| "How to store passwords?" | "Use bcrypt or Argon2" | "NEVER store plaintext passwords. Use Argon2id with at least 64MB memory, 3 iterations, and a salt. Consider using AWS KMS for key management. Implement rate limiting (5 attempts/hour) and account lockout after 10 failures." |
| "What's wrong with this code?" | "The SQL is vulnerable" | "CRITICAL VULNERABILITY: SQL injection on line 7. Replace f-string with parameterized queries. Also missing: input validation, rate limiting, and error handling that doesn't leak schema info. See OWASP Top 10 A03:2021." |
Zero-Shot vs One-Shot vs Few-Shot:
ZERO-SHOT (no examples):
Classify sentiment: "I love this product"
Output: Positive
ONE-SHOT (one example):
Classify sentiment. Example:
Text: "This movie was terrible"
Sentiment: Negative
Now classify: "I love this product"
Sentiment:
FEW-SHOT (3-5 examples):
Classify sentiment. Examples:
Text: "This movie was terrible" → Negative
Text: "The service was okay" → Neutral
Text: "Absolutely fantastic experience!" → Positive
Text: "Could be better, could be worse" → Neutral
Now classify: "I love this product"
Sentiment:
Real Example: Extracting Structured Data
Extract structured data from customer emails into JSON.
Example 1:
Email: "Hi, I want to return order #12345. The red shirt is too small."
Output: {"intent": "return", "order_id": "12345", "product": "red shirt", "reason": "size too small"}
Example 2:
Email: "Where's my package? Order 67890 was supposed to arrive yesterday."
Output: {"intent": "tracking", "order_id": "67890", "issue": "delayed delivery", "urgency": "high"}
Example 3:
Email: "Cancel my subscription immediately. I was charged $50 on Feb 15."
Output: {"intent": "cancel", "service": "subscription", "amount": 50.00, "date": "Feb 15", "urgency": "immediate"}
Now extract from this email:
Email: "Need help with order 99999. The blue sweater has a hole in the sleeve."
Output:
Few-Shot Best Practices:
- Use 3-5 examples (fewer if simple, more if complex)
- Cover edge cases in examples
- Be consistent in format across examples
- Label examples clearly (Example 1, Example 2, etc.)
- Use diverse examples (different intents, variations in phrasing)
Types of Constraints:
LENGTH CONSTRAINTS:
"Respond in exactly 5 words"
"Summarize in 2-3 sentences"
"Maximum 100 tokens"
VOCABULARY CONSTRAINTS:
"Use only words from a 3rd grade reading level"
"Never use jargon or technical terms"
"Avoid the words 'good', 'bad', 'nice'"
STRUCTURAL CONSTRAINTS:
"Output as valid JSON"
"Use XML tags"
"Start each paragraph with a question"
STYLE CONSTRAINTS:
"Write in active voice only"
"Never use passive constructions"
"Use bullet points, not paragraphs"
FORMAT CONSTRAINTS:
"No markdown formatting"
"No code blocks"
"Plain text only"
Example: Multiple Constraints
Respond with exactly 5 words.
No verbs (action words).
Every response as: [Adjective] [Noun] [Preposition] [Adjective] [Noun]
Example valid: "Happy dog in green grass"
Example invalid: "The dog runs fast" (contains 'runs' - a verb)
Now respond to: "Describe the weather today"
Your response (5 words, no verbs):
Why Constraints Fail (And How to Fix):
| Problem | Why | Fix |
|---|---|---|
| Claude ignores length constraint | Ambiguous definition | "Exactly 5 words. Count: 'The' (1), 'sky' (2), 'is' (3), 'blue' (4), '.' (5)" |
| Claude uses forbidden word | No negative examples | "Never use 'good', 'bad', 'nice'. Instead use precise adjectives like 'exceptional', 'suboptimal', 'elegant'" |
| Format inconsistent | Format not reinforced | Give 3 examples of correct format AND 2 examples of incorrect format |
Why XML Works Well with Claude:
- Claude was trained on extensive XML data
- Tags provide clear semantic boundaries
- Hierarchical structure mirrors Claude's attention patterns
- Easy to parse responses programmatically
XML Prompt Template:
<system>
You are a code review AI for a fintech company.
</system>
<context>
Project: Payment Processing API
Language: Python 3.11
Framework: FastAPI
Security requirements: PCI-DSS Level 1
</context>
<task>
Review the following code for security vulnerabilities:
</task>
<code>
def process_payment(card_number, amount):
connection = sqlite3.connect('payments.db')
cursor = connection.cursor()
cursor.execute(f"INSERT INTO payments VALUES ('{card_number}', {amount})")
return "Success"
</code>
<constraints>
Focus only on:
1. SQL injection vulnerabilities
2. Sensitive data exposure (PCI violations)
3. Input validation issues
Ignore style and performance for this review.
</constraints>
<output_format>
<vulnerability>
<type>SQL injection | Data exposure | Validation</type>
<line>[line number]</line>
<severity>[Critical | High | Medium | Low]</severity>
<description>[What's wrong]</description>
<fix>[How to fix]</fix>
</vulnerability>
</output_format>
<meta>
If no vulnerabilities found, output: <safe>No issues detected</safe>
</meta>
The Prompt Engineering Workflow:
START
↓
Write initial prompt
↓
Test on 5-10 edge cases
↓
Identify failures
↓
UNDERSTANDING ERROR? → Add clarification
FORMAT ERROR? → Add explicit format example
CONTEXT ERROR? → Add missing context
CONSTRAINT ERROR? → Reinforce constraint (bookend)
HALLUCINATION? → Add citation requirement + lower temp
↓
Refine prompt
↓
Test again
↓
Satisfactory? → YES → DONE
↓ NO
(Repeat)
The 5 Debugging Questions:
Ask yourself these questions for every failure:
-
WHAT DID YOU EXPECT?
Expected output: [paste example]
-
WHAT DID CLAUDE OUTPUT?
Actual output: [paste]
-
WHAT'S THE DIFFERENCE?
- Structure difference?
- Content omission?
- Constraint violation?
- Factual error?
-
WHY MIGHT CLAUDE HAVE MISUNDERSTOOD?
- Ambiguous instruction?
- Missing context?
- Conflicting examples?
- Unusual edge case?
-
HOW WILL YOU FIX IT?
- [Specific change to prompt]
- [Additional constraint]
- [Better formatting]
Real Debugging Example:
PROBLEM: Claude keeps using markdown when asked for plain text.
INITIAL PROMPT: "Respond in plain text only"
CLAUDE OUTPUT: **Hello world** (markdown bold)
DIAGNOSIS: "Plain text" is ambiguous. Claude might consider markdown
as "plain text with formatting."
FIXED PROMPT:
"Respond in PURE plain text with NO markdown formatting.
DO NOT USE: **bold**, *italics*, `code`, # headings, - lists, or any markdown syntax.
ONLY USE: Unformatted characters, spaces, newlines, and basic punctuation.
Example allowed: 'Hello world'
Example forbidden: '**Hello world**'
Respond to: 'Say hello in plain text'"
RESULT: "Hello world"