Code reviews are essential for maintaining code quality, security, and consistency in development teams. This template provides a structured approach to code reviews that can be adapted to different files, languages, and specific review focus areas. By using named variables, teams can create consistent review requests while customizing the scope and depth of analysis.
See also Production Prompt Engineering: Patterns, Testing, and Deployment for related architectural patterns on reliability and Prompt Engineering Guide for prompt design patterns.
This template demonstrates variable usage, clear instruction hierarchy, and practical application patterns for code review scenarios. All examples are practical implementation patterns meant to guide engineering teams rather than represent specific deployed systems.
Introduction
Code reviews are essential for maintaining code quality, security, and consistency in development teams. This template provides a structured approach to code reviews that can be adapted to different files, languages, and specific review focus areas. By using named variables, teams can create consistent review requests while customizing the scope and depth of analysis.
See also Production Prompt Engineering: Patterns, Testing, and Deployment for related architectural patterns on reliability and Prompt Engineering Guide for prompt design patterns.
This template demonstrates variable usage, clear instruction hierarchy, and practical application patterns for code review scenarios. All examples are practical implementation patterns meant to guide engineering teams rather than represent specific deployed systems.
Variable Definition
The template uses named variables to enable customization:
- file_path: Path to the file being reviewed
- language: Programming language identifier
- focus_areas: List of specific review areas (security, performance, style, etc.)
- reviewer_role: Perspective to adopt during review
Variable Validation and Safety
Before using variables in production prompts, validate them:
def validate_variables(variables):
required = ['file_path', 'language', 'focus_areas', 'reviewer_role']
for var in required:
if var not in variables:
raise ValueError(f"Missing required variable: {var}")
# Sanitize file path
if '..' in variables['file_path'] or variables['file_path'].startswith('/etc'):
raise ValueError("Invalid file path")
# Validate language against supported list
supported_languages = ['python', 'javascript', 'typescript', 'java', 'go', 'rust']
if variables['language'].lower() not in supported_languages:
raise ValueError(f"Unsupported language: {variables['language']}")
# Ensure focus_areas is a list
if not isinstance(variables['focus_areas'], list):
raise ValueError("focus_areas must be a list")
return True
Comprehensive Prompt Template
Main Template Structure
CODE_REVIEW_TEMPLATE = """You are a senior code reviewer specializing in {language}.
Your task is to review the code in {file_path} with focus on these areas: {focus_areas}.
Adopt the perspective of a {reviewer_role}.
Please provide your analysis in the following structured format:
## 1. Summary of Key Findings
Provide a high-level overview (2-3 paragraphs) of the most important issues found, their severity, and overall code quality assessment.
## 2. Detailed Analysis by Focus Area
For each focus area, provide:
- **Area**: [focus area name]
- **Findings**: Specific observations with line references where possible
- **Severity**: Critical / High / Medium / Low / Informational
- **Recommendation**: Concrete action with code example
Focus areas to cover: {focus_areas}
## 3. Security Considerations
Specifically analyze:
- Input validation and sanitization
- Authentication and authorization patterns
- Data exposure risks
- Injection vulnerabilities
- Cryptographic practices
- Dependency security
## 4. Performance Considerations
Evaluate:
- Algorithmic complexity
- Memory usage patterns
- Database query efficiency
- Caching opportunities
- Async/concurrency patterns
- Resource cleanup
## 5. Style and Readability Assessment
Review:
- Naming conventions and consistency
- Function/method size and cohesion
- Comment quality and necessity
- Error handling patterns
- Type annotations (where applicable)
- Documentation completeness
## 6. Specific Recommendations with Code Examples
For each significant issue, provide:
- **Issue**: Clear description
- **Location**: File and approximate line
- **Current Code**: Relevant snippet
- **Suggested Fix**: Improved version with explanation
- **Rationale**: Why this improves the code
## 7. Testing Recommendations
- Unit test gaps
- Integration test needs
- Edge cases to cover
- Property-based testing opportunities
## 8. Maintenance and Future Considerations
- Technical debt indicators
- Refactoring opportunities
- Scalability concerns
- Dependency update needs
---
File: {file_path}
Language: {language}
Focus Areas: {focus_areas}
Reviewer Role: {reviewer_role}
Example Usage
# Security-focused review
security_review = CODE_REVIEW_TEMPLATE.format(
file_path="/project/src/auth/token_manager.py",
language="python",
focus_areas=["security", "performance", "testing"],
reviewer_role="security-focused senior engineer"
)
# Performance optimization review
performance_review = CODE_REVIEW_TEMPLATE.format(
file_path="/project/src/data/etl_pipeline.py",
language="python",
focus_areas=["performance", "style", "maintenance"],
reviewer_role="performance engineer"
)
# Onboarding/new developer review
onboarding_review = CODE_REVIEW_TEMPLATE.format(
file_path="/project/src/api/handlers.py",
language="python",
focus_areas=["style", "readability", "documentation"],
reviewer_role="mentoring senior developer"
)
Language-Specific Adaptations
Python-Specific Considerations
When language is "python", include these additional focus points:
- Type hint coverage and accuracy
- Context manager usage for resource management
- List/dict comprehension appropriateness
- Async/await patterns
- Dependency injection practices
- PEP 8 compliance
JavaScript/TypeScript-Specific Considerations
When language is "javascript" or "typescript":
- Promise/async error handling
- Type safety (especially TypeScript strict mode)
- Bundle size implications
- Framework-specific patterns (React hooks, Vue composition API)
- ESLint/Prettier configuration alignment
Go-Specific Considerations
When language is "go":
- Error handling patterns (errors.Is/As)
- Interface design and composition
- Goroutine lifecycle management
- Memory allocation patterns
- Standard library usage vs. third-party
Advanced Variable Patterns
Conditional Sections Based on Variables
ADAPTIVE_TEMPLATE = CODE_REVIEW_TEMPLATE
# Add language-specific sections dynamically
if variables['language'] == 'python':
ADAPTIVE_TEMPLATE += PYTHON_SPECIFIC_SECTION
elif variables['language'] in ['javascript', 'typescript']:
ADAPTIVE_TEMPLATE += JAVASCRIPT_SPECIFIC_SECTION
# Add focus-area specific guidance
if 'security' in variables['focus_areas']:
ADAPTIVE_TEMPLATE += SECURITY_DEEP_DIVE_SECTION
if 'performance' in variables['focus_areas']:
ADAPTIVE_TEMPLATE += PERFORMANCE_DEEP_DIVE_SECTION
Nested Variable Expansion
FOCUS_AREA_DETAILS = {
'security': 'Focus on authentication, authorization, input validation, data protection, and common vulnerability patterns',
'performance': 'Focus on algorithmic complexity, memory efficiency, database optimization, caching, and resource utilization',
'style': 'Focus on naming conventions, code organization, formatting consistency, and readability',
'testing': 'Focus on test coverage, edge cases, mock quality, integration test scenarios, and test maintainability',
'maintenance': 'Focus on technical debt, refactoring opportunities, documentation, and long-term evolvability'
}
# Expand focus areas into detailed guidance
focus_details = "\n".join([FOCUS_AREA_DETAILS.get(area, area) for area in variables['focus_areas']])
template_with_details = TEMPLATE.replace("{focus_areas}", focus_details)
Integration with Development Workflows
CI/CD Pipeline Integration
# GitHub Actions example
name: Automated Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
code-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run AI Code Review
uses: ./actions/ai-code-review
with:
file_path: ${{ github.event.pull_request.changed_files[0] }}
language: ${{ fromJson('{"py": "python", "js": "javascript", "ts": "typescript"}')[github.event.pull_request.changed_files[0].split('.').pop()] }}
focus_areas: '["security", "performance", "style"]'
reviewer_role: 'senior engineer'
model: 'claude-3-5-sonnet-20241022'
Pre-commit Hook Integration
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: ai-code-review
name: AI Code Review
entry: python scripts/ai_review.py
language: system
files: '\.(py|js|ts|go|java)$'
args: ['--focus-areas', 'security,style']
PR Template Integration
<!-- PULL_REQUEST_TEMPLATE.md -->
## AI Code Review Request
**File**: `{{file_path}}`
**Language**: `{{language}}`
**Focus Areas**: {{focus_areas}}
**Reviewer Role**: `{{reviewer_role}}`
### Context for Reviewer
- **Purpose**: {{pr_purpose}}
- **Related Issue**: {{issue_link}}
- **Breaking Changes**: {{breaking_changes}}
Testing and Validation
Prompt Testing Framework
import pytest
from prompt_templates import CODE_REVIEW_TEMPLATE
class TestCodeReviewPrompt:
def test_variable_substitution(self):
prompt = CODE_REVIEW_TEMPLATE.format(
file_path="test.py",
language="python",
focus_areas="security, performance",
reviewer_role="senior engineer"
)
assert "test.py" in prompt
assert "python" in prompt
assert "security" in prompt
assert "senior engineer" in prompt
def test_required_sections_present(self):
prompt = CODE_REVIEW_TEMPLATE.format(
file_path="test.py",
language="python",
focus_areas="security",
reviewer_role="senior engineer"
)
required_sections = [
"Summary of Key Findings",
"Detailed Analysis by Focus Area",
"Security Considerations",
"Performance Considerations",
"Style and Readability Assessment",
"Specific Recommendations",
"Testing Recommendations",
"Maintenance and Future Considerations"
]
for section in required_sections:
assert section in prompt
def test_focus_areas_expanded(self):
focus = "security, performance, style"
prompt = CODE_REVIEW_TEMPLATE.format(
file_path="test.py",
language="python",
focus_areas=focus,
reviewer_role="senior engineer"
)
for area in ["security", "performance", "style"]:
assert area in prompt
def test_no_execution_instructions(self):
prompt = CODE_REVIEW_TEMPLATE.format(
file_path="test.py",
language="python",
focus_areas="security",
reviewer_role="senior engineer"
)
# Verify no dangerous instructions
dangerous = ["execute", "run", "eval", "import os", "subprocess"]
for danger in dangerous:
assert danger not in prompt.lower()
if __name__ == "__main__":
pytest.main([__file__, "-v"])
Limitations and Considerations
This template works best for structured review scenarios. For very large files, consider breaking the review into smaller segments. The template assumes the model can analyze code structure and content - testing with your specific LLM model is recommended before production use.
Known Limitations
- Context Window Limits: Large files may exceed context window; implement chunking strategies
- Language Coverage: Template optimized for common languages; may need adaptation for niche languages
- Domain Knowledge: Template provides general guidance; domain-specific reviews may need custom focus areas
- False Positives: AI reviews may flag patterns that are intentional; human review of AI output recommended
- Performance: LLM calls add latency to CI/CD; consider async processing for large PRs
Best Practices for Production Use
- Version Control: Store prompt templates in version control alongside application code
- A/B Testing: Compare different prompt versions for review quality
- Feedback Loop: Collect developer feedback on AI review usefulness
- Cost Monitoring: Track API usage and costs per review
- Audit Trail: Log all reviews for compliance and improvement tracking
Sources
- LangChain Prompts: https://python.langchain.com/docs/modules/model_io/prompts/
- OpenAI Prompt Engineering: https://platform.openai.com/docs/guides/prompt-engineering
- Code Review Best Practices: https://code-review-best-practices.example.com
- Security Code Review Guidelines: https://security-code-review.guide
- Google Code Review Guidelines: https://google.github.io/eng-practices/review/
- Microsoft Code Review Guidance: https://microsoft.github.io/code-with-engineering-playbook/code-reviews/
Tags
[[code-review]], [[prompt-template]], [[variables]], [[production-engineering]], [[ai-assisted-development]]
Categories
[[prompts]], [[ai-engineering]], [[development-tools]]
Prompt template
You are a senior code reviewer specializing in {language}.
Your task is to review the code in {file_path} with focus on these areas: {focus_areas}.
Adopt the perspective of a {reviewer_role}.
Please provide your analysis in the following structured format:
## 1. Summary of Key Findings
Provide a high-level overview of the most important issues found, their severity, and overall code quality assessment.
## 2. Detailed Analysis by Focus Area
For each focus area, provide:
- **Area**: [focus area name]
- **Findings**: Specific observations with line references where possible
- **Severity**: Critical / High / Medium / Low / Informational
- **Recommendation**: Concrete action with code example
Focus areas to cover: {focus_areas}
## 3. Security Considerations
Specifically analyze:
- Input validation and sanitization
- Authentication and authorization patterns
- Data exposure risks
- Injection vulnerabilities
- Cryptographic practices
- Dependency security
## 4. Performance Considerations
Evaluate:
- Algorithmic complexity
- Memory usage patterns
- Database query efficiency
- Caching opportunities
- Async/concurrency patterns
- Resource cleanup
## 5. Style and Readability Assessment
Review:
- Naming conventions and consistency
- Function/method size and cohesion
- Comment quality and necessity
- Error handling patterns
- Type annotations (where applicable)
- Documentation completeness
## 6. Specific Recommendations with Code Examples
For each significant issue, provide:
- **Issue**: Clear description
- **Location**: File and approximate line
- **Current Code**: Relevant snippet
- **Suggested Fix**: Improved version with explanation
- **Rationale**: Why this improves the code
## 7. Testing Recommendations
- Unit test gaps
- Integration test needs
- Edge cases to cover
## 8. Maintenance and Future Considerations
- Technical debt indicators
- Refactoring opportunities
- Scalability concerns
- Dependency update needs
---
File: {file_path}
Language: {language}
Focus Areas: {focus_areas}
Reviewer Role: {reviewer_role}