Spaces:
Runtime error
Runtime error
Download baseline.py from Krsnapriya/CodeReviewEnv-Elite: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/Krsnapriya/CodeReviewEnv-Elite/resolve/main/baseline.py
- Command line
-
hf download hf://spaces/Krsnapriya/CodeReviewEnv-Elite/baseline.py
-
curl -L -o baseline.py https://huggingface.co/spaces/Krsnapriya/CodeReviewEnv-Elite/resolve/main/baseline.py
10.3 kB
| # pyre-ignore-all-errors | |
| """ | |
| Baseline inference script for CodeReviewEnv-RX. | |
| Two modes: | |
| 1. Heuristic baseline: step-aware agent (no API key needed) | |
| 2. LLM baseline: uses Groq API for multi-step reasoning (requires GROQ_API_KEY) | |
| """ | |
| import os | |
| import sys | |
| import json | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from server.env import CodeReviewEnv | |
| from models import Action | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Heuristic Baseline (step-aware, deterministic) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_heuristic_baseline() -> dict: | |
| """ | |
| Step-aware heuristic agent: | |
| 1. Opens each file | |
| 2. Inspects lines looking for suspicious patterns | |
| 3. Flags issues when patterns match | |
| Fully deterministic and reproducible. | |
| """ | |
| BUG_PATTERNS = [ | |
| ("/ ", "bug"), | |
| ("+ price", "bug"), | |
| ("a + b", "bug"), | |
| ("open(", "bug"), | |
| ("config[key]", "bug"), | |
| ("[key]", "bug"), | |
| ("round(", "bug"), | |
| ("/ 0", "bug"), | |
| ("zip(", "bug"), | |
| ("/ len", "bug"), | |
| ("/ sum", "bug"), | |
| ("f\"SELECT", "bug"), | |
| ("md5(", "bug"), | |
| ("f\"/data/", "bug"), | |
| ("API_KEY =", "bug"), | |
| ("global balance", "bug"), | |
| (".acquire()", "bug"), | |
| (".append(", "bug"), | |
| ("return []", "bug"), | |
| ("return False", "bug"), | |
| ("validate_record(record)", "bug"), | |
| ("value / (value", "bug"), | |
| ("/ total", "bug"), | |
| ("max(values)", "bug"), | |
| ] | |
| from tasks import get_tasks | |
| all_levels = list(get_tasks().keys()) | |
| scores = {} | |
| details = {} | |
| for level in all_levels: | |
| env = CodeReviewEnv(task_level=level, seed=42) | |
| obs = env.reset() | |
| actions_taken = [] | |
| file_list = obs.available_files | |
| for fname in file_list: | |
| if env.done: | |
| break | |
| # Step 1: Open the file | |
| try: | |
| obs, reward = env.step(Action(action_type="open_file", file_name=fname)) | |
| actions_taken.append({ | |
| "action": "open_file", "file": fname, | |
| "reward": reward.reward, "result": reward.info.get("type", "") | |
| }) | |
| except ValueError: | |
| break | |
| # Get lines for this file | |
| file_lines = env.file_lines.get(fname, []) | |
| for i in range(1, len(file_lines) + 1): | |
| if env.done: | |
| break | |
| line_content = file_lines[i - 1] if i - 1 < len(file_lines) else "" | |
| stripped = line_content.strip() | |
| if not stripped or stripped.startswith("#") or stripped.startswith('"""'): | |
| continue | |
| # Check if line matches any pattern | |
| matched_pattern = None | |
| for pattern, issue_type in BUG_PATTERNS: | |
| if pattern in line_content: | |
| matched_pattern = (pattern, issue_type) | |
| break | |
| if matched_pattern is None: | |
| continue | |
| # Step 2: Inspect the line | |
| try: | |
| obs, reward = env.step(Action( | |
| action_type="inspect", line_number=i | |
| )) | |
| actions_taken.append({ | |
| "action": "inspect", "file": fname, "line": i, | |
| "reward": reward.reward, "result": reward.info.get("type", "") | |
| }) | |
| except ValueError: | |
| break | |
| if env.done: | |
| break | |
| # Step 3: Flag the issue | |
| try: | |
| obs, reward = env.step(Action( | |
| action_type="flag", | |
| line_number=i, | |
| issue_type=matched_pattern[1], | |
| suggestion=f"Heuristic: suspicious pattern '{matched_pattern[0]}' detected" | |
| )) | |
| actions_taken.append({ | |
| "action": "flag", "file": fname, "line": i, | |
| "type": matched_pattern[1], | |
| "reward": reward.reward, | |
| "result": reward.info.get("result", "unknown") | |
| }) | |
| except ValueError: | |
| break | |
| grade = env.grade_episode() | |
| scores[level] = grade.score | |
| details[level] = { | |
| "score": grade.score, | |
| "breakdown": grade.breakdown, | |
| "steps_taken": env.steps, | |
| "time_used": env.time_used, | |
| "correct_flags": len(env.correct_flags), | |
| "false_flags": env.false_flags, | |
| "files_visited": len(env.visited_files), | |
| "lines_inspected": len(env.inspected), | |
| "actions": actions_taken, | |
| } | |
| return {"scores": scores, "details": details} | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # LLM Baseline (requires GROQ_API_KEY) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_llm_baseline() -> dict: | |
| """ | |
| Multi-step LLM agent: | |
| 1. Opens each file | |
| 2. Inspects lines in batches | |
| 3. Uses Groq API to analyze visible code | |
| 4. Flags identified issues | |
| """ | |
| try: | |
| from groq import Groq | |
| except ImportError: | |
| return {"error": "groq package not installed. Run: pip install groq"} | |
| api_key = os.environ.get("GROQ_API_KEY") | |
| if not api_key: | |
| return {"error": "GROQ_API_KEY environment variable not set"} | |
| client = Groq(api_key=api_key) | |
| scores = {} | |
| from tasks import get_tasks | |
| all_levels = list(get_tasks().keys()) | |
| for level in all_levels: | |
| env = CodeReviewEnv(task_level=level, seed=42) | |
| obs = env.reset() | |
| file_list = obs.available_files | |
| for fname in file_list: | |
| if env.done: | |
| break | |
| # Open the file | |
| try: | |
| obs, _ = env.step(Action(action_type="open_file", file_name=fname)) | |
| except ValueError: | |
| break | |
| # Inspect first 20 lines | |
| file_lines = env.file_lines.get(fname, []) | |
| for i in range(1, min(len(file_lines) + 1, 21)): | |
| if env.done: | |
| break | |
| try: | |
| obs, _ = env.step(Action(action_type="inspect", line_number=i)) | |
| except ValueError: | |
| break | |
| if env.done: | |
| break | |
| # Build the visible code for LLM analysis | |
| visible = obs.visible_code.get(fname, {}) | |
| if not visible: | |
| continue | |
| code_text = "\n".join( | |
| f"{ln}: {content}" for ln, content in sorted(visible.items(), key=lambda x: int(x[0])) | |
| ) | |
| prompt = f"""You are a code reviewer. Analyze the following Python code and identify all bugs. | |
| For each issue, respond with a JSON array where each element has: | |
| - "line_number": the line number (integer) | |
| - "issue_type": one of "bug", "style", or "optimization" | |
| - "suggestion": a brief description of the fix | |
| File: {fname} | |
| ```python | |
| {code_text} | |
| ``` | |
| Respond ONLY with a valid JSON array. No explanation, no markdown.""" | |
| try: | |
| response = client.chat.completions.create( | |
| model="llama-3.3-70b-versatile", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=500, | |
| temperature=0.0, | |
| ) | |
| raw = response.choices[0].message.content.strip() | |
| if raw.startswith("```json"): | |
| raw = raw.replace("```json", "") | |
| if raw.startswith("```"): | |
| raw = raw.replace("```", "") | |
| raw = raw.strip() | |
| issues = json.loads(raw) | |
| except Exception as e: | |
| issues = [] | |
| print(f"LLM error for {level}/{fname}: {e}") | |
| # Submit each identified issue | |
| for issue in issues: | |
| if env.done: | |
| break | |
| try: | |
| action = Action( | |
| action_type="flag", | |
| line_number=issue.get("line_number", 1), | |
| issue_type=issue.get("issue_type", "bug"), | |
| suggestion=issue.get("suggestion", "LLM suggestion"), | |
| ) | |
| obs, _ = env.step(action) | |
| except ValueError: | |
| break | |
| grade = env.grade_episode() | |
| scores[level] = { | |
| "score": grade.score, | |
| "breakdown": grade.breakdown, | |
| "steps": env.steps, | |
| "time_used": env.time_used, | |
| } | |
| return scores | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CLI | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Run CodeReviewEnv-RX baseline") | |
| parser.add_argument( | |
| "--mode", | |
| choices=["heuristic", "llm"], | |
| default="heuristic", | |
| help="Baseline mode: 'heuristic' (no API key) or 'llm' (requires GROQ_API_KEY)", | |
| ) | |
| args = parser.parse_args() | |
| if args.mode == "heuristic": | |
| print("Running heuristic baseline...") | |
| result = run_heuristic_baseline() | |
| else: | |
| print("Running LLM baseline...") | |
| result = run_llm_baseline() | |
| print(json.dumps(result, indent=2)) | |