- Learn
- Prompt Engineering
- Prompt Templates and Patterns
Build a library of reusable prompt templates for common development tasks—from code generation to debugging to documentation.
Prompt Templates and Patterns
Creating effective prompts from scratch every time is inefficient. Building a library of reusable templates accelerates your workflow and ensures consistent quality.
Why Use Templates?
Templates provide:
- Consistency - Same quality across all requests
- Speed - Fill in blanks instead of composing from scratch
- Best practices - Encode lessons learned
- Team alignment - Shared standards across developers
Template Structure
A good template has:
[VARIABLES] - Placeholders you fill in
[FIXED TEXT] - Standard instructions that don't change
[OPTIONAL SECTIONS] - Include when relevant
Code Generation Templates
Function Generation
Generate a [LANGUAGE] function with the following specifications:
Function name: [FUNCTION_NAME]
Purpose: [DESCRIPTION]
Parameters:
[PARAMETER_LIST]
Return type: [RETURN_TYPE]
Requirements:
- [REQUIREMENT_1]
- [REQUIREMENT_2]
Constraints:
- [CONSTRAINT_1]
- [CONSTRAINT_2]
Example usage:
[EXAMPLE_CODE]
Include:
- [ ] JSDoc/docstring comments
- [ ] Input validation
- [ ] Error handling
- [ ] Unit test examples
Filled Example:
Generate a TypeScript function with the following specifications:
Function name: calculateDiscount
Purpose: Calculate the final price after applying discount codes
Parameters:
- originalPrice: number (the base price)
- discountCode: string (the discount code to apply)
- userTier: 'basic' | 'premium' | 'vip' (affects discount multiplier)
Return type: { finalPrice: number; discountApplied: number; }
Requirements:
- Validate discount code against allowed codes list
- Apply tier multiplier (basic: 1x, premium: 1.2x, vip: 1.5x)
- Round to 2 decimal places
Constraints:
- Discount cannot exceed original price
- Invalid codes should return original price with 0 discount
Include:
- [x] JSDoc comments
- [x] Input validation
- [x] Error handling
- [ ] Unit test examples
Component Generation
Create a [FRAMEWORK] component with these specifications:
Component name: [COMPONENT_NAME]
Type: [FUNCTIONAL|CLASS]
Props:
[PROPS_WITH_TYPES]
State (if any):
[STATE_VARIABLES]
Features:
- [FEATURE_1]
- [FEATURE_2]
Styling: [STYLING_APPROACH]
Accessibility requirements:
- [A11Y_REQUIREMENT]
Follow this existing pattern:
```typescript
[EXAMPLE_COMPONENT]
### API Endpoint Generation
Create a [FRAMEWORK] API endpoint:
Method: [HTTP_METHOD] Path: [ENDPOINT_PATH] Purpose: [DESCRIPTION]
Request:
- Body/Query: [REQUEST_SCHEMA]
- Headers: [REQUIRED_HEADERS]
Response:
- Success ([STATUS_CODE]): [SUCCESS_SCHEMA]
- Error ([ERROR_CODES]): [ERROR_SCHEMA]
Requirements:
- Authentication: [AUTH_TYPE]
- Validation: [VALIDATION_LIB]
- Rate limiting: [YES/NO]
Database operations: [DESCRIBE_DB_OPS]
Error handling: [ERROR_HANDLING_PATTERN]
## Debugging Templates
### Error Analysis
Analyze this error and help me fix it.
Error Type: [ERROR_TYPE] Error Message:
[FULL_ERROR_MESSAGE]
Stack Trace:
[STACK_TRACE]
Relevant Code:
[CODE_WHERE_ERROR_OCCURS]
Context:
- Environment: [ENVIRONMENT]
- When it occurs: [TRIGGER_CONDITIONS]
- Frequency: [ALWAYS|SOMETIMES|RARELY]
What I've tried:
- [ATTEMPT_1]
- [ATTEMPT_2]
Please:
- Explain what this error means
- Identify the root cause
- Suggest a fix with code
- Explain how to prevent this in the future
### Performance Investigation
Investigate this performance issue.
Symptom: [DESCRIPTION_OF_SLOWNESS]
Metrics:
- Current: [CURRENT_PERFORMANCE]
- Expected: [EXPECTED_PERFORMANCE]
- Measured using: [MEASUREMENT_METHOD]
Code under investigation:
[SLOW_CODE]
Context:
- Data size: [DATA_SIZE]
- Frequency of execution: [CALL_FREQUENCY]
- Environment: [ENVIRONMENT]
Questions:
- What is causing the performance issue?
- What is the current time/space complexity?
- How can this be optimized?
- What's the expected improvement?
## Refactoring Templates
### Code Cleanup
Refactor this code for better [QUALITY_ASPECT].
Current code:
[CODE_TO_REFACTOR]
Issues with current code:
- [ISSUE_1]
- [ISSUE_2]
Refactoring goals:
- [GOAL_1]
- [GOAL_2]
Constraints:
- Must preserve: [BEHAVIOR_TO_KEEP]
- Must not change: [API_CONSTRAINTS]
- Must remain compatible with: [COMPATIBILITY_REQUIREMENTS]
Style guide: [RELEVANT_STYLE_RULES]
### Pattern Migration
Migrate this code from [OLD_PATTERN] to [NEW_PATTERN].
Current implementation ([OLD_PATTERN]):
[CURRENT_CODE]
Target pattern ([NEW_PATTERN]): Example of target pattern:
[PATTERN_EXAMPLE]
Requirements:
- Maintain identical functionality
- Follow the new pattern consistently
- Update any related imports/dependencies
After migration, verify:
- [VERIFICATION_1]
- [VERIFICATION_2]
## Review Templates
### Code Review
Review this code for [REVIEW_FOCUS].
Code to review:
[CODE]
Context:
- Purpose: [CODE_PURPOSE]
- Part of: [LARGER_FEATURE]
- Author experience level: [JUNIOR|MID|SENIOR]
Review criteria:
- Correctness
- Security
- Performance
- Maintainability
- Test coverage
- Documentation
Provide feedback in this format:
- Critical: Must fix before merge
- Important: Should fix
- Minor: Nice to have
- Positive: What's done well
### Security Audit
Perform a security review of this code.
Code:
[CODE]
Context:
- Handles: [DATA_TYPE] (e.g., user input, payments, PII)
- Exposed via: [EXPOSURE_POINT] (e.g., public API, internal service)
- Authentication: [AUTH_METHOD]
Check for:
- Injection vulnerabilities (SQL, NoSQL, Command)
- XSS vulnerabilities
- Authentication/Authorization flaws
- Sensitive data exposure
- Security misconfiguration
- Vulnerable dependencies
For each issue found, provide:
- Vulnerability type
- Severity (Critical/High/Medium/Low)
- Location in code
- Exploitation scenario
- Recommended fix
## Documentation Templates
### Function Documentation
Write documentation for this function.
Function:
[FUNCTION_CODE]
Documentation style: [JSDOC|DOCSTRING|MARKDOWN]
Include:
- Purpose description
- Parameter descriptions with types
- Return value description
- Exceptions/errors that can be thrown
- Usage examples (at least 2)
- Edge cases to be aware of
### API Documentation
Generate API documentation for this endpoint.
Endpoint code:
[ENDPOINT_CODE]
Documentation format: [OPENAPI|MARKDOWN|CUSTOM]
Include:
- Endpoint description
- Request format (method, path, headers, body)
- Response formats (success and error cases)
- Authentication requirements
- Rate limits
- Example requests and responses
- Common error scenarios
## Testing Templates
### Unit Test Generation
Generate unit tests for this function.
Function to test:
[FUNCTION_CODE]
Testing framework: [JEST|PYTEST|MOCHA|etc]
Test coverage requirements:
- Happy path scenarios
- Edge cases
- Error conditions
- Boundary values
Mocking needs: [DEPENDENCIES_TO_MOCK]
Follow this test structure:
[EXAMPLE_TEST_STRUCTURE]
### Integration Test Generation
Generate integration tests for this [API_ENDPOINT|WORKFLOW].
Code under test:
[CODE]
Test environment:
- Framework: [TEST_FRAMEWORK]
- Database: [TEST_DB_APPROACH]
- External services: [MOCKED|REAL]
Scenarios to test:
- [SCENARIO_1]
- [SCENARIO_2]
- [SCENARIO_3]
Setup/teardown requirements: [SETUP_REQUIREMENTS]
## Creating Your Own Templates
### Template Design Process
1. **Identify repetition** - What prompts do you write often?
2. **Extract variables** - What changes between uses?
3. **Define fixed elements** - What stays the same?
4. **Add optional sections** - What's sometimes needed?
5. **Test and refine** - Iterate based on results
### Template Naming Convention
[TASK_TYPE][SPECIFICITY][VARIATION]
Examples:
- generate_function_typescript
- debug_error_runtime
- review_security_api
- refactor_extract_component
### Template Storage
Options for storing templates:
- **IDE snippets** - Quick access while coding
- **Text expander** - System-wide availability
- **Git repository** - Team sharing and version control
- **Documentation site** - Searchable reference
## Combining Templates
Chain templates for complex workflows:
Step 1: Use "generate_function" template Step 2: Use "generate_tests" template for the function Step 3: Use "review_code" template on both
## Practice Exercise
Create templates for your common tasks:
1. **Identify** 3 prompts you write frequently
2. **Extract** the variable and fixed parts
3. **Format** as reusable templates
4. **Test** with different inputs
5. **Refine** based on output quality
## Summary
- Templates provide consistency, speed, and quality
- Include clear placeholders for variable content
- Build templates for your most common tasks
- Share templates with your team
- Continuously refine based on results
## Next Steps
Let's explore common mistakes in prompt engineering—patterns to avoid and how to fix them.