CodeCommunity commited on
Commit
9ab4eb2
·
verified ·
1 Parent(s): 3cce99c

Update app/services/reviewer_service.py

Browse files
Files changed (1) hide show
  1. app/services/reviewer_service.py +30 -42
app/services/reviewer_service.py CHANGED
@@ -1,4 +1,3 @@
1
- import time
2
  import json
3
  import logging
4
  import re
@@ -15,7 +14,7 @@ DB_PATH = "review_cache.db"
15
 
16
  class AIReviewerService:
17
  def __init__(self):
18
- self.batch_size = 3
19
  self.db_lock = threading.Lock()
20
  self._init_db()
21
 
@@ -88,8 +87,7 @@ class AIReviewerService:
88
  ]
89
 
90
  new_results = []
91
- # Reduced max_workers to 2 to prevent hitting API Rate Limits
92
- with ThreadPoolExecutor(max_workers=2) as pool:
93
  future_to_batch = {pool.submit(self._process_batch, batch): batch for batch in batches}
94
  for future in as_completed(future_to_batch):
95
  try:
@@ -104,7 +102,7 @@ class AIReviewerService:
104
  "vulnerabilities": [],
105
  "improvement_suggestions": [],
106
  "metrics": {"complexity": 0, "maintainability": 0.0},
107
- "error": "RATE_LIMIT_EXCEEDED" if "429" in str(e) else str(e),
108
  })
109
 
110
  new_results_map = {item.get("fileName"): item for item in new_results if isinstance(item, dict)}
@@ -129,22 +127,6 @@ class AIReviewerService:
129
  self._save_cached_results(to_cache)
130
  return results
131
 
132
- def _call_llm_with_retry(self, prompt: str, max_tokens: int = 2048, retries: int = 3) -> str:
133
- """Helper to retry LLM generation automatically when 429 rate limits occur."""
134
- delay = 3.0
135
- for attempt in range(retries):
136
- try:
137
- return llm_engine.generate(prompt, max_tokens=max_tokens)
138
- except Exception as e:
139
- err_str = str(e).upper()
140
- if "429" in err_str or "RATE" in err_str or "LIMIT" in err_str:
141
- if attempt < retries - 1:
142
- logger.warning(f"⚠️ Rate limited (429). Retrying in {delay}s... (Attempt {attempt + 1}/{retries})")
143
- time.sleep(delay)
144
- delay *= 2 # Exponential backoff
145
- continue
146
- raise e
147
-
148
  def _process_batch(self, batch: list) -> list:
149
  combined_code = ""
150
  file_names = []
@@ -154,25 +136,29 @@ class AIReviewerService:
154
  combined_code += f"\n--- FILE: {f.fileName} ---\n{minified_content}\n"
155
  file_names.append(f.fileName)
156
 
157
- prompt = f"""Analyze {len(batch)} files. Be ultra-concise.
158
  CRITICAL: The "fileName" field MUST EXACTLY match the file path given in header (e.g. "{file_names[0]}").
159
 
160
  {combined_code}
161
 
162
- Return ONLY valid JSON array:
163
- [
164
- {{
165
- "fileName": "{file_names[0]}",
166
- "vulnerabilities": [{{"type": "type", "line": 1, "description": "short", "suggestion": "fix"}}],
167
- "improvement_suggestions": ["tip"],
168
- "metrics": {{"complexity": 3, "maintainability": 8.0}}
169
- }}
170
- ]"""
 
 
171
  batch_results = []
172
  try:
173
- response_text = self._call_llm_with_retry(prompt, max_tokens=2048)
174
  parsed = self._parse_json(response_text)
175
- processed_map = {item.get("fileName"): item for item in parsed if isinstance(item, dict)}
 
 
176
 
177
  for fn in file_names:
178
  if fn in processed_map:
@@ -196,7 +182,7 @@ Return ONLY valid JSON array:
196
  "vulnerabilities": [],
197
  "improvement_suggestions": [],
198
  "metrics": {"complexity": 0, "maintainability": 0.0},
199
- "error": "RATE_LIMIT_EXCEEDED" if "429" in str(e) else str(e),
200
  })
201
  return batch_results
202
 
