Article
code-reviewpythonopenaiautomationdevopsquality-assurancesecurity-analysisstatic-analysis
Automate Code Reviews with an AI Assistant
Use a large language model to perform an expert Code Review. This skill analyzes your code for bugs, security vulnerabilities, and style violations, providing actionable feedback to improve quality and save developer time before human review.
beginner15 min5 steps
The play
- Set Up Your Python EnvironmentTo use an AI for Code Review, you need an environment to call a model. We'll use Python with the OpenAI library. Install the library and set your API key as an environment variable for secure authentication.
- Define the Code Review System PromptInstruct the AI to act as the Code Review skill. A detailed system prompt is crucial for high-quality results. Specify the persona (expert reviewer), the required analysis categories (bugs, security, performance, style), and the desired output format.
- Submit Code for a General ReviewPass a piece of code to the model along with your system prompt. This example function has a potential bug (division by zero) and a style issue. The Code Review skill will identify these and provide feedback.
- Focus on Security AnalysisThe Code Review skill is particularly powerful for security. Let's test it with a function vulnerable to command injection. The AI should flag this as a high-severity issue and explain the danger of using unsanitized user input in system commands.
- Integrate into a Pre-Commit HookTo automate Code Review, run it before committing code. This example shows a basic Git pre-commit hook. It uses a Python script (e.g., 'review.py' from the starter code) to analyze staged files, preventing commits with high-severity issues.
Starter code
import os
import sys
from openai import OpenAI
# Ensure your OPENAI_API_KEY is set as an environment variable
if not os.environ.get("OPENAI_API_KEY"):
print("Error: OPENAI_API_KEY environment variable not set.")
sys.exit(1)
client = OpenAI()
SYSTEM_PROMPT = """
You are an expert AI assistant specializing in Code Review. Analyze the user's code for the following:
1. Bugs: Logical errors that could cause crashes or incorrect behavior.
2. Security Vulnerabilities: Weaknesses like injection flaws or data exposure.
3. Performance Issues: Inefficient code or memory leaks.
4. Style Violations: Deviations from language-specific best practices (e.g., PEP 8 for Python).
For each issue found, provide a concise description, the line number, a severity rating (Low, Medium, High), and a suggested fix. If no issues are found, reply with 'No issues found.'
"""
def review_code(code_content):
"""Sends code to the OpenAI API for review."""
try:
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Please review this Python code:\n\n```{code_content}```"}
]
)
return response.choices[0].message.content
except Exception as e:
return f"An error occurred during API call: {e}"
if __name__ == "__main__":
# If file paths are passed as arguments, review them
if len(sys.argv) > 1:
for file_path in sys.argv[1:]:
print(f"--- Reviewing {file_path} ---")
try:
with open(file_path, 'r') as f:
content = f.read()
review_result = review_code(content)
print(review_result)
except FileNotFoundError:
print(f"Error: File not found at {file_path}")
# Otherwise, run a default example
else:
print("--- Running default example review ---")
example_code = """
import os
def check_file_status(filename):
# DANGEROUS: Command injection vulnerability
os.system(f'ls -l {filename}')
"""
review_result = review_code(example_code)
print(review_result)