Skip to content

2803rishita/PR-Review-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PR Review Agent API πŸ€–

Automated GitHub Pull Request Review Agent powered by Lyzr AI

An intelligent backend system that analyzes GitHub pull requests and generates comprehensive, actionable code review comments using multi-agent AI reasoning.

πŸš€ Features

  • πŸ”— Real-Time Webhook Integration: Automatically analyzes PRs when opened or updated via GitHub webhooks
  • πŸ€– Automated PR Analysis: Fetch and analyze GitHub PR diffs automatically
  • 🧠 Multi-Agent AI Review: Powered by Lyzr Agent Studio for intelligent code analysis
  • πŸ” Comprehensive Issue Detection: Identifies logic errors, security vulnerabilities, performance issues, and best practice violations
  • πŸ’¬ Structured Feedback: Generates clear, actionable review comments with severity levels
  • 🎨 Beautiful Web UI: Modern dashboard for testing and monitoring
  • πŸ“Š GitHub Integration: Automatically posts review comments to GitHub PRs
  • πŸ“š Review History: Stores all reviews in a database for future reference
  • 🌐 RESTful API: Clean, well-documented API endpoints
  • πŸ”’ Production Ready: Built with FastAPI, includes logging, error handling, CORS support, and security

πŸ“‹ Prerequisites

  • Python 3.9+
  • GitHub Personal Access Token with repo scope
  • Lyzr Agent Studio account and API key
  • SQLite (default) or PostgreSQL (optional)

πŸ› οΈ Installation

1. Clone the repository

cd "c:\Users\Nirupam\Desktop\PR Agent Backend"

2. Create virtual environment

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install dependencies

pip install -r requirements.txt

4. Configure environment variables

The .env file is already configured with your credentials. Verify it contains:

# GitHub Configuration
GITHUB_TOKEN=your_github_token
GITHUB_WEBHOOK_SECRET=your_webhook_secret

# Lyzr Configuration
LYZR_API_KEY=your_lyzr_api_key
LYZR_USER_ID=your_email@example.com
LYZR_AGENT_ID=your_agent_id

# Application
SECRET_KEY=your_secret_key
DATABASE_URL=sqlite:///./pr_reviews.db
PORT=8000

πŸƒ Running the Application

Quick Start (Recommended)

Windows:

start.bat

Linux/Mac:

chmod +x start.sh
./start.sh

Manual Start

Development Mode:

source venv/Scripts/activate  # Windows: venv\Scripts\activate
python main.py

Or using uvicorn directly:

uvicorn main:app --reload --host 127.0.0.1 --port 8000

Production Mode:

uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

Access Points

🎨 Web UI Dashboard

A beautiful, modern web interface is available for easy testing and interaction:

Features:

  • πŸ“Š Real-time system health monitoring
  • πŸ” Analyze PRs with a simple form
  • οΏ½ View review history
  • 🎯 Beautiful, responsive design
  • πŸ“± Mobile-friendly interface

Access the Dashboard: Open your browser and navigate to: http://127.0.0.1:8000

οΏ½πŸ“š API Documentation

Interactive API Docs

Key Endpoints

1. Health Check

GET /api/v1/health

Check the health status of the application and its dependencies.

2. Analyze Pull Request

POST /api/v1/reviews/analyze
Content-Type: application/json

{
  "pr_url": "https://github.com/owner/repo/pull/123",
  "post_to_github": true
}

Analyzes a GitHub PR and optionally posts the review to GitHub.

Response:

{
  "review_id": 1,
  "pr_url": "https://github.com/owner/repo/pull/123",
  "status": "completed",
  "summary": "Overall review summary...",
  "total_issues": 5,
  "issues": [
    {
      "file": "src/main.py",
      "line": 42,
      "category": "Security",
      "severity": "HIGH",
      "issue": "SQL injection vulnerability detected",
      "suggestion": "Use parameterized queries",
      "code_example": "cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))"
    }
  ],
  "positive_feedback": "Good code structure and documentation",
  "pr_metadata": {...},
  "created_at": "2025-11-15T10:30:00",
  "completed_at": "2025-11-15T10:30:45"
}

3. Analyze by Details

POST /api/v1/reviews/analyze-by-details
Content-Type: application/json

{
  "owner": "username",
  "repo": "repository",
  "pr_number": 123,
  "post_to_github": true
}

Alternative endpoint to analyze PR by owner, repo, and PR number.

4. Get Review

GET /api/v1/reviews/{review_id}

Retrieve a specific review by ID.

5. List Reviews

GET /api/v1/reviews?skip=0&limit=50

List all reviews with pagination.

6. Delete Review

DELETE /api/v1/reviews/{review_id}

Delete a review by ID.

πŸ—οΈ Project Structure

PR Agent Backend/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/              # API routes
β”‚   β”‚   β”œβ”€β”€ reviews.py    # Review endpoints
β”‚   β”‚   └── health.py     # Health check endpoints
β”‚   β”œβ”€β”€ core/             # Core configuration
β”‚   β”‚   β”œβ”€β”€ config.py     # Settings and environment variables
β”‚   β”‚   └── logger.py     # Logging configuration
β”‚   β”œβ”€β”€ models/           # Database models
β”‚   β”‚   └── review.py     # PRReview and ReviewComment models
β”‚   β”œβ”€β”€ schemas/          # Pydantic schemas
β”‚   β”‚   └── review.py     # Request/response schemas
β”‚   β”œβ”€β”€ services/         # Business logic
β”‚   β”‚   β”œβ”€β”€ github_service.py   # GitHub API integration
β”‚   β”‚   └── lyzr_service.py     # Lyzr Agent integration
β”‚   └── utils/            # Utilities
β”‚       └── database.py   # Database utilities
β”œβ”€β”€ main.py               # Application entry point
β”œβ”€β”€ requirements.txt      # Python dependencies
β”œβ”€β”€ .env                  # Environment variables (configured)
β”œβ”€β”€ .env.example          # Environment template
└── README.md             # This file

