Prompt Engineering Guide
Effective prompt engineering is key to getting high-quality results from AI tools. This guide covers best practices for writing prompts that work.
What is Prompt Engineering?
Prompt engineering is the practice of crafting inputs (prompts) that guide AI models to produce desired outputs. Well-crafted prompts lead to:
- More accurate and relevant responses
- Consistent output format
- Better adherence to requirements
- Reduced need for iteration
Core Principles
1. Be Specific and Clear
Poor prompt:
Write some code for user loginBetter prompt:
Write a TypeScript function that handles user login with email and password.
Requirements:
- Validate email format
- Hash password before comparison
- Return JWT token on success
- Handle errors gracefully
- Include TypeScript types2. Provide Context
Give the AI relevant background information:
I'm working on a React application using TypeScript and Material-UI.
I need a reusable form component for user registration that includes:
- Email and password fields
- Client-side validation
- Error message display
- Loading state during submission3. Specify Output Format
Tell the AI exactly what format you want:
Generate API documentation for the following function in JSDoc format.
Include: description, parameters, return type, and usage example.4. Use Examples (Few-Shot Prompting)
Show examples of what you want:
Convert these function names to camelCase.
Examples:
- get_user_data → getUserData
- calculate_total_price → calculateTotalPrice
Convert:
- fetch_product_list →
- update_user_profile →Advanced Techniques
Chain of Thought
For complex problems, ask the AI to think step-by-step:
Analyze this code for potential bugs. Think through:
1. What each function does
2. Potential edge cases
3. Security implications
4. Performance concerns
Then provide a summary of issues found.Role Prompting
Assign a role to the AI:
You are a senior security engineer reviewing code for vulnerabilities.
Review this authentication function and identify any security issues:
[code here]Constraints and Requirements
Be explicit about constraints:
Refactor this function with these constraints:
- Must maintain backward compatibility
- No external dependencies
- Maximum 50 lines
- Include error handling
- Add TypeScript typesCommon Patterns
Code Review
Review this code for:
- Bugs and logic errors
- Security vulnerabilities
- Performance issues
- Code style and best practices
- Potential edge cases
[paste code]Documentation Generation
Generate comprehensive documentation for this API endpoint:
- Purpose and functionality
- Request/response examples
- Error handling
- Authentication requirements
- Rate limiting
[endpoint details]Test Case Generation
Generate unit test cases for this function.
Include:
- Happy path scenarios
- Edge cases
- Error conditions
- Mock external dependencies
Use Jest and TypeScript.
[function code]Code Explanation
Explain this code as if teaching a junior developer.
Include:
- What problem it solves
- How each part works
- Why certain approaches were used
- Potential improvements
[code here]Iterative Refinement
Don't expect perfection on the first try. Refine your prompts:
- Initial prompt: Get a basic result
- Analyze output: Identify what's missing or wrong
- Refine prompt: Add more specific requirements
- Iterate: Continue until satisfied
Example Iteration
Attempt 1:
Write a function to sort usersAttempt 2:
Write a TypeScript function to sort an array of users by last nameAttempt 3:
Write a TypeScript function to sort an array of users.
- Sort by last name, then first name
- Case-insensitive sorting
- Handle null/undefined names
- Include proper TypeScript types
- Add JSDoc commentsCommon Pitfalls
❌ Too Vague
Make this better✅ Specific Improvement Request
Refactor this function to:
- Reduce complexity (current cyclomatic complexity: 15)
- Extract repeated logic into helper functions
- Add error handling
- Improve variable names for clarity❌ Ambiguous Terms
Optimize this code✅ Clear Optimization Goals
Optimize this code for:
- Reduced memory usage (currently using 500MB)
- Faster execution (target: under 100ms)
- Better caching strategy❌ Missing Context
Fix the bug✅ Contextual Bug Report
This function throws "undefined is not a function" when the user array is empty.
Expected behavior: Return empty array
Current behavior: Throws error
Environment: Node.js 18, TypeScript 5.0
[code here]Templates for Common Tasks
Bug Fix Request
**Problem**: [Describe the bug]
**Expected**: [What should happen]
**Actual**: [What actually happens]
**Context**: [Environment, dependencies, versions]
**Code**: [Relevant code snippet]
Please identify and fix the bug.Feature Implementation
**Feature**: [Feature name]
**Requirements**:
- [Requirement 1]
- [Requirement 2]
**Constraints**:
- [Constraint 1]
**Tech Stack**: [List technologies]
**Similar to**: [Reference existing code/patterns]Code Refactoring
**Goal**: [What to improve]
**Keep**: [What must stay the same]
**Change**: [What can change]
**Standards**: [Coding standards to follow]
[Code to refactor]Best Practices Summary
- Start broad, then narrow - Begin with general context, then get specific
- One task at a time - Don't try to do too much in one prompt
- Include examples - Show don't just tell
- Specify format - Be explicit about output structure
- Iterate - Refine based on results
- Save good prompts - Build a library of effective prompts
- Test and validate - Always review AI-generated content
Resources
- Example Prompt Library - Collection of proven prompts
- Advanced Techniques - Deep dive into complex prompting strategies
- Troubleshooting Guide - When prompts don't work as expected
Remember: Good prompts are clear, specific, and provide context. The more information you give, the better the results you'll get.