# Prompt Engineering Guide

Core principles for effective prompting when working with AI coding assistants.

## The Fundamentals

### 1. Be Specific

**Vague prompts get vague results**

❌ Bad: "Create a function"
✅ Good: "Create a Python function that validates email addresses using regex, returns True/False, and includes error handling for None input"

### 2. Provide Context

**AI needs to understand your environment**

Include:
- Language and version
- Framework/library versions
- Existing code patterns
- Project constraints
- Current file structure

Example:
```
"I'm working on a Node.js Express application (v4.18) with TypeScript.
We use async/await throughout and follow functional programming patterns.
Create middleware for request logging that matches our existing auth middleware style."
```

### 3. Show Examples

**One example is worth a thousand words**

```
"Create a React component similar to this existing one:
[paste existing component]

But for displaying user profiles instead of posts."
```

### 4. Specify Constraints

**Tell the AI what NOT to do**

```
"Generate a sorting function that:
- Uses O(n log n) complexity
- Does NOT modify the original array
- Does NOT use built-in sort method
- Handles null/undefined gracefully"
```

### 5. Request Explanations

**Learn while you code**

```
"Create a caching layer for our API.
Explain your design choices and any trade-offs."
```

## Advanced Techniques

### Iterative Refinement

Start broad, then narrow:

```
Round 1: "I need to implement user authentication"
[Review response]

Round 2: "Good start. Now add password hashing with bcrypt
and JWT token generation"
[Review response]

Round 3: "Add rate limiting to prevent brute force attacks"
```

### Alternative Exploration

Ask for options:

```
"Show me 3 different approaches to implement real-time notifications:
1. WebSockets
2. Server-Sent Events
3. Long polling

For each, briefly explain pros/cons for our use case."
```

### Error-Driven Development

Use errors to guide:

```
"I'm getting this error: [paste error]

Here's the relevant code: [paste code]

What's wrong and how do I fix it?
After fixing, explain why the error occurred."
```

### Constraint Specification

Be explicit about requirements:

```
"Create a date picker component with these requirements:
MUST:
- Work with React 18
- Support date ranges
- Be keyboard accessible

SHOULD:
- Have minimal dependencies
- Work with our theme system

COULD:
- Support time selection
- Include presets (last 7 days, etc.)

MUST NOT:
- Use moment.js (deprecated in our project)
- Require jQuery
```

## Prompting Patterns

### Pattern 1: The Template Fill

"Using this template: [paste template]
Create a [component/function] for [purpose]
Replace [placeholders] with [specific values]"

### Pattern 2: The Incremental

```
Step 1: "Create the basic structure for X"
Step 2: "Add error handling"
Step 3: "Add tests"
Step 4: "Add documentation"
```

### Pattern 3: The Comparison

"Here's how we currently do X: [paste code]
Create a new version that Y
Keep the same interface but improve Z"

### Pattern 4: The Review

"Review this code: [paste code]
Check for:
- Security vulnerabilities
- Performance issues
- Best practice violations
- Edge cases we might have missed"

### Pattern 5: The Debug

"This code should X but instead it Y
[paste code]
[paste error/unexpected behavior]

Help me debug:
1. What's causing this?
2. How do I fix it?
3. How can I prevent this in the future?"

## Model-Specific Tips

### For Claude
- Tends toward thorough explanations
- Good at understanding context
- Can handle complex, multi-step requests
- Prefers when you explain your reasoning

### For GPT-4
- Often more concise
- Good at quick iterations
- Handles technical depth well
- Can be more direct

### For Copilot
- Best with inline code context
- Good at autocomplete-style suggestions
- Use comments to guide
- Works well with clear function names

## Common Mistakes

### ❌ Assuming Context
Don't assume AI knows your project
→ Always provide relevant context

### ❌ Accepting First Output
AI rarely gets it perfect first try
→ Iterate and refine

### ❌ Vague Requirements
"Make it better" isn't actionable
→ Specify what aspect to improve

### ❌ Ignoring Explanations
Generated code without understanding is technical debt
→ Always ask "why" if you don't understand

### ❌ Not Testing Output
AI can make mistakes
→ Always verify generated code

## Effective Prompting Checklist

Before submitting a prompt, ask:

- [ ] Did I specify the language/framework?
- [ ] Did I provide relevant context?
- [ ] Did I include constraints?
- [ ] Did I show examples if applicable?
- [ ] Did I specify what success looks like?
- [ ] Did I mention what to avoid?

## Example: Good vs. Better Prompts

### Scenario: Need user validation

❌ Basic:
```
"Create user validation"
```

✅ Good:
```
"Create a user validation function in JavaScript that checks:
- Email format
- Password strength (min 8 chars, 1 number, 1 special char)
- Username length (3-20 chars)

Return an object with validation results."
```

✅ Better:
```
"Create a user validation function for our Node.js Express app (ES6+).

Context:
- We use Joi for other validations
- Function should match that pattern
- Need detailed error messages for UX

Requirements:
- Email format validation
- Password: min 8 chars, ≥1 number, ≥1 special char, ≥1 uppercase
- Username: 3-20 chars, alphanumeric + underscore only
- Return: { valid: boolean, errors: array }

Example usage:
const result = validateUser({ email, password, username });
if (!result.valid) {
  // Show result.errors to user
}

Please include JSDoc comments."
```

## Practice Exercise

Try improving this prompt:
```
"Fix my code"
```

Better version might be:
```
"I have a React component that should filter a list when typing in a search box,
but the list doesn't update. Using React 18 with hooks.

Code: [paste]
Expected: List filters as I type
Actual: Nothing happens

What's wrong and how do I fix it?"
```

## Resources in This Repo

- Example prompts: `prompts/` directory
- Model-specific tips: `model-nuances/` directory
- Usage patterns: `playbooks/` directory

## Remember

**Good prompts = Better code = Less debugging**

Take an extra 30 seconds to craft a clear prompt.
It saves hours of back-and-forth.
