Most teams treat AI code review as a browser tab. Someone pastes a diff into a chat window, asks “anything wrong here?”, skims the answer, and moves on. That is fine for a one-off, but it means the review only happens when a human remembers to do it, and it happens after the PR is already open and someone has already been asked to look.

The better place for an LLM reviewer is the CI pipeline. Every pull request already triggers a run. Tests execute, linters execute, type checkers execute. Adding a model that reads the diff and posts its findings as a comment costs a few seconds of wall-clock time and, in my experience, somewhere between ten and sixty cents per PR. By the time a human opens the review, the mechanical issues are already flagged inline. The human spends their attention on the things a model is bad at: architecture, intent, whether the feature should exist at all.

This post is the end-to-end build. The naive version first, where it breaks, and the version that actually survives contact with a busy team.

The Naive Version

The obvious implementation is a GitHub Action that fires on pull_request, grabs the whole repository, stuffs it into a prompt, and asks the model to review it.

name: AI Review (naive)
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: |
          FILES=$(find . -name '*.py' | xargs cat)
          curl https://api.anthropic.com/v1/messages \
            -H "x-api-key: $ANTHROPIC_API_KEY" \
            -H "anthropic-version: 2023-06-01" \
            -d "{\"model\":\"claude-sonnet-5-5\",
                 \"max_tokens\":4096,
                 \"messages\":[{\"role\":\"user\",
                 \"content\":\"Review this code: $FILES\"}]}"

This breaks almost immediately, and it breaks in three different ways.

It reviews code nobody changed. The PR touched four files. The model just read four hundred. It will confidently tell you that a helper function written two years ago has a subtle bug, which may even be true, but it is not what this PR is about and it is not what the author can act on right now.

The cost scales with the repo, not the change. A ten-line PR against a large codebase sends the entire codebase on every push. Push three times to fix a typo and you have paid to review the whole repo three times. This is where “under a dollar per PR” quietly becomes “twelve dollars per PR.”

The output is a wall of text. Dumping a thousand tokens of prose into a shell comment, or worse, into a single PR comment, is useless. Nobody reads it. The signal that mattered is buried under style nitpicks and restatements of what the code obviously does.

The fix for all three is the same idea: review the diff, not the repository.

Diff-Scoped Review

A pull request is fundamentally a diff. That is the unit of change, and it is the unit the review should operate on. GitHub gives you the diff for free through the API, and git gives it to you locally in CI.

          main (base)
             |
             |   git diff origin/main...HEAD
             v
   +-------------------------+
   |   unified diff only     |   <- this is the review input
   |   ~200 lines typical    |
   +-------------------------+
             |
             v
       LLM reviewer  ---->  structured findings  ---->  inline PR comments

Scoping to the diff solves the cost problem outright. A typical PR diff is a couple hundred lines. At current Sonnet-class pricing, a few hundred lines of input plus a structured response lands well under a dollar, usually under thirty cents. The cost now tracks the size of the change, which is exactly what you want.

It also solves relevance. The model can only comment on lines that changed, because those are the only lines it can see. There is a real tradeoff here: the model loses context about the rest of the codebase. A function call looks fine in the diff but passes an argument in the wrong order relative to a definition the model never saw. In practice this is an acceptable loss. The diff carries enough local context (the surrounding lines in each hunk) to catch the overwhelming majority of what matters: logic errors inside the change, missing error handling on new code paths, obvious injection and secret-handling problems, and the kind of off-by-one and null-check mistakes that live entirely within a few lines.

If you want to buy back some of that lost context cheaply, include the full text of each changed file (not the whole repo) alongside the diff. The diff tells the model what changed; the file gives it the local surroundings. That is a middle ground that stays well inside the budget.

The Prompt That Produces Usable Output

The single biggest lever on review quality is not the model. It is forcing the output into a structure you can route. Free-form prose is where good reviews go to die. Ask for JSON.

SYSTEM = """You are a code reviewer running inside a CI pipeline.
You are reviewing a single pull request diff, not an entire codebase.

Report ONLY issues that are introduced or made worse by this diff.
Do not comment on code that was not changed.
Do not report style, formatting, or naming preferences.
Do not restate what the code does.

Severity definitions:
- blocker: a bug the diff introduces that will cause incorrect
  behavior, a crash, data loss, or a security vulnerability.
- warning: a likely problem - missing error handling, an
  unhandled edge case, a race condition - that a reasonable
  reviewer would want addressed.
- note: a genuine correctness or clarity concern that is minor.

If you are not confident an issue is real, do not report it.
An empty findings list is a valid and common answer.

Respond with JSON only:
{
  "findings": [
    {
      "file": "path/to/file.py",
      "line": 42,
      "severity": "blocker|warning|note",
      "title": "short imperative summary",
      "detail": "what is wrong and why, 1-2 sentences",
      "category": "logic|error-handling|security|correctness"
    }
  ]
}
"""

