As development teams in the US and UK face tighter deadlines and complex microservices, automating routine code reviews and refactoring has become essential. Manual code reviews often slow down CI/CD pipelines.
In this post, we will build a lightweight Python script powered by modern AI models to automatically review pull requests, flag code smells, and suggest clean-code refactoring.
Why Automate Code Refactoring?
- Reduces Tech Debt: Catch anti-patterns and legacy code issues before production deployment.
- Accelerates CI/CD: Speed up pull request merges by providing instant AI-driven preliminary feedback.
- Focus on Core Logic: Free up senior developers from tedious syntax and formatting checks.
Step 1: Setting Up Your Python Environment
First, ensure you have Python installed. Install the required libraries for making API calls and handling code parsers:
pip install requests openai pydantic
Step 2: The Automation Script
Create a file named ai_code_reviewer.py and paste the following production-ready script:
import os
import openai
from pydantic import BaseModel
# Configure your API key via environment variables for security
openai.api_key = os.getenv("OPENAI_API_KEY")
class ReviewResponse(BaseModel):
code_smells_found: bool
suggestions: list[str]
optimized_code: str
def review_code_snippet(file_path: str):
"""Reads a Python file and requests an AI-driven refactoring review."""
if not os.path.exists(file_path):
return "File not found."
with open(file_path, "r") as file:
source_code = file.read()
prompt = f"""
You are an expert Principal Software Engineer. Review the following Python code for performance bottlenecks, security vulnerabilities, and PEP 8 compliance. Provide suggestions and optimized code.
Code:
{source_code}
"""
try:
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
temperature=0.2
)
analysis = response.choices[0].message.content
return analysis
except Exception as e:
return f"An error occurred during review: {str(e)}"
if __name__ == "__main__":
target_file = "sample_script.py"
print(f"Running AI Code Review for: {target_file}")
result = review_code_snippet(target_file)
print(result)
Step 3: Integrating into GitHub Actions (CI/CD)
To run this automatically whenever a developer opens a pull request, create a GitHub Workflow file at .github/workflows/ai_review.yml:
name: AI PR Reviewer
on:
pull_request:
branches: [ main ]
jobs:
ai_review:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install Dependencies
run: pip install requests openai pydantic
- name: Run Review Script
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: python ai_code_reviewer.py
Conclusion
By implementing this Python and AI-powered workflow, development teams can maintain high code quality standards effortlessly.
What automation tools are you currently using in your development pipeline? Let us know in the comments below!
.png)
No comments:
Post a Comment