What you'll build
An automated code review system that analyzes pull requests and suggests improvements using AI.
Every time someone makes a PR, the AI reviews the complete diff. It detects potential bugs, security vulnerabilities, duplicate code, and refactoring opportunities. It generates a report with a quality score and specific comments per line.
When finished, you'll have a script that gets the diff from GitHub, sends it to Gemini for analysis, and generates a detailed report. You can integrate it with GitHub Actions to run automatically on each PR.
The prompt to start
Create a script that:
- Gets diff from a GitHub PR
- Sends to Gemini for analysis
- Generates review comments
- (Optional) Posts on GitHub
What the AI will create
import google.generativeai as genai
import subprocess
import os
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-flash")
def get_diff(base: str = "main") -> str:
"""Get diff from current branch vs base"""
result = subprocess.run(
["git", "diff", base],
capture_output=True,
text=True
)
return result.stdout
def review_code(diff: str) -> str:
"""Review code with AI"""
prompt = f"""You are a senior developer doing code review.
Analyze this diff and provide:
1. **Summary**: What this change does
2. **Potential bugs**: Errors that could occur
3. **Security**: Detected vulnerabilities
4. **Improvements**: Refactoring suggestions
5. **Score**: 1-10 quality
DIFF:
```diff
{diff[:10000]}
Be constructive and specific."""
response = model.generate_content(prompt)
return response.text
def main(): print("๐ Getting diff...") diff = get_diff()
if not diff:
print("No changes to review")
return
print(f"๐ Analyzing {len(diff)} characters of diff...")
review = review_code(diff)
print("\n" + "=" * 50)
print("๐ CODE REVIEW")
print("=" * 50)
print(review)
if name == "main": main()
---
## GitHub Actions integration
```yaml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get diff
run: |
git diff origin/main > diff.txt
- name: AI Review
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
run: |
python review.py diff.txt > review.md
- name: Comment on PR
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: review
});