@@ -216,23 +202,25 @@ Return ONLY valid JSON array:
216
  continue
217
  cleaned_lines.append(stripped)
218
 
219
- return "\n".join(cleaned_lines)
220
 
221
  def _parse_json(self, text: str):
222
  text = text.strip()
223
  if not text:
224
- return []
225
 
226
  text = re.sub(r"```(?:json)?", "", text, flags=re.IGNORECASE).strip()
227
- start_idx = text.find('[')
228
- end_idx = text.rfind(']')
229
-
230
- if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
231
- text = text[start_idx : end_idx + 1]
232
 
233
  try:
234
  return json.loads(text)
235
  except json.JSONDecodeError:
236
- return []
 
 
 
 
 
 
 
237
 
238
  service = AIReviewerService()
 
 
1
  import json
2
  import logging
3
  import re
 
14
 
15
  class AIReviewerService:
16
  def __init__(self):
17
+ self.batch_size = 1
18
  self.db_lock = threading.Lock()
19
  self._init_db()
20
 
 
87
  ]
88
 
89
  new_results = []
90
+ with ThreadPoolExecutor(max_workers=3) as pool:
 
91
  future_to_batch = {pool.submit(self._process_batch, batch): batch for batch in batches}
92
  for future in as_completed(future_to_batch):
93
  try:
 
102
  "vulnerabilities": [],
103
  "improvement_suggestions": [],
104
  "metrics": {"complexity": 0, "maintainability": 0.0},
105
+ "error": str(e),
106
  })
107
 
108
  new_results_map = {item.get("fileName"): item for item in new_results if isinstance(item, dict)}
 
127
  self._save_cached_results(to_cache)
128
  return results
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def _process_batch(self, batch: list) -> list:
131
  combined_code = ""
132
  file_names = []
 
136
  combined_code += f"\n--- FILE: {f.fileName} ---\n{minified_content}\n"
137
  file_names.append(f.fileName)
138
 
139
+ prompt = f"""Review these files. Be ultra-concise.
140
  CRITICAL: The "fileName" field MUST EXACTLY match the file path given in header (e.g. "{file_names[0]}").
141
 
142
  {combined_code}
143
 
144
+ Return ONLY valid JSON object with key "results":
145
+ {{
146
+ "results": [
147
+ {{
148
+ "fileName": "{file_names[0]}",
149
+ "vulnerabilities": [{{"type": "Bug", "line": 1, "description": "short description", "suggestion": "fix suggestion"}}],
150
+ "improvement_suggestions": ["tip"],
151
+ "metrics": {{"complexity": 3, "maintainability": 8.0}}
152
+ }}
153
+ ]
154
+ }}"""
155
  batch_results = []
156
  try:
157
+ response_text = llm_engine.generate(prompt, max_tokens=2048)
158
  parsed = self._parse_json(response_text)
159
+
160
+ results_list = parsed.get("results", []) if isinstance(parsed, dict) else (parsed if isinstance(parsed, list) else [])
161
+ processed_map = {item.get("fileName"): item for item in results_list if isinstance(item, dict)}
162
 
163
  for fn in file_names:
164
  if fn in processed_map:
 
182
  "vulnerabilities": [],
183
  "improvement_suggestions": [],
184
  "metrics": {"complexity": 0, "maintainability": 0.0},
185
+ "error": str(e),
186
  })
187
  return batch_results
188
 
 
202
  continue
203
  cleaned_lines.append(stripped)
204
 
205
+ return "\n".join(cleaned_lines[:400])
206
 
207
  def _parse_json(self, text: str):
208
  text = text.strip()
209
  if not text:
210
+ return {}
211
 
212
  text = re.sub(r"```(?:json)?", "", text, flags=re.IGNORECASE).strip()
 
 
 
 
 
213
 
214
  try:
215
  return json.loads(text)
216
  except json.JSONDecodeError:
217
+ start_idx = text.find('{')
218
+ end_idx = text.rfind('}')
219
+ if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
220
+ try:
221
+ return json.loads(text[start_idx : end_idx + 1])
222
+ except json.JSONDecodeError:
223
+ return {}
224
+ return {}
225
 
226
  service = AIReviewerService()