File size: 2,810 Bytes
64a7b70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import json
from typing import Dict, Any
from openai import OpenAI

class CodeReviewerModel:
    """
    AI Code Reviewer using OpenAI GPT models
    """
    def __init__(self, api_key: str = None, model: str = "gpt-4o"):
        self.api_key = api_key or os.getenv("OPENAI_API_KEY")
        self.model = model
        
        if not self.api_key:
            raise ValueError(
                "OpenAI API key is required. "
                "Set OPENAI_API_KEY environment variable or pass api_key parameter."
            )
        
        self.client = OpenAI(api_key=self.api_key)

    def generate_review(self, code: str) -> Dict[str, Any]:
        """
        Generate code review for the given code snippet
        """
        prompt = f"""
        You are an expert code reviewer. Analyze this code and provide JSON response:

        ```python
        {code}
        ```

        Return JSON with exactly these keys:

        "readability": string,
        "bugs": list of strings,
        "optimizations": list of strings,
        "refactored_code": string,
        "security_issues": list of strings,
        "overall_score": number (0-100)
        """
        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are a senior software engineer. Always return valid JSON."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.0,
                max_tokens=1000
            )

            result_text = response.choices[0].message.content.strip()

            # Clean the response (remove markdown code blocks)
            if result_text.startswith("```json"):
                result_text = result_text[7:]
            if result_text.startswith("```"):
                result_text = result_text[3:]
            if result_text.endswith("```"):
                result_text = result_text[:-3]

            review_data = json.loads(result_text.strip())
            return review_data

        except json.JSONDecodeError as e:
            return {
                "error": f"JSON parsing error: {str(e)}",
                "readability": "Error in analysis",
                "bugs": ["Failed to parse AI response"],
                "optimizations": [],
                "refactored_code": code,
                "security_issues": [],
                "overall_score": 0
            }
        except Exception as e:
            return {
                "error": str(e),
                "readability": "Error in analysis",
                "bugs": [],
                "optimizations": [],
                "refactored_code": code,
                "security_issues": [],
                "overall_score": 0
            }