Prompt Engineering

For Developers

Lecture 3

Crafting effective prompts for AI-assisted development

Why Prompt Engineering Matters

The same AI, vastly different results

Vague Prompt

"Make a login page"

Result

  • Generic HTML form
  • No validation
  • Hardcoded credentials
  • No error handling

Structured Prompt

"Create a secure login form with email validation, bcrypt password hashing, JWT tokens, and rate limiting. Use React Hook Form with Zod schema validation."

Result

  • Secure implementation
  • Proper validation
  • Industry best practices
  • Production-ready

Anatomy of an Effective Prompt

1. Context

What's the situation? What does the AI need to know?

2. Task

What exactly should the AI do? Be specific.

3. Constraints

What are the boundaries? What should it NOT do?

4. Output Format

How should the response be structured?

Template[CONTEXT] I'm building a [type of app] using [tech stack]. [TASK] Create a [specific component/feature] that [does what]. [CONSTRAINTS] Must include [requirements]. Do not [restrictions].
Template[CONTEXT] I'm building a [type of app] using [tech stack]. [TASK] Create a [specific component/feature] that [does what]. [CONSTRAINTS] Must include [requirements]. Do not [restrictions]. [OUTPUT] Provide [format: code only, explanation + code, etc.]

Technique 1: Context Setting

Foundation

Give AI the information it needs to generate relevant code.

Without ContextCreate a user authentication function.

Result: Generic, possibly insecure code

With ContextI'm building a Flask REST API with PostgreSQL. Users must authenticate with email/password. We use JWT tokens for session management. The app follows OWASP security guidelines. Create a user authentication function.

Result: Secure, framework-appropriate code

Pro tip: Reference your vision.md: "Read vision.md first, then..."

Technique 2: Be Specific

Precision

Vague requests get vague results. Details matter.

VagueSpecific
"Add validation""Add Zod schema validation for email (RFC 5322), password (min 8 chars, 1 upper, 1 number), and phone (E.164 format)"
"Handle errors""Catch network errors, show toast notification, log to Sentry, retry 3 times with exponential backoff"
"Make it fast""Implement React.memo, useMemo for expensive calculations, lazy load images, target < 100ms render"
"Add tests""Write Jest unit tests covering: valid input, empty fields, invalid email format, duplicate users, network failure"

Technique 3: Role Assignment

Perspective

Give the AI a role to adopt a specific expertise perspective.

Security Expert

"Act as a security engineer. Review this code for vulnerabilities..."

Performance Engineer

"Act as a performance specialist. Optimize this database query..."

Code Reviewer

"Act as a senior developer. Review this PR for best practices..."

Test Engineer

"Act as a QA engineer. Generate edge case tests for..."

ExampleAct as a senior Python developer with expertise in async programming. Review this FastAPI endpoint for performance issues and race conditions. Suggest improvements using best practices for high-concurrency systems.

Technique 4: Step-by-Step Instructions

Decomposition

Break complex tasks into numbered steps for better results.

Multi-Step PromptImplement user registration. Follow these steps: Step 1: Create a Pydantic model for user input validation - Email must be valid format - Password must be 8+ chars with 1 uppercase and 1 number Step 2: Create the registration endpoint - POST /api/auth/register - Hash password with bcrypt - Store in PostgreSQL Step 3: Add error handling - Duplicate email returns 409 - Validation errors return 422 with details - Database errors return 500 Step 4: Write tests for each error case

Technique 5: Provide Examples

Few-Shot Learning

Show the AI what you want with concrete examples.

With ExamplesConvert these function names to our naming convention. Convention: camelCase verbs, descriptive, no abbreviations Examples: - get_usr_data → getUserData - calc_tot → calculateTotal - chk_auth → checkAuthentication - proc_pmt → processPayment Now convert: - upd_prof - del_itm - val_inp - gen_rpt
Few-shot prompting: 3-5 examples usually sufficient to establish the pattern.

Technique 6: Set Clear Constraints

Boundaries

Tell AI what NOT to do. Prevents over-engineering and scope creep.

Without Constraints

"Build a todo app"

AI might add: authentication, categories, due dates, notifications, sharing, themes...

With Constraints

"Build a todo app"

  • Do NOT add authentication
  • Do NOT use external libraries
  • Keep it single-file
  • No CSS frameworks
Constraint Keywords- Do NOT add features beyond the requirements - ONLY use standard library functions - MUST NOT modify existing files - AVOID third-party dependencies - KEEP the solution under 100 lines

Technique 7: Specify Output Format

Structure

Control how the AI structures its response.

Code Only

"Provide only the code, no explanations."

Commented Code

"Add inline comments explaining each section."

Explanation + Code

"First explain the approach, then provide code."

Format SpecificationRespond in this format: ## Approach Brief explanation of the solution strategy ## Implementation ```python # Code here ``` ## Testing ```python # Test cases ``` ## Notes Any caveats or considerations

Technique 8: Iterative Refinement

Dialogue

Don't expect perfection on the first try. Refine through conversation.

Initial Request

"Create a pagination component"

Refinement 1

"Add keyboard navigation support"

Refinement 2

"Make it accessible (ARIA labels)"

Refinement 3

"Add loading states"

Key insight: Iteration is faster than trying to specify everything upfront.

Technique 9: Chain of Thought

Reasoning

Ask AI to think through the problem step by step.

Chain of Thought PromptDebug this function. Think through it step by step: 1. What is the function supposed to do? 2. What inputs does it receive? 3. Trace through the logic with a sample input 4. Where does the actual output differ from expected? 5. What's causing the bug? 6. How should it be fixed? ```python def calculate_discount(price, discount_percent): return price - (price / discount_percent) # Bug here ```

Why It Works

Forces the AI to reason through the problem rather than pattern-match to a solution.

Common Prompt Mistakes

Too Vague

"Make it better"
"Fix the bug"
"Add some tests"

Too Long

Walls of text confuse AI. Break into multiple prompts.

Contradictory

"Keep it simple but add all these features..."

No Examples

Abstract requirements without concrete samples.

If you can't explain what you want clearly to a human, you can't explain it clearly to an AI.

Prompt Templates for AIDD Phases

PhasePrompt Start
Discover"Read vision.md. Map user journeys for [feature]. Identify personas, goals, flows..."
Plan"Based on the journeys, create task epics with user stories and acceptance criteria..."
Review"Review these tasks for duplication, coupling, missing edge cases..."
Execute"Implement [task] using TDD. Write failing test first, then implement..."
Commit"Review changes for security issues, run linting, write commit message following conventions..."
Test"Generate human test script (think-aloud) and automated E2E tests for..."
Always: Start with "Read vision.md first" to maintain context.

Practice: Improve This Prompt

Original (Bad)

"Create a search feature"

Improved (Good)

"I'm building a React e-commerce app with TypeScript. Create a product search feature:

Requirements:
- Debounced input (300ms) to prevent excessive API calls
- Show loading spinner during search
- Display results in a dropdown below input
- Keyboard navigation (up/down arrows, enter to select)
- Handle empty results and errors gracefully

Constraints: Do NOT use external search libraries. Keep component under 150 lines.

Output: Provide the React component code with TypeScript types."

Key Takeaways

CTCO

Context, Task, Constraints, Output format

Specific

Vague prompts = vague results

Examples

Show what you want with samples

Iterate

Refine through conversation

Prompt engineering is not about tricks. It's about clear communication with a machine.

Questions?

Effective Prompt Engineering

Next: Specifications & Vision Documents

Slide Overview