import os from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.prompts import ChatPromptTemplate import logging logger = logging.getLogger(__name__) class AIReviewer: def __init__(self): self.api_key = os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY") self.model_name = os.getenv("GEMINI_MODEL", "gemini-1.5-flash") self.allowed_extensions = [".py", ".js", ".php", ".html", ".css", ".ts", ".java"] if not self.api_key: logger.warning("GOOGLE_API_KEY not configured.") self.llm = ChatGoogleGenerativeAI( model=self.model_name, google_api_key=self.api_key, temperature=0.1 ) def filter_diff(self, diff_content: str) -> str: """ Filter the diff to only include files with allowed extensions. """ if not diff_content: return "" filtered_diff = [] current_file_allowed = False lines = diff_content.splitlines() for line in lines: # Check for new file header in diff if line.startswith("diff --git"): current_file_allowed = any(line.endswith(ext) or f"{ext} " in line for ext in self.allowed_extensions) if current_file_allowed: filtered_diff.append(line) return "\n".join(filtered_diff) def review_diff(self, diff_content: str) -> str: """ Analyze the code diff and provide a short, concise review summary. """ filtered_diff = self.filter_diff(diff_content) if not filtered_diff: return "No relevant code changes (filtered by extensions) found in the diff." # Truncate diff if it's too large max_diff_length = 50000 if len(filtered_diff) > max_diff_length: logger.warning("Diff content too large, truncating...") filtered_diff = filtered_diff[:max_diff_length] + "\n\n... (diff truncated)" prompt = ChatPromptTemplate.from_template(""" You are an expert Senior Software Engineer. Review the following git diff. **CRITICAL REQUIREMENT**: You MUST return your response as raw HTML (do not wrap in ```html markdown blocks). The output must be formatted as a cleanly styled HTML table to be embedded in an email. Keep your response understandable. Focus on observations (bugs, syntax errors, major clean code violations, security risks, performance). Use this exact HTML structure:
| Category | Details |
|---|---|
| Summary | [1-2 sentences summarizing the change] |
| Key Issues | [Use HTML
|
| Suggestions | [Use HTML
|