Skip to content

Instantly share code, notes, and snippets.

@j0uni
Last active April 5, 2025 14:35
Show Gist options
  • Save j0uni/1bd3f471c0cf9a352b67af4297d8f6ab to your computer and use it in GitHub Desktop.
Save j0uni/1bd3f471c0cf9a352b67af4297d8f6ab to your computer and use it in GitHub Desktop.
OpenAI pull request review Python script
import requests
import openai
import os
from openai import OpenAI
GITHUB_TOKEN = ""
OPENAI_API_KEY = ""
REPO_OWNER = "j0uni"
REPO_NAME = "rtl_icecast"
PULL_REQUEST_ID = 8
# GitHub API URL
GITHUB_API_URL = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/pulls/{PULL_REQUEST_ID}/files"
# GitHub API URL
GITHUB_API_URL = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/pulls/{PULL_REQUEST_ID}/files"
# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)
# Get changed files from GitHub PR
def get_changed_files_from_pr():
headers = {
'Authorization': f'token {GITHUB_TOKEN}'
}
print(f"Fetching changed files from: {GITHUB_API_URL}")
response = requests.get(GITHUB_API_URL, headers=headers)
if response.status_code != 200:
print("Error fetching pull request details:", response.json())
return []
return response.json()
# Analyze diff with OpenAI
def analyze_code_with_openai(diff):
try:
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant reviewing code diffs. You are are professional with 20 years of experience and you want to make high quality, standardized programming."},
{"role": "user", "content": f"Please review the following code diff. Find out possible problems and provide code examples for better practices or for fixes. :\n\n{diff}"}
],
temperature=0.5,
max_tokens=2000
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error analyzing code with OpenAI: {e}")
return None
# Review PR
def review_pull_request():
changed_files = get_changed_files_from_pr()
if not changed_files:
print("No changed files found in the pull request.")
return
for file in changed_files:
filename = file.get('filename')
patch = file.get('patch')
print(f"\nReviewing file: {filename}")
if patch:
review = analyze_code_with_openai(patch)
if review:
print(f"Review for {filename}:\n{review}")
print("-" * 80)
else:
print(f"No patch data found for {filename}.")
if __name__ == "__main__":
review_pull_request()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment