Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

AI Code Review CLI

A production-quality command-line tool that reviews local source code files or current Git diff changes using Google's Gemini API and returns structured, Pydantic-validated feedback.

Intentionally designed as a lightweight, clean, and highly robust CLI portfolio project demonstrating modern AI engineering patterns.


Overview

The AI Code Review CLI helps engineers get immediate feedback on code modifications or source files. It reads the target content, prompts Google's Gemini API, enforces a structured JSON response schema matching a strict Pydantic model definition, and prints a formatted issue analysis table in the terminal using Rich.


Features

  • Dual Input Modes: Review a single source code file or run reviews directly on staged/unstaged changes compared to HEAD (Git diff analysis).
  • Enforced JSON Output: Configures the official Google GenAI SDK to strictly guarantee structured JSON matching our Pydantic schema (no raw conversational headers, code blocks, or trailing descriptions).
  • Robust JSON Validation: Validates all JSON output properties using Pydantic, incorporating defensive validation fallbacks for alternative array structures.
  • Rich Terminal Presentation: Displays identified code issues in a clean terminal table with color-coded severity levels (HIGH in red, MEDIUM in yellow, LOW in green).
  • Graceful Error Handling: Catches missing API keys, non-existent directories, empty repositories, API failures, and malformed JSON payloads, exiting cleanly with descriptive errors without dumping stack tracebacks.

Project Architecture

AI Code Review CLI/
│
├── .env.example                # Environmental template variables
├── requirements.txt            # Package dependencies
├── main.py                     # Root CLI entrypoint wrapper
│
├── ai_code_reviewer/           # Core library package
│   ├── __init__.py             # Package version
│   ├── main.py                 # Argparse routing, Rich rendering flow
│   ├── git_helper.py           # Git command wrapper & File reader
│   ├── reviewer.py             # Google GenAI API client invocation
│   └── models.py               # Pydantic schema validation structures
│
└── samples/                    # Sample materials
    ├── sample_input.py         # Buggy Python file for testing reviews
    └── malformed_response.json # Example malformed JSON for parser testing

Module Responsibilities

  • git_helper.py: Executes the shell subprocess commands to fetch repository diff states and handles filesystem reads. It is isolated from API or rendering concerns.
  • models.py: Holds validation structures (ReviewFinding & ReviewReport). It defines types, literals, and schema metadata.
  • reviewer.py: Integrates the Gemini API, prompt configurations, JSON loaders, and Pydantic validation checks.
  • main.py (CLI Package): Orchestrates argparse, parses CLI flags, displays console status bars, and renders the Rich table layout.

Installation

Prerequisites

  • Python 3.11+
  • Git CLI (available in system path)
  • Gemini API Key

Step-by-Step Setup

  1. Clone & Navigate

    git clone <repository-url>
    cd "AI Code Review CLI"
  2. Initialize Virtual Environment

    python -m venv .venv
    .venv\Scripts\activate      # Windows
    source .venv/bin/activate    # macOS/Linux
  3. Install Dependencies

    pip install -r requirements.txt
  4. Environment Configuration Copy the example environment template and add your Gemini API key:

    copy .env.example .env      # Windows
    cp .env.example .env        # macOS/Linux

    Open .env and set:

    GEMINI_API_KEY=your_actual_gemini_api_key_here

Usage

Ensure your virtual environment is active before running commands.

1. Review a Specific File

Execute the tool on any local file path:

python main.py samples/sample_input.py

2. Review Current Git Changes

Run a review over all staged and unstaged edits compared to your last commit (HEAD):

python main.py --diff

Example Output

Code review completed: Found 3 issues:

+-----------------------------------------------------------------------------+
| Severity     | Category     |   Line | Issue             | Suggestion       |
|--------------+--------------+--------+-------------------+------------------|
| HIGH         | Security     |     12 | SQL injection     | Use              |
|              |              |        | vulnerability     | parameterized    |
|              |              |        | found in          | SQL queries      |
|              |              |        | execute_user_que  | instead of       |
|              |              |        |                   | f-strings.       |
| MEDIUM       | Bug          |      5 | Potential         | Add a check: if  |
|              |              |        | ZeroDivisionError | not numbers:     |
|              |              |        | if input list is  | return 0.0       |
|              |              |        | empty.            |                  |
| LOW          | Style        |      1 | Unused imports:   | Remove unused    |
|              |              |        | os, sys.          | import           |
|              |              |        |                   | statements.      |
+-----------------------------------------------------------------------------+

Technical Notes

Prompt Engineering Design

To prevent Gemini from returning standard markdown syntax or conversational text, we employ a dual-constraint strategy:

  1. System Instruction: Informs the model it is a critical code reviewer and explicitly restricts output to valid JSON adhering to our Pydantic model structure. It states: "You must respond ONLY with a JSON object conforming to the specified JSON schema. Do not include markdown code fences (like \``json)..."`
  2. SDK Native Validation: When invoking client.models.generate_content, we supply the response_schema parameter mapped to our Pydantic wrapper schema ReviewReport and configure response_mime_type="application/json". The Gemini API uses these instructions to strictly constrain output formats at the model's generation layer.
  3. Temperature Tuning: Setting temperature=0.0 ensures the model output remains deterministic and closely aligned with the requested types.

JSON Validation Architecture

Large Language Models (LLMs) can occasionally fail structure constraints. To guarantee that our tool never crashes and never presents raw/unparsed text to users, we built a defensive parsing pathway:

  • Pre-Cleanups: The parser detects and strips any markdown code blocks (```json ... ```) if they are returned by the API.
  • Wrapper Parsing (Case A): First attempts validation against the primary ReviewReport schema wrapper (which expects { "findings": [...] }).
  • Array Parsing Fallback (Case B): If the API skips the wrapper and emits a root array [...], the code falls back to TypeAdapter(list[ReviewFinding]) to parse findings directly.
  • Exception Boundary: If validation fails completely, the error is caught, formatted cleanly as a console error, and the program exits gracefully with status code 1.

Future Improvements

  1. GitHub Actions Integration: Trigger code reviews automatically on incoming Pull Requests.
  2. Custom Review Guidelines: Support passing custom system prompts or rules files (e.g. style guides) to configure the reviewer's focus area.
  3. Cost & Token Optimizations: Expose flags to configure max review context lengths, keeping API tokens minimal.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages