An automated code review system that accepts a GitHub repository and pull request number, dispatches a parallel fleet of specialized AI agents to analyze the diff, and delivers a structured report with findings ranked by severity — posted back to the PR as a comment. This project was created during the IBM BOB 2.0 Hackathon by LABLAB.
- Overview
- Architecture
- Repository Structure
- Backend
- Frontend
- Data Flow
- Database Schema
- API Reference
- Getting Started
- Key Design Decisions
DevGuardAI is a full-stack application built for the LabLabAI hackathon. When a review is requested, the backend:
- Fetches the PR metadata and all changed file contents from the GitHub API.
- Runs three specialized LLM agents in parallel (Code Quality, Security, Test Coverage).
- Passes all raw findings to a fourth Aggregator Agent that deduplicates, prioritizes, and computes an overall PR status (
PASS,NEEDS_ATTENTION, orBLOCKED). - Persists every finding and the final report to PostgreSQL.
- Posts a formatted Markdown report back to the GitHub PR as a comment.
┌──────────────────────────────────────────────────────────────────────┐
│ Docker Compose │
│ │
│ ┌─────────────┐ HTTP ┌──────────────────────────────────────┐ │
│ │ Frontend │ ◄──────► │ Backend (FastAPI) │ │
│ │ React/TS │ :3000 │ port 8000 │ │
│ │ (nginx) │ │ │ │
│ └─────────────┘ │ ┌──────────┐ ┌─────────────────┐ │ │
│ │ │ Review │ │ Orchestrator │ │ │
│ │ │ Service │──►│ │ │ │
│ │ └──────────┘ │ ┌───────────┐ │ │ │
│ │ │ │ │CodeAgent │ │ │ │
│ │ │ │ ├───────────┤ │ │ │
│ │ ┌────▼─────┐ │ │SecurityAg.│ │ │ │
│ │ │ GitHub │ │ ├───────────┤ │ │ │
│ │ │ Service │ │ │ TestAgent │ │ │ │
│ │ └──────────┘ │ └─────┬─────┘ │ │ │
│ │ │ │ │ │ │ │
│ │ GitHub API │ ┌─────▼──────┐ │ │ │
│ │ │ │ Aggregator │ │ │ │
│ │ │ │ Agent │ │ │ │
│ │ │ └────────────┘ │ │ │
│ │ └─────────────────┘ │ │
│ │ │ │
│ │ ┌──────────────────────────────┐ │ │
│ │ │ PostgreSQL (SQLAlchemy + │ │ │
│ │ │ asyncpg + Alembic) │ │ │
│ │ └──────────────────────────────┘ │ │
│ └──────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────┘
Key technology choices:
| Layer | Technology |
|---|---|
| Backend framework | FastAPI 0.136 (async) |
| LLM provider | Google Gemini (google-genai 2.25) |
| Database | PostgreSQL 15 |
| ORM | SQLAlchemy 2.0 (async) |
| Migrations | Alembic |
| HTTP client | httpx (async) |
| Frontend | React 19 + TypeScript + Vite |
| Container runtime | Docker Compose |
├── docker-compose.yml # Orchestrates db, backend, frontend
├── backend/
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── alembic.ini
│ ├── .env.example
│ ├── migrations/
│ │ └── versions/
│ │ ├── 0001_init.py # Initial schema
│ │ └── 0002_report_column_add_report_in_review.py
│ └── src/
│ ├── main.py # FastAPI app + lifespan
│ ├── core/config.py # Pydantic settings
│ ├── agents/ # LLM agent implementations
│ ├── api/
│ │ ├── endpoints/ # FastAPI routers
│ │ └── schemas/ # Pydantic request/response models
│ ├── clients/github_client.py # Async GitHub REST client
│ ├── database/
│ │ ├── db.py # Session factory
│ │ └── models.py # SQLAlchemy ORM models + enums
│ ├── exception_handlers/ # Typed HTTP exceptions
│ ├── repositories/ # Data-access layer
│ └── services/ # Business logic
└── frontend/
├── Dockerfile # Multi-stage: Vite build → nginx
└── src/
├── api/ # Typed API client wrappers
├── components/ # Reusable UI components
├── pages/ # Home, Review, History
└── types/review.ts # Shared TypeScript interfaces
- Creates the
FastAPIapplication titled "AI Code Review Assistant". - Uses an
asynccontextmanagerlifespan to create a single sharedGitHubClientinstance on startup and gracefully close it on shutdown. - Applies
CORSMiddlewarewith origins driven by configuration. - Mounts the
review_routerunder/api/v1. - Exposes
GET /_infoas a lightweight health/info probe (used by the Docker healthcheck).
A pydantic-settings BaseSettings class that reads from backend/.env:
| Variable | Default | Purpose |
|---|---|---|
DB_HOST |
db |
PostgreSQL host |
DB_PORT |
5432 |
PostgreSQL port |
DB_USER |
admin |
DB username |
DB_PASS |
admin_123 |
DB password |
DB_NAME |
code_reviewer_db |
Database name |
GITHUB_TOKEN |
(required) | GitHub Personal Access Token |
GITHUB_API_URL |
https://api.github.com |
GitHub API base URL |
GEMINI_API_KEY |
(required) | Google Gemini API key |
GEMINI_MODEL |
gemini-3.5-flash |
Gemini model identifier |
APP_NAME |
Code_reviewer |
Application name |
DEBUG |
True |
Debug flag |
cors_origins |
["*"] |
CORS allowed origins |
A computed URL_DATABASE property returns the full postgresql+asyncpg://… connection string.
Router — src/api/endpoints/review_endpoint.py
All routes are prefixed /api/v1 and tagged reviews.
| Method | Path | Description |
|---|---|---|
POST |
/reviews |
Trigger a new AI code review |
GET |
/reviews |
List all past reviews |
GET |
/reviews/{review_id} |
Get review status + agent statuses |
GET |
/reviews/{review_id}/findings |
Get all raw findings for a review |
GET |
/reviews/{review_id}/report |
Get the aggregated report summary |
GET |
/reviews/{review_id}/markdown |
Get the full Markdown report (plain text) |
ReviewService is injected via Depends, itself depending on an AsyncSession and a GitHubClient.
Schemas — src/api/schemas/
| Schema | Purpose |
|---|---|
ReviewCreate |
Input: repository (owner/repo) + pull_request (int) |
ReviewResponse |
Full review record with embedded agent statuses |
ReviewFindingsResponse |
Review ID + list of FindingResponse |
ReviewReportResponse |
Aggregated report: status, summary, statistics, key issues, recommendations |
ReviewReport |
Internal Pydantic model for the LLM response from AggregatorAgent |
AgentResult |
LLM response schema for the three specialized agents: agent_type + findings[] |
FindingCreate / FindingResponse |
Individual finding data |
ReviewContextResponse |
PR context passed into agents: metadata + changed files + README |
ChangedFile / PullRequestData |
GitHub API response shapes |
ReviewService — src/services/review_service.py
Central business logic class. Key methods:
| Method | Description |
|---|---|
create_review |
Full end-to-end flow: fetch GitHub context → run orchestrator → persist findings → post PR comment |
get_review_by_id |
Returns review + agent statuses |
get_review_with_findings |
Returns review + individual findings |
get_review_report |
Returns structured aggregated report from stored JSONB |
get_review_markdown |
Returns formatted Markdown report |
list_reviews |
Returns all reviews ordered by creation date |
The create_review flow:
- Fetches PR context from GitHub (
GitHubService). - Creates a
Reviewrow withstatus=RUNNING. - Calls
ReviewOrchestrator.run_analysis()— the most time-intensive step. - Persists one
ReviewAgentrow per agent type. - Persists all individual
Findingrows. - Updates the
Reviewrow tostatus=COMPLETED, storing the full report as JSONB. - Posts the formatted Markdown report as a PR comment (failure is non-fatal — logged as a warning).
ReviewOrchestrator — src/services/orchestrator.py
Coordinates the multi-agent pipeline:
- Runs
CodeAgent,SecurityAgent, andTestAgentconcurrently withasyncio.gather(return_exceptions=True). - Filters out any agent that raised an exception (partial failure resilience).
- Passes valid results to
AggregatorAgent.aggregate(). - Returns a final
ReviewReport.
GitHubService — src/services/github_service.py
Higher-level abstraction over GitHubClient:
get_review_context— assembles aReviewContextResponseby:- Fetching PR metadata.
- Fetching changed file list (filtered to max 30 files; skips binaries/lock files/minified assets).
- Concurrently fetching full file contents and the repo README.
post_pr_comment— posts the Markdown report as a PR comment.- File filtering ignores:
.png,.jpg,.gif,.webp,.ico,.zip,.pdf,.lock,.min.js,.map,.exe,.bin.
generate_markdown_report — src/services/helper.py
Pure function that formats a Review ORM object (with its JSONB report and related findings) into a rich Markdown string, including a statistics table, findings sorted by severity, key issues, and recommendations. Used both for the API response and the GitHub PR comment.
All agents live in src/agents/ and share the same async LLM call mechanism.
BaseAgent — src/agents/base.py
Abstract base class defining the contract:
- Abstract property
agent_type: AgentType - Abstract async method
analyze(context: ReviewContextResponse) -> AgentResult
call_llm_with_schema — src/agents/call_llm.py
Shared async helper that calls Gemini with:
response_mime_type="application/json"— forces structured JSON output.response_schema=response_model— constrains the output to the provided Pydantic model.temperature=0.2— low temperature for deterministic, factual analysis.
Returns the response.parsed object — a fully hydrated Pydantic model instance.
| Agent | Class | agent_type |
Focus Areas |
|---|---|---|---|
| Code Quality | CodeAgent |
code |
Bugs, bad practices, code duplication, complexity, N+1 queries, incorrect async usage, resource leaks |
| Security | SecurityAgent |
security |
SQL injection, command injection, missing authorization, exposed secrets, unsafe file ops, SSRF, IDOR |
| Test Coverage | TestAgent |
test |
Missing tests, insufficient coverage, missing edge cases, missing integration/negative tests |
Each agent concatenates all changed file paths and contents into a single user prompt and calls call_llm_with_schema with its system prompt and AgentResult as the response schema.
AggregatorAgent — src/agents/aggregator_agent.py
Receives all AgentResult objects, formats them into a structured text block, and calls Gemini again with a Tech Lead persona. Rules enforced in the system prompt:
- Never invent new findings — only work from what the specialized agents reported.
- May merge duplicates, group related findings, prioritize, summarize.
- Determines
overall_status:PASS— no critical/high issues.NEEDS_ATTENTION— medium/low issues or minor gaps.BLOCKED— critical/high security vulnerabilities or severe bugs.
Returns a ReviewReport (summary, status, statistics, key_issues, recommendations, findings).
Async HTTP client built on httpx.AsyncClient. Initialized with a Bearer token and Accept: application/vnd.github+json headers.
| Method | GitHub Endpoint |
|---|---|
get_pull_request |
GET /repos/{owner}/{repo}/pulls/{pull_number} |
get_all_pull_request_files |
GET /repos/{owner}/{repo}/pulls/{pull_number}/files (paginated, 100/page) |
get_file_content |
GET /repos/{owner}/{repo}/contents/{path}?ref={sha} (base64-decoded) |
post_pr_comment |
POST /repos/{owner}/{repo}/issues/{pull_number}/comments |
Error mapping:
401/403→GitHubAuthenticationError(orGitHubRateLimitErrorif rate limit message present)404→GitHubNotFoundError429→GitHubRateLimitError- Other →
GitHubException
SQLAlchemy 2.0 declarative models with UUID primary keys and automatic created_at/updated_at timestamps on the shared Base.
Enums:
| Enum | Values |
|---|---|
Status |
queued, running, completed, failed |
AgentType |
code, security, test |
SeverityStatus |
critical, high, medium, low, info |
CategoryStatus |
bug, security, performance, architecture, test, style |
src/database/db.py provides the async session factory and get_session dependency.
Migrations are managed by Alembic with two versions:
0001_init.py— createsreviews,findings,review_agentstables.0002_…— adds thereportJSONB column toreviews.
At container start, docker-compose.yml runs alembic upgrade head before launching uvicorn.
src/repositories/ implements the repository pattern.
BaseRepository (base_repository.py) provides generic create, get, get_all, update, delete, and add_all methods for any SQLAlchemy model.
Specialized repositories:
| Repository | Extra Methods |
|---|---|
ReviewRepository |
get_review_with_agents, get_review_with_findings, get_all_with_agents |
ReviewAgentRepository |
Inherits BaseRepository |
FindingRepository |
Inherits BaseRepository |
All queries use SQLAlchemy's selectinload for eager-loading relationships to avoid N+1 problems.
src/exception_handlers/ defines a typed exception hierarchy:
BaseAppException
├── DatabaseException
└── NotFoundException
GitHubException
├── GitHubNotFoundError (404)
├── GitHubAuthenticationError (401)
└── GitHubRateLimitError (429)
A React 19 + TypeScript SPA built with Vite, served by nginx in production.
Pages:
| Page | File | Description |
|---|---|---|
| Home | src/pages/Home.tsx |
Input form for owner/repo + PR number; triggers review creation and navigates to Review page |
| Review | src/pages/Review.tsx |
Displays review status, per-agent status cards, report summary, and findings |
| History | src/pages/History.tsx |
Paginated list of all past reviews |
Components:
| Component | Purpose |
|---|---|
AgentStatus |
Renders per-agent status badge (queued / running / completed / failed) |
FindingCard |
Displays a single finding with severity icon, category, file path, and recommendation |
Statistics |
Renders the severity breakdown table |
API client (src/api/reviews.ts) wraps all backend calls using typed helper functions (createReview, getReview, getReviewFindings, getReviewReport, getReviewMarkdown, listReviews).
User submits owner/repo + PR number
│
▼
POST /api/v1/reviews
│
▼
ReviewService.create_review()
│
├─ GitHubService.get_review_context()
│ ├─ get_pull_request() ──► GitHub API
│ ├─ get_pull_request_files() ──► GitHub API (paginated)
│ └─ get_file_content() × N ──► GitHub API (concurrent)
│
├─ ReviewRepository.create() ──► INSERT reviews (status=RUNNING)
│
└─ ReviewOrchestrator.run_analysis()
│
├─ asyncio.gather(
│ CodeAgent.analyze() ──► Gemini API
│ SecurityAgent.analyze() ──► Gemini API
│ TestAgent.analyze() ──► Gemini API
│ )
│
└─ AggregatorAgent.aggregate() ──► Gemini API
│
▼
ReviewReport
│
┌───────────────┘
│
├─ ReviewAgentRepository.create() × 3 ──► INSERT review_agents
├─ FindingRepository.create() × N ──► INSERT findings
├─ ReviewRepository.update() ──► UPDATE reviews (status=COMPLETED, report=JSONB)
└─ GitHubService.post_pr_comment() ──► GitHub API
│
▼
ReviewResponse returned to client
┌─────────────────────────────────────────────────────────┐
│ reviews │
├──────────────────┬──────────────────────────────────────┤
│ id │ UUID (PK) │
│ repository │ VARCHAR │
│ pull_request │ INTEGER │
│ commit_sha │ VARCHAR (nullable) │
│ status │ ENUM(queued,running,completed,failed)│
│ progress │ INTEGER (0–100) │
│ summary │ TEXT (nullable) │
│ report │ JSONB (nullable) │
│ started_at │ TIMESTAMPTZ │
│ completed_at │ TIMESTAMPTZ │
│ created_at │ TIMESTAMPTZ │
│ updated_at │ TIMESTAMPTZ │
└─────────────────────────────────────────────────────────┘
│ 1 1 │
│ CASCADE DELETE CASCADE DELETE │
▼ N ▼ N
┌────────────────────────────┐ ┌───────────────────────────────┐
│ review_agents │ │ findings │
├──────────┬─────────────────┤ ├────────────┬──────────────────┤
│ id │ UUID (PK) │ │ id │ UUID (PK) │
│ review_id│ UUID (FK) │ │ review_id │ UUID (FK) │
│ agent_type│ ENUM │ │ agent_type │ ENUM │
│ status │ ENUM │ │ severity │ ENUM │
│ started_at│ TIMESTAMPTZ │ │ category │ ENUM │
│ completed_at│ TIMESTAMPTZ │ │ file_path │ VARCHAR │
│ error │ TEXT (nullable) │ │ line │ INTEGER (nullable)│
│ created_at│ TIMESTAMPTZ │ │ title │ VARCHAR │
│ updated_at│ TIMESTAMPTZ │ │ description│ TEXT │
└────────────────────────────┘ │ recommendation│ TEXT (nullable)│
│ created_at │ TIMESTAMPTZ │
│ updated_at │ TIMESTAMPTZ │
└───────────────────────────────┘
Trigger a new review. The request is synchronous — the response is returned only after all agents complete.
Request body:
{
"repository": "owner/repo",
"pull_request": 42
}Response 202: ReviewResponse
List all reviews ordered by creation date (newest first).
Response 200: ReviewResponse[]
Response 200: ReviewResponse with embedded agents[]
Response 200: ReviewFindingsResponse — { id, findings[] }
Response 200: ReviewReportResponse
{
"review_id": "…",
"repository": "owner/repo",
"pull_request": 42,
"status": "NEEDS_ATTENTION",
"summary": "…",
"statistics": { "total": 5, "critical": 0, "high": 1, "medium": 2, "low": 2, "info": 0 },
"key_issues": ["…"],
"recommendations": ["…"]
}Response 200 (plain text): Full Markdown report (same content posted to GitHub PR).
- Docker and Docker Compose
- A GitHub Personal Access Token with
reposcope (read PR data and post comments) - A Google Gemini API key
Copy the example file and fill in your secrets:
cp backend/.env.example backend/.env# backend/.env
DB_HOST=db
DB_PORT=5432
DB_NAME=code_reviewer_db
DB_USER=postgres
DB_PASS=secret
APP_NAME=Code_reviewer
DEBUG=True
GITHUB_TOKEN=ghp_your_token_here
GITHUB_API_URL=https://api.github.com
GEMINI_API_KEY=your_gemini_api_key_heredocker compose up --buildThis will:
- Start PostgreSQL on port
5432. - Run
alembic upgrade headto apply all migrations. - Start the FastAPI backend on port
8000. - Build the React frontend and serve it via nginx on port
3000.
Open http://localhost:3000 to use the UI, or call the API directly at http://localhost:8000.
The OpenAPI docs are available at http://localhost:8000/docs.
Backend:
cd backend
python -m venv venv
# Windows
.\venv\Scripts\activate
# Linux/macOS
source venv/bin/activate
pip install -r requirements.txt
# Apply migrations (PostgreSQL must be running)
alembic upgrade head
uvicorn src.main:app --reload --host 0.0.0.0 --port 8000Frontend:
cd frontend
npm install
VITE_API_URL=http://localhost:8000/api/v1 npm run dev| Decision | Rationale |
|---|---|
| Parallel agent execution | asyncio.gather runs Code, Security, and Test agents concurrently, cutting total LLM latency to ~1× instead of 3×. |
| Structured LLM output | Gemini's response_schema + response_mime_type="application/json" guarantees each agent returns a valid, fully typed Pydantic model — no prompt-engineering fragility or post-processing needed. |
| Aggregator as a fourth LLM call | Separating aggregation from analysis keeps individual agent prompts focused, and gives the aggregator a global view to deduplicate and reprioritize. |
| JSONB report column | The full ReviewReport is stored as JSONB alongside the normalized findings rows, enabling fast report retrieval without a JOIN while keeping individual findings queryable. |
| Repository pattern | Decouples database access from business logic, making the service layer testable without a live database. |
| Non-fatal PR comment posting | GitHub comment posting errors are caught and logged as warnings so a transient API failure doesn't roll back an otherwise successful review. |
| File filtering in GitHubService | Binary files, lock files, and minified assets are excluded before sending content to the LLM to reduce token usage and avoid irrelevant noise in findings. |