# 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.

Source: https://codeitronics.com/blogs/ai-systems-day-9-code-reviewer (published 2026-11-27)

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](https://pub-206c6a53642c4bdb86310f0393204592.r2.dev/blogs/series/30-days-of-building-ai-systems/54-ai-systems-day-9-code-reviewer.png)

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

## Table of Contents

* [What We Are Building](#what-we-are-building)
* [System Architecture](#system-architecture)
* [Key Components](#key-components)
* [Data Flow Step by Step](#data-flow-step-by-step)
* [A Minimal Tech Stack](#a-minimal-tech-stack)
* [Example Input and Output](#example-input-and-output)
* [Production Concerns](#production-concerns)
* [Extensions Worth Adding](#extensions-worth-adding)
* [Key Takeaways](#key-takeaways)
* [FAQs](#faqs)
* [Up Next](#up-next)

## 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

| Component         | Job                                                               |
| ----------------- | ----------------------------------------------------------------- |
| Git integration   | Webhook on PR events, API to read diffs and post reviews          |
| Code parser       | Diff parsing, plus tree-sitter or AST to find enclosing functions |
| LLM               | Reviews the change in context                                     |
| Rules engine      | Team conventions and best practices as explicit checks            |
| Security scanner  | SAST for known vulnerability patterns                             |
| Scoring engine    | Severity levels and an overall quality score                      |
| Comment generator | Turns findings into clear inline comments                         |
| Knowledge base    | Team 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:

```python
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

| Layer         | Choice                                             |
| ------------- | -------------------------------------------------- |
| Frontend      | Next.js, React, Tailwind, for settings and history |
| Backend       | Python with FastAPI                                |
| LLM           | A current OpenAI GPT or Anthropic Claude model     |
| Code analysis | tree-sitter or language ASTs                       |
| Embeddings    | OpenAI or Voyage, for searching the codebase       |
| Vector DB     | Pinecone or Qdrant                                 |
| Database      | PostgreSQL for reviews, findings, and feedback     |
| Integrations  | GitHub API, GitLab API                             |
| Notifications | Slack, email, Microsoft Teams                      |
| Deployment    | Docker 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](/contact).
