CodeReviewer / model.py
Ranajit1997's picture
deploy Dockerize FastApi AI Code reviewer
64a7b70
Raw History Blame Contribute Delete
2.81 kB
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
}