Skip to content

Founder-led. Limited engagements.Talk to Us →

Part 9 of 30 · 30 Days of Building AI Systems

AI Code Reviewer System | 30 Days of Building AI Systems, Day 9

Build an AI code reviewer: PR webhooks, diff and context building, SAST plus LLM review, severity scoring, and inline GitHub comments without the noise.

By 7 min readAI Systems · Code Review · Developer Tools · LLM Engineering
AI Code Reviewer System | 30 Days of Building AI Systems, Day 9

Yesterday we built a data analyst that computes with code and explains with the model. Today we build an AI code reviewer: a system that picks up every pull request, reads the diff with enough repository context to understand it, finds bugs, risky patterns, and security issues, and posts focused review comments back to the PR.

AI Code Reviewer System — CodeITronics infographic

Save this sheet. The rest of this note walks through it section by section.

What We Are Building

The reviewer analyzes code changes in pull requests, detects bugs and issues, suggests improvements, enforces best practices, checks for security vulnerabilities, explains its findings clearly, scores code quality, and integrates with GitHub or GitLab.

It serves development teams, open source maintainers, enterprises running CI/CD, and anyone responsible for code quality, governance, security, or mentoring junior engineers.

The goal is to act like a careful senior engineer, not a linter with opinions. A senior reviewer reads the change in context, comments on what matters, and stays quiet about the rest. That last part is the hardest thing to build. A reviewer that leaves twenty comments per PR gets muted within a week.

System Architecture

code source: GitHub / GitLab PR (webhook)
  -> code extraction: diff, changed files, metadata
  -> context builder: surrounding code, dependencies, coding standards
  -> AI review engine: LLM + rules engine + SAST
  -> results & scoring: severity, dedupe, quality score
  -> report & comments: inline comments + summary
  -> publish review to PR / MR
  -> developer fixes, pushes, re-review

The review engine has three parts, and they're there for a reason. Linters and static analysis security testing (SAST) tools are deterministic, fast, and cheap, and they catch known patterns reliably. The LLM catches what rules can't express: logic errors, unclear naming, a missing edge case, code that contradicts the PR description. Run the rules first and give their findings to the model so it doesn't spend effort rediscovering them.

Key Components

ComponentJob
Git integrationWebhook on PR events, API to read diffs and post reviews
Code parserDiff parsing, plus tree-sitter or AST to find enclosing functions
LLMReviews the change in context
Rules engineTeam conventions and best practices as explicit checks
Security scannerSAST for known vulnerability patterns
Scoring engineSeverity levels and an overall quality score
Comment generatorTurns findings into clear inline comments
Knowledge baseTeam docs, patterns, and past review decisions

Data Flow Step by Step

  1. A developer pushes code or opens a pull request.
  2. The webhook fires, and the system fetches the diff and changed files.
  3. The parser maps each changed hunk to its enclosing function or class, and the context builder adds related code and the team's standards.
  4. Rules and SAST run, then the LLM reviews with their findings in hand.
  5. Findings are deduplicated, ranked by severity, and capped.
  6. Inline comments and a summary are posted to the PR.
  7. The developer fixes issues, pushes, and the review runs again on the new diff only.

Posting the review is one API call. On GitHub, a review with inline comments looks like this:

import requests

def post_review(owner, repo, pr_number, commit_sha, findings, token):
    comments = [
        {"path": f["path"], "line": f["line"], "side": "RIGHT", "body": f["message"]}
        for f in findings
    ]
    resp = requests.post(
        f"https://api.github.com/repos/{owner}/{repo}/pulls/{pr_number}/reviews",
        headers={"Authorization": f"Bearer {token}",
                 "Accept": "application/vnd.github+json"},
        json={"commit_id": commit_sha, "event": "COMMENT",
              "body": summary(findings), "comments": comments},
        timeout=30,
    )
    resp.raise_for_status()

Use "event": "COMMENT" rather than requesting changes. An automated reviewer should inform the human reviewers, not block merges on its own judgment.

A Minimal Tech Stack

LayerChoice
FrontendNext.js, React, Tailwind, for settings and history
BackendPython with FastAPI
LLMA current OpenAI GPT or Anthropic Claude model
Code analysistree-sitter or language ASTs
EmbeddingsOpenAI or Voyage, for searching the codebase
Vector DBPinecone or Qdrant
DatabasePostgreSQL for reviews, findings, and feedback
IntegrationsGitHub API, GitLab API
NotificationsSlack, email, Microsoft Teams
DeploymentDocker on AWS, or Vercel for the UI

