An automated GitHub PR review agent powered by Groq AI that provides intelligent code reviews as soon as pull requests are created or updated. Built to work like CodeRabbit, but free and self-hosted.
- π Automatic PR Reviews: Reviews PRs immediately when opened or updated
- π§ AI-Powered Analysis: Uses Groq's fast LLaMA 3.3 70B model for intelligent code analysis
- π― Smart Filtering: Only reviews relevant files and respects size limits
- π¬ Contextual Comments: Provides line-specific feedback with severity levels
- π Security Focus: Identifies potential security vulnerabilities
- β‘ Performance Insights: Highlights performance concerns
- π¨ Code Quality: Checks for best practices and code style
- π Comprehensive Reporting: Generates overall PR summaries
- π Easy Deployment: One-click deploy to popular hosting platforms
- βοΈ Configurable: Customizable review parameters and file limits
- π Robust Error Handling: Handles edge cases like force-pushes and invalid commits
graph TB
A[GitHub Repository] -->|PR Event| B[GitHub Webhook]
B --> C{Webhook Verification}
C -->|Valid| D[PR Review Agent]
C -->|Invalid| E[Reject Request]
D --> F[Extract PR Information]
F --> G[Authenticate with GitHub App]
G --> H[Fetch Changed Files]
H --> I{Filter Files}
I -->|Reviewable| J[Fetch File Contents]
I -->|Not Reviewable| K[Skip File]
J --> L[Send to Groq AI]
L --> M[LLaMA 3.3 70B Model]
M --> N[Generate Review]
N --> O[Parse AI Response]
O --> P[Create GitHub Comments]
P --> Q[Post Review to PR]
subgraph "Services"
R[GitHub Service]
S[Groq Service]
T[Review Service]
U[Logger Service]
end
D --> R
D --> S
D --> T
D --> U
sequenceDiagram
participant GH as GitHub
participant WH as Webhook Handler
participant AUTH as GitHub Auth
participant FILES as File Service
participant AI as Groq AI
participant REVIEW as Review Service
GH->>WH: PR opened/updated event
WH->>WH: Verify webhook signature
WH->>AUTH: Create installation token
AUTH-->>WH: Authenticated Octokit client
WH->>FILES: Fetch PR files
FILES->>GH: Get PR details & file list
GH-->>FILES: PR data & changed files
FILES->>GH: Fetch file contents (with fallback)
GH-->>FILES: File contents
FILES-->>WH: Reviewable files with content
loop For each file
WH->>AI: Analyze code
AI->>AI: LLaMA 3.3 70B processing
AI-->>WH: Review analysis
end
WH->>REVIEW: Generate review summary
REVIEW-->>WH: Formatted review
WH->>GH: Post review comments
GH-->>WH: Review posted confirmation
graph LR
A[GitHub App] --> B[Private Key + App ID]
B --> C[Create App Auth]
C --> D[Installation Token]
D --> E[Authenticated API Calls]
F[Installation ID] --> C
G[Repository Access] --> D
graph TD
A[PR Files List] --> B{File Extension Check}
B -->|Supported| C{File Size Check}
B -->|Not Supported| D[Skip File]
C -->|Within Limits| E{File Status Check}
C -->|Too Large| F[Skip File]
E -->|Not Removed| G[Fetch Content]
E -->|Removed| H[Skip File]
G --> I{Content Fetch}
I -->|Success| J[Add to Review Queue]
I -->|Failed - Try Head SHA| K[Fetch with PR Head SHA]
K -->|Success| J
K -->|Failed - Try Branch| L[Fetch with Branch Ref]
L -->|Success| J
L -->|Failed| M[Skip File]
J --> N[Send to AI Analysis]
Deploy with one click on Railway for the best experience:
Why Railway?
- β‘ Auto-scaling based on traffic
- π Persistent logs and metrics
- π Automatic deployments from GitHub
- π° Generous free tier for testing
- π οΈ Built-in environment variable management
If you prefer to run locally or use a different platform:
-
Clone the repository
git clone https://github.com/kuldeep27396/pr-review-agent.git cd pr-review-agent npm install -
Set up your GitHub App (see GitHub App Setup)
-
Configure environment variables (see Configuration)
-
Start the application
npm start
-
Create a GitHub App at GitHub Apps:
- App name:
Your PR Review Agent - Homepage URL: Your deployment URL
- Webhook URL:
https://your-domain.com/webhook - Webhook secret: Generate a secure random string
- App name:
-
Set Repository Permissions:
Contents: Read Pull requests: Write Metadata: Read -
Subscribe to Events:
Pull request Pull request review -
Download the private key and note your App ID
-
Install the app on your repositories
- Sign up at Groq Console
- Create an API key (free tier available)
- Note the key for configuration
Create a .env file or set environment variables:
# GitHub App Configuration (Required)
GITHUB_APP_ID=1234567 # Your GitHub App ID
GITHUB_PRIVATE_KEY="-----BEGIN RSA..." # Your private key (with proper newlines)
GITHUB_WEBHOOK_SECRET=your_secret_here # Webhook secret for verification
# Groq API Configuration (Required)
GROQ_API_KEY=gsk_... # Your Groq API key
# Server Configuration
PORT=3000 # Server port (default: 3000)
NODE_ENV=production # Environment mode
# Review Settings (Optional)
MAX_FILES_TO_REVIEW=10 # Max files per PR (default: 10)
MAX_FILE_SIZE_KB=100 # Max file size in KB (default: 100)
REVIEW_TIMEOUT_MS=30000 # AI request timeout (default: 30s)
LOG_LEVEL=info # Logging level (error/warn/info/debug)The agent reviews these file types:
| Category | Extensions |
|---|---|
| JavaScript/TypeScript | .js, .jsx, .ts, .tsx, .vue, .svelte |
| Python | .py |
| Java/JVM | .java, .kt, .scala |
| C/C++ | .c, .cpp, .h |
| Systems | .rs, .go, .cs |
| Mobile | .swift, .dart |
| Web | .html, .css, .scss, .less |
| Data | .sql, .r, .yaml, .yml, .json, .xml |
| Scripts | .sh, .php, .rb |
- π£ Webhook Reception: GitHub sends PR events to
/webhookendpoint - π Authentication Verification: Validates webhook signature and creates GitHub App token
- π File Discovery: Fetches list of changed files from PR
- π Smart Filtering: Filters files by type, size, and status (excludes removed files)
- π Content Retrieval: Fetches file contents with robust error handling:
- Primary: Use individual file SHA
- Fallback 1: Use PR head SHA (handles force-pushes)
- Fallback 2: Use PR branch reference
- π€ AI Analysis: Sends code to Groq's LLaMA 3.3 70B model with structured prompts
- π Review Generation: Parses AI response and creates structured comments
- π¬ Comment Posting: Posts line-specific comments and overall review to PR
| Category | Icon | Description | Triggers |
|---|---|---|---|
| Bugs | π | Potential runtime errors | REQUEST_CHANGES |
| Security | π | Security vulnerabilities | REQUEST_CHANGES |
| Performance | β‘ | Performance bottlenecks | COMMENT |
| Style | π¨ | Code style issues | COMMENT |
| Best Practices | β | Code quality improvements | COMMENT |
| Severity | Icon | Action |
|---|---|---|
| High | π΄ | Request changes |
| Medium | π‘ | Add comment |
| Low | π’ | Add comment |
The agent uses carefully crafted prompts that include:
- Context: PR title, description, and file metadata
- Code Content: Full file content with syntax highlighting
- Analysis Requirements:
- Overall assessment (APPROVE/REQUEST_CHANGES/COMMENT)
- Specific issues with line numbers
- Security concerns
- Performance considerations
- Improvement suggestions
- Response Format: Structured JSON for consistent parsing
# Install dependencies
npm install
# Start development server with auto-reload
npm run dev
# Run tests
npm test
# Test server functionality
npm run test-server
# Validate environment configuration
npm run validate
github-pr-review-agent/
βββ src/
β βββ index.js # Main application & webhook handler
β βββ services/
β β βββ github.js # GitHub API integration & authentication
β β βββ groq.js # Groq AI service & prompt management
β β βββ review.js # Review orchestration & comment generation
β βββ utils/
β βββ logger.js # Logging utility with file/console output
βββ scripts/
β βββ setup-github-app.js # GitHub App setup helper
β βββ validate-env.js # Environment validation
β βββ test-github-auth.js # Authentication testing
βββ test/
β βββ test-server.js # Local testing utilities
βββ docs/ # Deployment guides
βββ .github/workflows/ # CI/CD workflows
βββ Dockerfile # Container configuration
βββ docker-compose.yml # Local development setup
βββ railway.json # Railway deployment config
βββ render.yaml # Render deployment config (legacy)
# Test GitHub authentication locally
node scripts/test-github-auth.js
# Test Groq API connection
node -e "
const { GroqService } = require('./src/services/groq');
new GroqService().analyzeCode({filename: 'test.js', content: 'console.log(\"test\")'})
.then(result => console.log('β
Groq test passed'))
.catch(err => console.error('β Groq test failed:', err));
"
# Validate all environment variables
npm run validate| Endpoint | Method | Description | Response |
|---|---|---|---|
/ |
GET | Application info and status | JSON with app info |
/health |
GET | Health check for monitoring | 200 (healthy) / 500 (unhealthy) |
/webhook |
POST | GitHub webhook handler | 200 (processed) / 400 (invalid) |
{
"status": "healthy",
"timestamp": "2025-01-26T10:30:00.000Z",
"uptime": 3600,
"version": "1.0.0"
}The application provides detailed logging at multiple levels:
// Log levels and what they capture
ERROR: Authentication failures, API errors, critical issues
WARN: File fetch failures, parsing issues, non-critical problems
INFO: PR processing, successful operations, status updates
DEBUG: Detailed execution flow, variable values, timing info- Console: All log levels (formatted for readability)
- File System: Organized log files (when writable)
logs/error.log- Error messages onlylogs/warn.log- Warning level and abovelogs/info.log- Info level and abovelogs/all.log- All log messages
- Container Environments: Graceful fallback to console-only logging
- Check Health Endpoint:
GET /healthto verify service status - Review Recent Logs: Check application logs for error patterns
- Test Authentication: Run
node scripts/test-github-auth.jsfor GitHub issues - Validate Configuration: Run
npm run validatefor environment issues - Monitor Webhooks: Check GitHub App's "Advanced" tab for delivery status
No reviews being posted?
- Check webhook deliveries in GitHub App settings
- Verify app installation on target repositories
- Confirm webhook URL is publicly accessible
- Review authentication logs for token issues
Reviews failing for specific files?
- Check file size limits (
MAX_FILE_SIZE_KB) - Verify file extensions are supported
- Look for content fetch errors in logs
- Test with simpler files first
AI analysis errors?
- Verify Groq API key and quota
- Check for rate limiting in logs
- Test with smaller code snippets
- Monitor API response times
-
Connect Your GitHub Account
- Railway will fork the repository to your account
- Automatic deployments will be set up
-
Configure Environment Variables In the Railway dashboard, add these variables:
GITHUB_APP_ID=your_app_id GITHUB_PRIVATE_KEY=your_private_key GITHUB_WEBHOOK_SECRET=your_webhook_secret GROQ_API_KEY=your_groq_api_key
-
Get Your Webhook URL
- After deployment, Railway provides a URL like:
https://your-app.railway.app - Your webhook URL will be:
https://your-app.railway.app/webhook
- After deployment, Railway provides a URL like:
-
Update GitHub App Settings
- Go to your GitHub App settings
- Update webhook URL to your Railway deployment URL
- π Automatic Deployments: Every push to main branch triggers a new deployment
- π Built-in Monitoring: View logs, metrics, and resource usage
- β‘ Auto-scaling: Automatically scales based on traffic
- π° Free Tier: Generous free tier for personal projects
- π οΈ Easy Management: Simple dashboard for environment variables and settings
If you prefer Docker deployment on any other platform:
# Build the container
docker build -t pr-review-agent .
# Run with environment variables
docker run -d \
-p 3000:3000 \
-e GITHUB_APP_ID=your_app_id \
-e GITHUB_PRIVATE_KEY="$(cat private-key.pem)" \
-e GITHUB_WEBHOOK_SECRET=your_secret \
-e GROQ_API_KEY=your_groq_key \
pr-review-agentNote: Railway is the recommended and tested deployment platform for this project.
We welcome contributions! Here's how to get started:
-
Fork and Clone
git clone https://github.com/your-username/pr-review-agent.git cd pr-review-agent npm install -
Set Up Environment
cp .env.example .env # Fill in your configuration values -
Run Tests
npm test npm run validate
- Code Style: Follow existing patterns and use meaningful variable names
- Logging: Add appropriate log statements for debugging
- Error Handling: Include comprehensive error handling for external APIs
- Documentation: Update README and code comments for new features
- Testing: Test with real GitHub repositories and various file types
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes with appropriate tests
- Ensure all tests pass and linting is clean
- Update documentation for any new features
- Commit with clear, descriptive messages
- Push to your branch and create a Pull Request
Problem: [@octokit/auth-token] Token passed to createTokenAuth is not a string
Solution: Ensure you're using authStrategy: createAppAuth in Octokit configuration
Problem: Bad credentials errors
Solution:
- Verify GitHub App ID is correct (numeric)
- Check private key format includes proper line breaks
- Confirm app is installed on target repositories
Problem: Installation not found
Solution: Install the GitHub App on your repositories through the GitHub interface
Problem: No commit found for the ref errors
Solution: The agent now handles this automatically with fallback strategies
Problem: No files being reviewed despite PR having changes Solution:
- Check if files have supported extensions
- Verify files aren't exceeding size limits
- Check file status (removed files are skipped)
Problem: Groq API timeout or rate limit errors Solution:
- Increase
REVIEW_TIMEOUT_MSfor larger files - Check Groq API quota and usage
- Consider upgrading Groq plan for higher limits
Problem: Webhook signature verification failures Solution:
- Verify
GITHUB_WEBHOOK_SECRETmatches GitHub App configuration - Check webhook URL is correct and accessible
- Ensure raw body is used for signature verification
Problem: Reviews taking too long Solution:
- Reduce
MAX_FILES_TO_REVIEWlimit - Decrease
MAX_FILE_SIZE_KBlimit - Check network connectivity to APIs
Problem: Memory issues with large files Solution:
- Lower file size limits
- Implement streaming for large file processing
- Monitor container memory usage
This project is licensed under the MIT License - see the LICENSE file for details.
- Groq - For providing fast AI inference with LLaMA models
- Octokit - For excellent GitHub API integration
- CodeRabbit - For inspiration and reference
- Open Source Community - For tools, libraries, and continuous improvement
If you find this project useful, please consider giving it a star! β
- CodeRabbit - Commercial AI code review service
- GitHub Copilot - AI-powered coding assistant
- SonarQube - Code quality and security analysis
- ReviewBot - Automated code review tools
Made with β€οΈ for the developer community
Deploy your own instance today and experience AI-powered code reviews!