Three things in that prompt are doing most of the work.

The first is the explicit instruction that an empty list is valid. Models are eager to please. If you ask “what is wrong with this code,” they will find something wrong, even when nothing is. Telling the model up front that “no findings” is a normal, expected answer is the difference between a reviewer you trust and one that cries wolf on every PR.

The second is the severity rubric. Without defined levels, everything comes back as equally urgent. With them, you get a signal you can act on programmatically. Blockers go to the top. Notes get collapsed.

The third is the hard ban on style, formatting, and naming. This is the noise suppression that makes the whole thing tolerable, and it deserves its own section.

Killing the Noise

The reason most teams turn off AI review after a week is noise. The model comments that a variable could be named better, that this line is over eighty characters, that a comment would be nice here. Each one is individually harmless and collectively fatal. Developers learn that the bot’s comments are not worth reading, and once they learn that, the real findings get ignored along with the fake ones.

Noise suppression happens at three layers, and you want all three.

At the prompt layer, you ban the categories outright, as above. This is the cheapest filter and it removes the bulk of the junk. You already run a linter and a formatter. Those tools are deterministic, free, and correct. The model should never be doing their job.

At the parsing layer, you drop findings by severity and category before they ever reach the PR. This is a safety net for when the model ignores the prompt, which it occasionally will.

ALLOWED = {"logic", "error-handling", "security", "correctness"}

def filter_findings(findings, min_severity="warning"):
    order = {"note": 0, "warning": 1, "blocker": 2}
    threshold = order[min_severity]
    kept = []
    for f in findings:
        if f.get("category") not in ALLOWED:
            continue
        if order.get(f.get("severity"), 0) < threshold:
            continue
        kept.append(f)
    return kept

Set the threshold per branch if you like. On a hotfix branch you might only want blockers. On a feature branch, warnings and up.

At the posting layer, you cap the number of comments. A review that posts twenty inline comments is a review nobody will read. Post the top five or six by severity, and roll the rest into a collapsed summary. A hard cap also protects you from a pathological diff (a large generated file, a vendored dependency) producing a hundred findings.

The table below is the rough division of labor I have landed on. The point is that the AI reviewer should stay in its lane and leave the deterministic checks to deterministic tools.

ConcernWho should catch itWhy
Formatting, line lengthFormatter (ruff, prettier)Deterministic, instant, free
Naming conventions, importsLinterDeterministic, configurable
Type mismatchesType checkerSound, no false positives
Logic errors in the diffAI reviewerNeeds to understand intent
Missing error handlingAI reviewerNeeds to reason about paths
Injection, secret handlingAI reviewer plus SASTNeeds context SAST lacks
Architecture, should-this-existHumanJudgment, taste, product sense

The Full GitHub Action

Here is the version that actually ships. It fetches the diff scoped to the base branch, sends it with the structured prompt, filters the findings, and posts them as inline review comments. The key detail at the end: it never sets a failing exit code.

name: AI Code Review
on:
  pull_request:
    types: [opened, synchronize, reopened]

permissions:
  contents: read
  pull-requests: write

jobs:
  ai-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - run: pip install anthropic

      - name: Run AI review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
          HEAD_SHA: ${{ github.event.pull_request.head.sha }}
          REPO: ${{ github.repository }}
        run: python .github/scripts/ai_review.py

And the script. It is deliberately boring. The cleverness lives in the prompt, not the plumbing.

import json
import os
import subprocess
import urllib.request

from anthropic import Anthropic

MODEL = "claude-sonnet-5-5"
MAX_COMMENTS = 6

def changed_diff(base, head):
    # Scope to the merge base so we only see this PR's changes,
    # not everything that landed on main since the branch forked.
    return subprocess.run(
        ["git", "diff", f"{base}...{head}", "--unified=3"],
        capture_output=True, text=True, check=True,
    ).stdout

def review(diff):
    client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    resp = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        system=SYSTEM,  # the prompt from the earlier section
        messages=[{
            "role": "user",
            "content": f"Review this pull request diff:\n\n{diff}",
        }],
    )
    text = resp.content[0].text
    # The model returns JSON; be defensive about stray prose.
    start, end = text.find("{"), text.rfind("}")
    return json.loads(text[start:end + 1])["findings"]