Example Input and Output

The sheet's input is a small Python diff in utils.py: add(a, b) changes from return a + b to assigning result = a + b and then returning result. The context says Python 3.11, PEP 8, and the project guidelines.

The review scores it 87 out of 100, "Good", with two issues:

  • Redundant temporary variable (minor). result adds a line without adding clarity, so returning the expression directly is simpler.
  • Missing type hints (info). Adding parameter and return types improves readability and lets type checkers help.

Then come the suggestions: add a docstring and add a unit test for edge cases. The summary notes a solid change with minor improvements, one file reviewed, three lines added, two removed.

That's the right tone for a small change: short, ranked, and honest that nothing here is serious.

Production Concerns

Evaluation

Replay the reviewer on a set of merged PRs where you know what human reviewers flagged, plus PRs that later caused bugs. Measure how many real issues it caught and, just as important, what share of its comments developers judged useful. Add a thumbs up or down to every comment and track the rate per rule and per category.

Cost

Cost scales with diff size times context size. Skip generated files, lockfiles, and vendored code. On re-pushes, review only the new commits. Route small PRs to a cheaper model and keep the stronger model for large or security-sensitive changes.

Failure Modes

  • Noise. Too many low-value comments, and developers stop reading. Cap comments per PR, drop style nits that a formatter could fix, and move anything below a severity threshold into the summary instead of inline.
  • Missing context. The model flags a "bug" that a helper three files away already handles. Better context building, such as callers, callees, and types, fixes more of this than a bigger model.
  • Wrong line numbers. Comments land on the wrong line when the diff mapping is off. Map findings to diff positions in code and validate them before posting.
  • Secrets and IP. Code goes to a model provider. Check data retention terms, and scan for secrets before sending anything.
  • Prompt injection in code. A comment in the diff can contain instructions to the reviewer. Treat code as data, and never let review output trigger merges or deployments.

Extensions Worth Adding

From the sheet: auto-fix suggestions, chat with your codebase, unit test generation, performance analysis, Jira or Linear integration, and a codebase knowledge graph. The knowledge graph quietly improves everything else, because "who calls this function?" is exactly the context the reviewer is usually missing.

Key Takeaways

  • Combine deterministic rules and SAST with LLM review. Each catches what the other misses.
  • Context building (enclosing functions, callers, types, standards) matters more than model choice.
  • Optimize for signal: cap comments, rank by severity, and measure how useful each one is.
  • Post as comments, not blocking reviews. Humans own the merge decision.

FAQs

Will an AI reviewer replace human code review?

No. It handles the first pass, catching obvious bugs, missing tests, and known risks, so human reviewers can spend their time on design and intent.

Should the quality score gate merges?

Not on its own. Scores are useful for trends across a repo. Gate merges on deterministic checks like tests, linters, and SAST, and leave judgment calls to people.

How do I teach it our team's conventions?

Write them down as explicit rules where you can, and put the rest in a short standards document that the context builder always includes. Review rejected comments monthly and turn repeated patterns into rules.

Up Next

Tomorrow is Day 10, the AI Document Summarizer System. It reads full documents end to end and produces executive summaries, key points, and answers, using summarization strategies that hold up past a few pages. If you want an AI reviewer wired into your own pipeline, get in touch.

Keep reading

AI Data Analyst System | 30 Days of Building AI Systems, Day 8

Build an AI data analyst: data profiling, LLM-written pandas code run in a sandbox, charts, and narratives where every number is computed rather than guessed.

AI Voice Assistant System | 30 Days of Building AI Systems, Day 7

Build an AI voice assistant: streaming speech to text, an LLM with tool calling, and text to speech, with a latency budget, barge-in, and real failure modes.

AI Email Assistant | 30 Days of Building AI Systems, Day 5

Build an AI email assistant that triages your inbox, summarizes threads, and drafts replies in your tone, with OAuth scoping and prompt injection defenses.

Subscribe to the edition

One useful systems note a week from real Salesforce and automation builds. Unsubscribe in one click.

Letters

Letters to the editor

No letters yet. Questions and counterpoints are welcome.