This prompt template is designed for automated code review workflows in production LLM applications. It provides a standardized way to analyze source code across four dimensions—correctness, performance, security, and style—and return results in strict JSON format that can be immediately parsed and acted upon by downstream systems.
In the modern software development lifecycle (SDLC), the volume of code changes often outpaces the availability of senior engineering resources. While static analysis tools (SAST) are excellent at finding known vulnerability patterns and style violations, they struggle with high-level logic errors and architectural inconsistencies. Conversely, generic LLM-based reviews often suffer from "noise"—flagging trivial style issues while missing critical race conditions or subtle logic bugs. This template bridges that gap by combining the broad reasoning capabilities of Large Language Models with the strict structural constraints required for production automation.
The template uses a disciplined variable naming convention aligned with production prompt best practices. All variables are designed to be substituted at runtime with proper validation before the API call, ensuring the model receives consistent and high-quality input.
1. Detailed Variable Taxonomy
The prompt utilizes a namespaced variable system to prevent collisions and clearly communicate the nature of the data to the model:
Input Variables (The "What")
These variables provide the core material for analysis.
code_snippet(required): The raw source code to review. To maintain a high "signal-to-noise" ratio and avoid model distraction, snippets should be limited to approximately 200 lines. For larger files, we recommend a pre-processing step that chunks the code into logical functions or classes.code_language(required): The programming language identifier. This is critical because it allows the model to shift its internal attention to language-specific anti-patterns (e.g., focusing on GIL issues in Python or memory safety in C++).
Context Variables (The "Background")
These variables provide the "why" and the "where," which are often missing from generic AI reviews.
ctx_file_path(optional): The relative path of the file. This helps the model reason about the code's architectural role (e.g., distinguishing between a low-level utility and a high-level API controller).ctx_pr_description(optional): The pull request description or JIRA ticket summary. By understanding the intent of the change, the model can distinguish between a "bug" and an intentional architectural shift.team_standards_doc(required): The team's specific coding standards. Hardcoding standards into a prompt is a maintenance nightmare; by passing them as a variable, the same prompt can be used across different teams with different style guides.
State Variables (The "History")
These variables maintain continuity across the review process.
history_previous_reviews(optional): Previous comments or iterative feedback. This prevents the model from repeating the same suggestions in subsequent versions of a PR, which is one of the primary frustrations developers have with AI assistants.
Configuration Variables (The "How")
These variables control the behavior of the model's analysis.
review_focus(required): A comma-separated list (e.g., "security,performance"). This allows the calling application to prioritize certain dimensions based on the risk profile of the change.cfg_output_format(optional, default: "json"): Ensures future-proofing for different integration targets.
2. Step-by-Step Production Integration Guide
Integrating this prompt into a production pipeline requires more than just a simple API call. We recommend the following five-step architecture:
Step 1: Context Retrieval and Sanitization
The application should query the Git API to retrieve the diff and the associated PR metadata. The code_snippet should be extracted and stripped of unnecessary boilerplate to save tokens and focus the model's attention on the modified logic.
Step 2: Model Selection and Routing
Not all code reviews require the same level of reasoning. For simple style checks, a faster model (like Haiku 5.5) may suffice. However, for security-critical components or complex logic changes, the application should route the request to a high-reasoning model (like Opus 5.5). Refer to the Claude Model Capabilities and Deployment Guide for guidance on selecting the optimal model tier based on the complexity of the task.
Step 3: Variable Injection and Validation
Before the prompt is sent, all variables must be validated. The review_focus should be checked against an allowed list to prevent prompt injection or invalid instructions. The team_standards_doc should be truncated if it exceeds a certain token limit to avoid displacing the actual code snippet in the context window.
Step 4: Structured Output Parsing and Validation
The model is instructed to return a strict JSON object. The application must use a schema validator (such as Pydantic in Python or Zod in TypeScript) to ensure the response is well-formed. If the model returns markdown fences or preamble text, a sanitization layer should strip these before parsing.
Step 5: Human-in-the-Loop Feedback
AI reviews should be treated as "suggestions." The output should be presented to the human reviewer as a series of proposed comments that they can either accept, modify, or dismiss. This feedback should then be fed back into the history_previous_reviews variable for the next iteration of the review.
3. Case Study: Detecting a Subtle Logic Bug
Consider a scenario where a developer introduces an off-by-one error in a loop that calculates order totals. A generic prompt might simply say "the loop looks incorrect." However, when using this structured template:
- The
ctx_pr_description("Fixing a bug where the last item was skipped") tells the model exactly what to look for. - The
review_focus("correctness") forces the model to ignore style nitpicks and focus on the loop boundaries. - The resulting JSON output provides the exact line number and a specific suggestion: "The loop range
range(len(items) - 1)skips the final element. Change torange(len(items))."
This level of precision is what makes the prompt viable for production use, as it provides actionable data rather than vague critiques.
4. Comparison with Alternative Review Patterns
vs. Static Analysis (SAST)
SAST tools are deterministic and fast, making them ideal for finding "known unknowns" (e.g., using a banned function). This prompt is probabilistic and reasoning-based, making it ideal for "unknown unknowns" (e.g., a logic flaw that only occurs under specific business conditions). A production-grade system should use both.
vs. LLM "Chat" Reviews
Chat-based reviews are great for developers in their IDE but are impossible to monitor or aggregate. By using a structured prompt with JSON output, organizations can track "Issue Recall" and "Noise Ratios" across their entire engineering org, enabling data-driven improvements to their coding standards.
vs. Agentic Review Loops
Some advanced systems use a "Critic" agent to review the "Reviewer" agent. While powerful, this doubles the cost and latency. This template is designed to be a high-performance, single-pass solution that provides 80% of the value at 50% of the cost.
5. Monitoring and Evaluation Framework
To ensure the prompt remains effective as the codebase evolves, teams should implement a "Golden Dataset" evaluation:
- The Dataset: Curate a set of 100 historical PRs that contain known bugs (both logic and security) and known "clean" snippets.
- Precision Tracking: Measure how many of the model's flagged issues were actually bugs. High noise leads to "AI fatigue," where developers start ignoring all AI suggestions.
- Recall Tracking: Measure how many of the known bugs the model actually found. Low recall means the AI is giving a false sense of security.
- Trigger-Based Escalation: Use the
correctness_scoreas a trigger. For example, any snippet scoring below 70 should automatically be flagged for a mandatory senior architect review, regardless of the PR size.
Conclusion
The Code Review Assistant prompt transforms code review from a manual, inconsistent process into a scalable, observable pipeline. By using a disciplined variable taxonomy and structured output, it enables a level of automation that preserves quality while accelerating delivery. When integrated with proper model routing and a human-in-the-loop feedback system, it becomes a powerful force multiplier for engineering teams.
Prompt template
## Role
You are a Senior Software Engineer performing a code review. Your task is to analyze the provided code snippet and return a structured review in the specified output format.
## Code to Review
**Language:** {{code_language}}
**File Context:** {{ctx_file_path}}
```{{code_language}}
{{code_snippet}}
```
## Review Context
**Team Standards:** {{team_standards_doc}}
**PR Description:** {{ctx_pr_description}}
**Previous Review Comments:** {{history_previous_reviews}}
## Review Instructions
Analyze the code for the following dimensions based on the `review_focus` parameter:
1. **Correctness**: Logic errors, edge cases, off-by-one errors, null pointer risks, type mismatches.
2. **Performance**: Algorithmic complexity, unnecessary allocations, database query patterns, caching opportunities.
3. **Security**: Input validation, SQL injection, XSS, path traversal, secrets handling, cryptographic misuse.
4. **Style & Maintainability**: Naming conventions, function length, cyclomatic complexity, documentation, testability.
For each issue found, provide the exact line number (1-indexed), a categorical type, a concise description, and a specific, actionable suggestion.
## Output Format
Return only a valid JSON object matching this exact schema. Do not include markdown fences, commentary, or any text outside the JSON.
```json
{
"correctness_score": integer (0-100),
"issues": [
{
"line": integer,
"type": "correctness" | "performance" | "security" | "style",
"description": "string",
"suggestion": "string"
}
],
"summary": "string (2-3 sentences max)"
}
```
**Constraints:**
- If no issues are found, return `"issues": []` and `"correctness_score": 100`.
- The `summary` must be 2-3 sentences maximum.
- Line numbers must correspond to the provided snippet (line 1 is the first line of the snippet).
- Do not hallucinate line numbers; if uncertain, omit the `line` field or use `null`.