def post_comment(body):
    repo = os.environ["REPO"]
    pr = os.environ["PR_NUMBER"]
    url = f"https://api.github.com/repos/{repo}/issues/{pr}/comments"
    data = json.dumps({"body": body}).encode()
    req = urllib.request.Request(url, data=data, method="POST")
    req.add_header("Authorization", f"Bearer {os.environ['GITHUB_TOKEN']}")
    req.add_header("Accept", "application/vnd.github+json")
    urllib.request.urlopen(req)

def format_comment(findings):
    icon = {"blocker": "🔴", "warning": "🟡", "note": "🔵"}
    lines = ["## AI Review", "",
             "_Automated. Advisory only - this does not block merge._", ""]
    for f in findings[:MAX_COMMENTS]:
        lines.append(
            f"{icon.get(f['severity'], '')} **{f['title']}** "
            f"(`{f['file']}:{f['line']}`)\n\n  {f['detail']}\n"
        )
    extra = len(findings) - MAX_COMMENTS
    if extra > 0:
        lines.append(f"\n_{extra} lower-severity findings suppressed._")
    return "\n".join(lines)

def main():
    diff = changed_diff(os.environ["BASE_SHA"], os.environ["HEAD_SHA"])
    if not diff.strip():
        return
    findings = filter_findings(review(diff), min_severity="warning")
    if not findings:
        print("No findings above threshold.")
        return
    findings.sort(
        key=lambda f: {"blocker": 2, "warning": 1, "note": 0}[f["severity"]],
        reverse=True,
    )
    post_comment(format_comment(findings))
    # Note: we exit 0 regardless of findings. See below.

if __name__ == "__main__":
    main()

For true inline comments anchored to specific lines, use the pulls review API (/pulls/{n}/reviews) with a comments array carrying path and line. I have shown the simpler issue-comment version to keep the plumbing readable; the line-anchored version is the same data shaped differently.

Why It Must Not Block Merges

This is the part people get wrong, and it is the most important decision in the whole design.

The temptation is to make the job fail when it finds a blocker. It feels rigorous. It feels like you are taking quality seriously. It is a mistake, and it will get the entire system switched off within a month.

LLM reviewers are probabilistic. They produce false positives. Not often, if your prompt is tight, but often enough that it is a certainty some of them will be wrong. The moment a false positive stands between a developer and a merge, you have created an adversary. Picture the on-call engineer with a one-line production hotfix at 2 a.m., blocked by a bot insisting on a null check for a value that provably cannot be null. They will not thank the bot. They will find the setting that disables it, and they will turn it off for everyone, forever. One bad block poisons the well for every good comment the thing would ever have made.

There is a deeper reason too. A blocking gate implies the model’s judgment is authoritative. It is not. It is advisory. The human reviewer and the author are the authority. The AI’s job is to surface candidates for their attention, not to render verdicts. Keeping it non-blocking keeps the authority where it belongs and keeps the tool in a role it can actually fill well.

So the review posts comments and always exits zero. Developers read the comments because the comments are usually right and never in their way. Trust accumulates instead of eroding. The findings get acted on far more often than a blocking gate would ever achieve, precisely because nobody is fighting the tool.

Your deterministic checks are where blocking belongs. Tests failing should block. Type errors should block. A linter violation can block. Those are sound: when they fail, something is genuinely wrong, with no probabilistic hand-waving. The AI reviewer lives in the advisory layer, next to them but never in the gate.

What Works and What Does Not

What works, consistently: catching missing error handling on new code paths, spotting logic errors that live inside the diff, flagging obvious injection and secret-leak patterns, and surfacing the null-check and off-by-one class of bug that humans skim right past. For a few tens of cents per PR, it reliably removes a layer of mechanical mistakes before a human spends a minute on the change. The time saved is real and it compounds across a team.

What does not work: anything requiring whole-repo context the diff cannot carry, judgments about whether an abstraction is right, and anything to do with product intent. The model does not know your system. It knows the two hundred lines in front of it. Asking it to reason about architecture from a diff is asking for confident nonsense.

What to actually do: scope to the diff, force structured JSON output, suppress style and formatting ruthlessly at all three layers, cap the comment count, and keep it non-blocking without exception. Start with a high severity threshold - blockers only - and lower it as the team builds trust in the output. Run it alongside your existing linters and type checkers, not instead of them. Treat it as a fast, cheap first pass that makes human review sharper, and never as a replacement for the human. Get those boundaries right and it is one of the highest-return things you can add to a pipeline. Get them wrong, especially the blocking part, and it is the first thing your team will disable.