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.
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.
- 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 (
HIGHin red,MEDIUMin yellow,LOWin 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.
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
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.
- Python 3.11+
- Git CLI (available in system path)
- Gemini API Key
-
Clone & Navigate
git clone <repository-url> cd "AI Code Review CLI"
-
Initialize Virtual Environment
python -m venv .venv .venv\Scripts\activate # Windows source .venv/bin/activate # macOS/Linux
-
Install Dependencies
pip install -r requirements.txt
-
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
.envand set:GEMINI_API_KEY=your_actual_gemini_api_key_here
Ensure your virtual environment is active before running commands.
Execute the tool on any local file path:
python main.py samples/sample_input.pyRun a review over all staged and unstaged edits compared to your last commit (HEAD):
python main.py --diffCode 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. |
+-----------------------------------------------------------------------------+
To prevent Gemini from returning standard markdown syntax or conversational text, we employ a dual-constraint strategy:
- 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)..."` - SDK Native Validation: When invoking
client.models.generate_content, we supply theresponse_schemaparameter mapped to our Pydantic wrapper schemaReviewReportand configureresponse_mime_type="application/json". The Gemini API uses these instructions to strictly constrain output formats at the model's generation layer. - Temperature Tuning: Setting
temperature=0.0ensures the model output remains deterministic and closely aligned with the requested types.
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
ReviewReportschema wrapper (which expects{ "findings": [...] }). - Array Parsing Fallback (Case B): If the API skips the wrapper and emits a root array
[...], the code falls back toTypeAdapter(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.
- GitHub Actions Integration: Trigger code reviews automatically on incoming Pull Requests.
- Custom Review Guidelines: Support passing custom system prompts or rules files (e.g. style guides) to configure the reviewer's focus area.
- Cost & Token Optimizations: Expose flags to configure max review context lengths, keeping API tokens minimal.