πŸ”§ Configuration

Environment Variables

Variable Description Required Default
GITHUB_TOKEN GitHub Personal Access Token Yes -
GITHUB_WEBHOOK_SECRET Webhook secret for validation No -
LYZR_API_KEY Lyzr API key Yes -
LYZR_USER_ID Lyzr user email Yes -
LYZR_AGENT_ID Lyzr agent ID Yes -
LYZR_BASE_URL Lyzr API base URL No https://agent.api.lyzr.app/v3
SECRET_KEY Application secret key Yes -
DATABASE_URL Database connection string No sqlite:///./pr_reviews.db
PORT Server port No 8000
LOG_LEVEL Logging level No INFO
MAX_DIFF_SIZE Max diff lines to process No 10000

Lyzr Agent Configuration

Your Lyzr Agent should be configured with:

  • Agent Name: PR Code Review Agent
  • Agent Role: Senior Code Reviewer and Quality Assurance Specialist
  • Agent Goal: Provide comprehensive code review feedback
  • Agent Instructions: See Lyzr agent configuration section in setup docs

πŸ”— GitHub Webhook Setup (Automated PR Reviews)

Set up webhooks to automatically analyze PRs when they're opened or updated!

Quick Setup

  1. Install ngrok (for local development):

    # Download from https://ngrok.com/download
    ngrok http 8000
  2. Copy ngrok URL (e.g., https://abc123.ngrok.io)

  3. Configure GitHub Webhook:

    • Go to your repo β†’ Settings β†’ Webhooks β†’ Add webhook
    • Payload URL: https://abc123.ngrok.io/webhook/github
    • Content type: application/json
    • Secret: Your GITHUB_WEBHOOK_SECRET from .env
    • Events: Select "Pull requests"
  4. Test it: Open a PR and watch the magic happen! πŸŽ‰

πŸ“– Detailed Guide: See WEBHOOK_SETUP.md for complete instructions.

Test Webhook Functionality

# Test webhook endpoint
python test_webhook.py

πŸ§ͺ Testing

Test with cURL

curl -X POST "http://localhost:8000/api/v1/reviews/analyze" \
  -H "Content-Type: application/json" \
  -d '{
    "pr_url": "https://github.com/owner/repo/pull/123",
    "post_to_github": false
  }'

Test with Python

import requests

response = requests.post(
    "http://localhost:8000/api/v1/reviews/analyze",
    json={
        "pr_url": "https://github.com/owner/repo/pull/123",
        "post_to_github": False
    }
)

print(response.json())

πŸ“Š Database

The application uses SQLite by default. The database file pr_reviews.db is created automatically on first run.

Database Schema

pr_reviews table:

  • id: Primary key
  • pr_url: GitHub PR URL
  • pr_number: PR number
  • repository: Repository name
  • pr_title: PR title
  • pr_author: PR author
  • status: Review status (pending/in_progress/completed/failed)
  • review_summary: Overall review summary
  • total_issues: Number of issues found
  • review_data: Complete review JSON
  • created_at: Creation timestamp
  • updated_at: Update timestamp
  • completed_at: Completion timestamp
  • error_message: Error message if failed

review_comments table:

  • id: Primary key
  • review_id: Foreign key to pr_reviews
  • file_path: File path
  • line_number: Line number
  • category: Issue category
  • severity: Issue severity
  • issue_description: Issue description
  • suggestion: Suggested fix
  • code_example: Code example
  • created_at: Creation timestamp

🚨 Error Handling

The API returns standard HTTP status codes:

  • 200 OK: Successful GET request
  • 201 Created: Successful POST request
  • 204 No Content: Successful DELETE request
  • 400 Bad Request: Invalid input
  • 404 Not Found: Resource not found
  • 422 Unprocessable Entity: Validation error
  • 500 Internal Server Error: Server error

Error responses include:

{
  "error": "Error type",
  "detail": "Detailed error message",
  "status_code": 500
}

πŸ“ Logging

Logs are output to stdout. In development mode, logs are human-readable. In production mode, logs are in JSON format for easier parsing.

Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL

πŸ”’ Security

  • GitHub token is never exposed in logs or responses
  • All sensitive data is stored in environment variables
  • CORS is configured for specific origins
  • Database credentials are protected
  • Input validation using Pydantic schemas

πŸ›£οΈ Roadmap

  • Add webhook support for real-time PR monitoring
  • Implement rate limiting
  • Add Redis caching
  • Support for multiple LLM providers
  • Custom review templates
  • Slack/Discord notifications
  • Review metrics and analytics
  • Support for GitLab and Bitbucket

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

πŸ“„ License

This project is part of the Lyzr AI Backend Engineering Intern Challenge.

πŸ‘₯ Author

Built for the Lyzr AI Backend Engineering Intern Challenge

πŸ™ Acknowledgments

  • FastAPI: Modern Python web framework
  • Lyzr AI: Multi-agent orchestration platform
  • PyGithub: GitHub API wrapper
  • SQLAlchemy: SQL toolkit and ORM

πŸ“ž Support

For issues or questions:

  1. Check the API documentation at /docs
  2. Review the logs for error details
  3. Check GitHub token permissions
  4. Verify Lyzr agent configuration

Built with ❀️ using FastAPI and Lyzr AI

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages