This prompt is designed for engineering managers and tech leads who need a consistent, data-driven way to assess the review burden of incoming pull requests before assigning them to a developer. Instead of relying on gut feel or a quick glance at the line count, you feed a raw git diff into the prompt and receive a structured complexity score. The score is built from four weighted dimensions: the sheer volume of the change (lines added, modified, deleted), the breadth of the change (number of files touched), the estimated impact on cyclomatic complexity (new branches, loops, or deeply nested logic), and the degree of cross-module coupling (changes that span service boundaries, shared libraries, or database schemas). The output is a decision-support artifact that helps you prioritize which PRs need a senior reviewer, which can be safely handled by a junior developer, and which should be broken into smaller, more reviewable units.
Prompt
PR Diff Complexity Scoring Prompt

When to Use This Prompt
Quantify PR review burden before assignment by scoring raw diffs on lines changed, file count, cyclomatic complexity impact, and cross-module coupling.
The ideal integration point is your CI/CD pipeline or a code review assignment tool. When a PR is opened, your automation extracts the diff and sends it to this prompt. The resulting JSON payload—containing a numeric score, a categorical label (e.g., low, medium, high, critical), and a breakdown of contributing factors—can be written as a comment on the PR, used to route the review to the appropriate team member, or logged for retrospective analysis of your team's review load. A concrete implementation would parse the diff with a script, pass it as the [RAW_DIFF] placeholder, and validate the output against a strict JSON schema before acting on it. If the model returns a score above a configurable threshold, the harness can automatically flag the PR for a two-person review or block merging until a designated senior engineer approves.
This prompt does not replace human judgment for critical paths, security-sensitive changes, or architectural decisions. It is a triage tool, not an approval gate. Do not use it as the sole determinant for merging or rejecting code. The complexity score is a lagging indicator of review effort, not a leading indicator of code quality or correctness. For changes touching authentication, payment processing, or data migrations, always require human review regardless of the score. If the diff is too large for a single model context window, you must chunk it and aggregate the scores, which introduces its own risks of underestimation. Start by using this prompt on non-critical repositories and calibrate the thresholds against your team's actual review time data before expanding its scope.
Use Case Fit
Where the PR Diff Complexity Scoring Prompt works, where it fails, and what you must provide before running it in a pipeline.
Good Fit: Triage Before Assignment
Use when: you need to sort a batch of incoming PRs by review effort before assigning them to engineers. The prompt produces a numeric score and breakdown that helps match reviewer expertise to change complexity. Guardrail: Always pair the score with a human-readable rationale so the assigner can override the model's ranking when domain knowledge contradicts the metric.
Bad Fit: Sole Merge Gate
Avoid when: you want a single pass/fail gate that blocks merges based on a complexity threshold. The score estimates review burden, not correctness or safety. Guardrail: Use this prompt as a routing signal, not a policy engine. Merge decisions must still involve tests, linting, and human approval for critical paths.
Required Inputs
What you must provide: a unified diff with full file paths, line counts, and changed function signatures. Without file-level granularity, the model cannot estimate cross-module coupling or cyclomatic impact. Guardrail: Strip secrets and personal data before sending the diff. If the diff exceeds the model's context window, chunk it by file and aggregate scores in application code.
Operational Risk: Score Drift
What to watch: the same diff can produce different scores across model versions, temperature settings, or prompt revisions. This undermines trend analysis and SLA thresholds. Guardrail: Pin the model version and temperature. Run a weekly calibration check against a golden set of 10 scored diffs. If scores drift more than 15%, investigate before trusting pipeline decisions.
Operational Risk: Context Window Overrun
What to watch: large PRs with many files can exceed the model's context limit, causing truncated output or hallucinated file references. Guardrail: Implement a pre-flight check that counts tokens before calling the model. If the diff exceeds 80% of the context window, split by file, score individually, and compute a weighted aggregate in your application layer.
Operational Risk: Gaming the Score
What to watch: developers may learn to structure PRs to minimize the complexity score—splitting logically related changes across multiple small PRs or hiding cross-module impact through indirection. Guardrail: Cross-reference the complexity score with other signals like deployment frequency, rollback rate, and post-merge incident count. A low score paired with high post-merge churn is a leading indicator of gaming.
Copy-Ready Prompt Template
A reusable prompt for scoring PR diff complexity, ready to paste into your prompt layer with square-bracket placeholders.
This template is the core instruction set for the PR Diff Complexity Scoring Prompt. It is designed to be copied directly into your application's prompt management system, LLM playground, or orchestration layer. The prompt instructs the model to analyze a provided diff and return a structured complexity score based on multiple weighted dimensions. Every variable that changes between runs is represented as a square-bracket placeholder, such as [PR_DIFF], [REPO_CONTEXT], and [RISK_THRESHOLD]. Replace these placeholders with real data at runtime before sending the request to the model.
textYou are a code review complexity analyst. Your task is to analyze the provided pull request diff and produce a structured complexity score. Use the following dimensions, each scored from 1 (lowest) to 5 (highest), with a brief justification for the score. ## Scoring Dimensions 1. **Change Volume (lines_changed_score):** Based on total lines added, modified, and deleted. 2. **File Count (file_count_score):** Based on the number of distinct files touched. 3. **Cyclomatic Complexity Impact (cyclomatic_complexity_score):** Assess new or modified control flow structures (loops, conditionals, branches). 4. **Cross-Module Coupling (coupling_score):** Assess changes that span multiple modules, packages, or services, especially when they modify shared interfaces or data models. ## Inputs - **Diff:** [PR_DIFF] - **Repository Context (optional):** [REPO_CONTEXT] ## Output Schema Return ONLY a valid JSON object with no additional text or markdown fences. The object must conform to this structure: { "overall_complexity_score": <float between 1.0 and 5.0>, "complexity_level": "low" | "medium" | "high" | "critical", "dimension_scores": { "lines_changed_score": <integer 1-5>, "file_count_score": <integer 1-5>, "cyclomatic_complexity_score": <integer 1-5>, "coupling_score": <integer 1-5> }, "score_justifications": { "lines_changed": "<brief explanation>", "file_count": "<brief explanation>", "cyclomatic_complexity": "<brief explanation>", "coupling": "<brief explanation>" }, "review_recommendation": "<one-sentence guidance on review priority and suggested reviewer seniority>" } ## Constraints - [CONSTRAINTS] - If the diff is empty or cannot be parsed, return a JSON object with an `error` field describing the issue. - If the repository context is provided, use it to improve the accuracy of the coupling and cyclomatic complexity assessments. ## Risk Threshold - Flag any dimension with a score of 4 or higher as a potential review bottleneck. - If the overall complexity score is above [RISK_THRESHOLD], the `complexity_level` must be "high" or "critical".
To adapt this template, start by replacing [PR_DIFF] with the actual unified diff text from your version control system. The [REPO_CONTEXT] placeholder can be populated with a summary of the repository's architecture, key module boundaries, or a directory tree to improve the model's understanding of coupling. The [CONSTRAINTS] placeholder allows you to inject organization-specific rules, such as 'ignore changes to markdown files' or 'treat any change to the /auth module as high coupling.' Finally, set [RISK_THRESHOLD] to a float like 3.5 to control when a PR is automatically flagged as high complexity. After substitution, the prompt is ready for a single-turn request to a capable LLM. Always validate the output JSON against the expected schema before acting on the score.
Prompt Variables
Inputs the PR Diff Complexity Scoring Prompt needs to produce a reliable, repeatable complexity score. Validate each input before calling the model to prevent garbage-in/garbage-out scoring.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DIFF_CONTENT] | The raw unified diff text to analyze for complexity | diff --git a/src/auth/login.ts b/src/auth/login.ts @@ -12,7 +12,15 @@ ... | Must be non-empty and parseable as a unified diff. Reject if only commit messages or prose are provided. Max 50k characters to stay within context window. |
[FILE_METADATA] | Optional JSON array of file paths with their change type and language for more accurate coupling analysis | [{"path": "src/auth/login.ts", "change_type": "modified", "language": "typescript"}] | If provided, each object must have 'path' and 'change_type' fields. 'change_type' must be one of: added, modified, deleted, renamed. Null allowed if unavailable. |
[REPO_CONTEXT] | Optional description of the repository's architecture, module boundaries, and known high-risk areas to calibrate cross-module coupling scoring | Monorepo with packages: auth, billing, shared-ui. Auth and billing should not directly import from each other. | If provided, must be a string under 2000 characters. Null allowed. Used to weight cross-module imports more heavily when they violate stated boundaries. |
[COMPLEXITY_THRESHOLDS] | Optional custom thresholds for low, medium, high, and critical complexity bands to override defaults | {"low": 10, "medium": 25, "high": 50, "critical": 75} | If provided, must be a valid JSON object with integer values for all four keys. Values must be ascending: low < medium < high < critical. Null allowed to use defaults. |
[PREVIOUS_SCORE] | Optional previous complexity score for the same component or file set to detect complexity trends | {"score": 42, "date": "2025-01-15", "files_changed": 8} | If provided, must include 'score' as an integer. Used to flag increasing complexity trends. Null allowed for first-time analysis. |
[OUTPUT_SCHEMA] | The expected JSON schema for the complexity score output, used to enforce structured generation | {"type": "object", "properties": {"overall_score": {"type": "integer"}, "band": {"type": "string", "enum": ["low", "medium", "high", "critical"]}, ...}} | Must be a valid JSON Schema object. Required fields: overall_score (integer 0-100), band (enum), factors (array of objects with name, score, explanation). Reject if schema is malformed. |
[LANGUAGE_WEIGHTS] | Optional per-language complexity multipliers to adjust scoring for languages with inherently higher or lower verbosity | {"python": 0.8, "rust": 1.2, "javascript": 1.0} | If provided, must be a JSON object mapping language strings to float multipliers between 0.5 and 2.0. Null allowed to use default equal weighting. |
Implementation Harness Notes
How to wire the PR Diff Complexity Scoring Prompt into a CI/CD pipeline or review tool with validation, retries, and model selection.
The PR Diff Complexity Scoring Prompt is designed to be called programmatically within a CI/CD pipeline, a code review automation service, or a developer CLI tool. The primary integration point is immediately after a pull request is opened or updated. The application layer must fetch the raw diff (e.g., via git diff or the GitHub/GitLab API), inject it into the [DIFF] placeholder, and parse the structured JSON output. Because the output drives reviewer assignment and merge gating, the harness must validate the response schema before acting on the score. Do not use this prompt to block merges autonomously without a human-readable summary and an override mechanism.
The implementation should follow a strict validate-retry-escalate pattern. First, define a JSON schema for the expected output: a root object with required integer fields lines_changed, files_changed, complexity_score (1-10), and cross_module_coupling (1-5), plus a rationale string and a risk_factors array of strings. After receiving the model response, validate it against this schema. If validation fails, retry once with the same prompt but append the validation error to the [CONSTRAINTS] section: 'Your previous output failed JSON schema validation with the following errors: [ERROR_DETAILS]. You must output strictly valid JSON matching the schema.' If the second attempt also fails, log the failure, set a default high-complexity score (e.g., 8), and flag the PR for mandatory human review. For model choice, a fast, cost-effective model like GPT-4o-mini or Claude 3.5 Haiku is sufficient for most diffs. For very large diffs (>1000 lines), truncate to the first 1000 lines and append a note in [CONTEXT] that the diff was truncated, or switch to a model with a larger context window like Gemini 1.5 Pro.
Logging and observability are critical for tuning the scoring threshold over time. Log the raw complexity score, the PR ID, the number of files changed, the model used, and the latency for every call. Track the correlation between high complexity scores and actual review outcomes (e.g., review time, bugs found post-merge) to calibrate your scoring thresholds. Avoid wiring the score directly to a merge block without a grace period. Start by using the score to add a label (e.g., complexity:high) and recommend a senior reviewer. Only after validating the scoring against your team's historical data should you consider gating merges on a maximum complexity threshold.
Expected Output Contract
Defines the required JSON output structure for the PR Diff Complexity Scoring Prompt. Use this contract to validate the model's response before the score is used for review assignment or pipeline gating.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
complexity_score | number (0.0-10.0) | Must be a float within the inclusive range 0.0 to 10.0. Parse check: JSON number type. | |
score_breakdown | object | Must contain sub-fields: lines_changed_score, file_count_score, cyclomatic_impact_score, coupling_score. Each must be a number 0.0-10.0. | |
lines_changed_score | number (0.0-10.0) | Must be present inside score_breakdown. Scale should reflect the total lines added + deleted relative to typical PR size. | |
file_count_score | number (0.0-10.0) | Must be present inside score_breakdown. Scale should reflect the number of distinct files modified. | |
cyclomatic_impact_score | number (0.0-10.0) | Must be present inside score_breakdown. Should estimate the introduction of new branches, loops, or conditionals. | |
coupling_score | number (0.0-10.0) | Must be present inside score_breakdown. Should reflect changes spanning multiple modules, services, or directories. | |
risk_factors | array of strings | Must be a JSON array. Each element must be a non-empty string describing a specific risk (e.g., 'Modifies shared authentication module'). | |
review_recommendation | string (enum) | Must be one of: 'LIGHTWEIGHT', 'STANDARD', 'DEEP_REVIEW', 'SPLIT_PR'. Schema check: strict enum match. | |
summary | string | A single-sentence justification for the score and recommendation. Must not be empty. |
Common Failure Modes
Complexity scoring prompts fail in predictable ways when the diff is large, the model loses count, or the output drifts from the expected schema. These cards cover the most common failure modes and how to guard against them before the prompt reaches production.
Token Window Overflow on Large Diffs
What to watch: The raw diff exceeds the model's context window, causing silent truncation. The model scores only a partial diff, producing a misleadingly low complexity score. Guardrail: Pre-process the diff to extract file names, change counts, and chunk summaries. Pass aggregated statistics plus a sampled diff subset rather than the full raw diff. Add a pre-flight token count check and reject diffs above a safe threshold with a clear error message.
Hallucinated Line Counts and File Counts
What to watch: The model generates plausible but incorrect numbers for lines changed, files touched, or cyclomatic complexity deltas. These fabricated metrics then feed into the final score, making it unreliable. Guardrail: Compute lines changed, file count, and other quantifiable metrics in application code before the prompt runs. Pass these as pre-computed facts in the prompt context and instruct the model to use them verbatim rather than recalculating.
Score Drift Toward the Middle of the Scale
What to watch: The model defaults to mid-range complexity scores (e.g., 5-7 on a 1-10 scale) for ambiguous or unfamiliar changes, masking genuinely high-risk or trivial diffs. Guardrail: Anchor the scoring rubric with concrete examples at each tier. Include few-shot examples of diffs that score 1-2, 5-6, and 9-10. Require the model to justify the score with specific evidence from the diff before emitting the final number.
Cross-Module Coupling Overestimation
What to watch: The model treats any import or reference across module boundaries as high coupling, inflating the complexity score for routine cross-module usage. Guardrail: Define coupling tiers in the prompt (e.g., utility import vs. circular dependency vs. shared mutable state). Provide a pre-computed module dependency graph and instruct the model to classify coupling severity using those tiers rather than counting all cross-module references equally.
Schema Non-Compliance in Structured Output
What to watch: The model returns a complexity score but omits required fields like breakdown, risk_factors, or review_priority. Downstream tooling that expects a strict JSON schema breaks. Guardrail: Use structured output mode with a strict JSON schema. Add a post-generation validation step that checks for all required fields and retries with a repair prompt if the schema is violated. Log schema failures for monitoring.
Ignoring Deleted Code in Complexity Assessment
What to watch: The model focuses only on added lines and ignores the risk of deletions that remove error handling, validation, or safety checks. A diff that deletes critical guards scores low despite high risk. Guardrail: Explicitly instruct the model to analyze both additions and deletions. Include a dedicated deletion_risk field in the output schema. Provide examples where deletions increase risk despite reducing line count.
Evaluation Rubric
Criteria for evaluating the PR Diff Complexity Scoring Prompt output before integrating into a review assignment pipeline. Each criterion targets a specific failure mode common in complexity estimation.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Score Boundedness | Output score is an integer between 1 and 100 inclusive. | Score is null, negative, zero, exceeds 100, or is a float. | Parse output; assert 1 <= score <= 100 and score % 1 == 0. |
Factor Attribution | Each of the 4 factors (lines, files, cyclomatic, coupling) has a non-null sub-score and a 1-sentence justification. | Missing sub-score, null justification, or justification that repeats the factor name without evidence. | Schema validation: check for 4 keys in |
File Count Accuracy | Reported file count matches the number of distinct file headers in the [DIFF] input. | Count is off by more than 1, or counts non-code files (e.g., lock files) when instructed to exclude them. | Parse diff for |
Cross-Module Detection | Coupling score > 20 only when imports or function calls cross top-level directories; otherwise <= 20. | High coupling score for a single-module change, or zero score when cross-module imports are present. | Grep diff for import/call patterns; assert coupling score directionally matches cross-directory references. |
Cyclomatic Complexity Signal | Cyclomatic score > 30 when diff adds 3+ new branching statements (if/for/while/case); <= 10 when none added. | High score with no new branches, or low score when multiple nested conditionals are added. | Count branching keywords in added lines; assert score directionally matches count. |
Output Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] exactly, with no extra or missing top-level keys. | Missing | JSON.parse() in test harness; validate against JSON Schema with |
Summary Actionability |
| Summary is generic ('This is a complex PR'), missing the score number, or exceeds 5 sentences. | Check string length and presence of score integer in summary text; assert sentence count between 2 and 4. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add a strict JSON output schema with required fields: complexity_score, lines_changed, files_touched, cyclomatic_impact, cross_module_coupling, risk_factors[], and review_priority. Include a system instruction that enforces numeric ranges and requires evidence for each factor.
Add a validation layer that:
- Rejects outputs missing required fields
- Checks score ranges (1-10)
- Verifies
risk_factorsentries reference specific files or functions - Retries with error context on validation failure
Watch for
- Silent format drift when the model returns markdown-wrapped JSON
- Missing
cross_module_couplingon single-file diffs (should be 0, not absent) - Review priority mismatches where a high complexity score gets a low priority label

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us