Ranajit1997/CodeReviewer
0
1import os2import json3from typing import Dict, Any4from openai import OpenAI5 6class CodeReviewerModel:7 """8 AI Code Reviewer using OpenAI GPT models9 """10 def __init__(self, api_key: str = None, model: str = "gpt-4o"):11 self.api_key = api_key or os.getenv("OPENAI_API_KEY")12 self.model = model13 14 if not self.api_key:15 raise ValueError(16 "OpenAI API key is required. "17 "Set OPENAI_API_KEY environment variable or pass api_key parameter."18 )19 20 self.client = OpenAI(api_key=self.api_key)21 22 def generate_review(self, code: str) -> Dict[str, Any]:23 """24 Generate code review for the given code snippet25 """26 prompt = f"""27 You are an expert code reviewer. Analyze this code and provide JSON response:28 29 ```python30 {code}31 ```32 33 Return JSON with exactly these keys:34 35 "readability": string,36 "bugs": list of strings,37 "optimizations": list of strings,38 "refactored_code": string,39 "security_issues": list of strings,40 "overall_score": number (0-100)41 """42 try:43 response = self.client.chat.completions.create(44 model=self.model,45 messages=[46 {"role": "system", "content": "You are a senior software engineer. Always return valid JSON."},47 {"role": "user", "content": prompt}48 ],49 temperature=0.0,50 max_tokens=100051 )52 53 result_text = response.choices[0].message.content.strip()54 55 # Clean the response (remove markdown code blocks)56 if result_text.startswith("```json"):57 result_text = result_text[7:]58 if result_text.startswith("```"):59 result_text = result_text[3:]60 if result_text.endswith("```"):61 result_text = result_text[:-3]62 63 review_data = json.loads(result_text.strip())64 return review_data65 66 except json.JSONDecodeError as e:67 return {68 "error": f"JSON parsing error: {str(e)}",69 "readability": "Error in analysis",70 "bugs": ["Failed to parse AI response"],71 "optimizations": [],72 "refactored_code": code,73 "security_issues": [],74 "overall_score": 075 }76 except Exception as e:77 return {78 "error": str(e),79 "readability": "Error in analysis",80 "bugs": [],81 "optimizations": [],82 "refactored_code": code,83 "security_issues": [],84 "overall_score": 085 }86 