Zaidoppa commited on
Commit
bfb35fc
·
verified ·
1 Parent(s): 2448b1e

Upload 9 files

Browse files
Files changed (9) hide show
  1. DockerFile +30 -0
  2. baseline.py +177 -0
  3. easy_style.json +24 -0
  4. env.py +82 -0
  5. hard_logic.json +25 -0
  6. medium_secret.json +24 -0
  7. models.py +28 -0
  8. openenv.yaml +11 -0
  9. requirements.txt +3 -0
DockerFile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official lightweight Python image
2
+ FROM python:3.10-slim
3
+
4
+ # Create a non-root user (Hugging Face Spaces requirement)
5
+ RUN useradd -m -u 1000 user
6
+
7
+ # Set the working directory
8
+ WORKDIR /app
9
+
10
+ # Copy requirements first to leverage Docker caching
11
+ COPY requirements.txt .
12
+
13
+ # Install dependencies
14
+ RUN pip install --no-cache-dir -r requirements.txt
15
+
16
+ # Copy the rest of your environment files into the container
17
+ COPY . .
18
+
19
+ # Change ownership of the files to the non-root user
20
+ RUN chown -R user:user /app
21
+
22
+ # Switch to the non-root user
23
+ USER user
24
+
25
+ # Set environment variables required by Hugging Face
26
+ ENV HOME=/home/user \
27
+ PATH=/home/user/.local/bin:$PATH
28
+
29
+ # Define the default command to run your benchmark
30
+ CMD ["python", "baseline.py"]
baseline.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+ from pydantic import ValidationError
5
+
6
+ # Try to load Anthropic, but don't crash if the user hasn't installed it
7
+ try:
8
+ import anthropic
9
+ ANTHROPIC_AVAILABLE = True
10
+ except ImportError:
11
+ ANTHROPIC_AVAILABLE = False
12
+
13
+ from openai import OpenAI
14
+ from models import Action
15
+ from env import RepoReviewerEnv
16
+
17
+ class UniversalClient:
18
+ """A wrapper that standardizes calls to OpenAI, Gemini, Claude, and Ollama."""
19
+ def __init__(self, provider: str, model: str, api_key: str):
20
+ self.provider = provider
21
+ self.model = model
22
+ self.api_key = api_key
23
+
24
+ if self.provider == "openai":
25
+ self.client = OpenAI(api_key=self.api_key)
26
+ elif self.provider == "gemini":
27
+ # Secret Trick: Gemini has an OpenAI-compatible endpoint!
28
+ self.client = OpenAI(
29
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
30
+ api_key=self.api_key
31
+ )
32
+ elif self.provider == "anthropic":
33
+ if not ANTHROPIC_AVAILABLE:
34
+ raise ImportError("You must `pip install anthropic` to use Claude.")
35
+ self.client = anthropic.Anthropic(api_key=self.api_key)
36
+ elif self.provider == "ollama":
37
+ self.client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
38
+ else:
39
+ # Fallback for custom endpoints (Groq, DeepSeek, Together, vLLM)
40
+ self.client = OpenAI(base_url=self.provider, api_key=self.api_key)
41
+
42
+ def generate_json(self, messages: list) -> str:
43
+ """Sends the payload to the LLM and forces a JSON string response."""
44
+ if self.provider == "anthropic":
45
+ # Claude handles system prompts differently
46
+ system_prompt = next((m["content"] for m in messages if m["role"] == "system"), "")
47
+ user_msgs = [m for m in messages if m["role"] != "system"]
48
+
49
+ response = self.client.messages.create(
50
+ model=self.model,
51
+ system=system_prompt,
52
+ messages=user_msgs,
53
+ max_tokens=1024,
54
+ temperature=0.0
55
+ )
56
+ return response.content[0].text
57
+ else:
58
+ # Everyone else (OpenAI, Gemini, Ollama, Groq) uses this standard call
59
+ response = self.client.chat.completions.create(
60
+ model=self.model,
61
+ messages=messages,
62
+ response_format={"type": "json_object"},
63
+ temperature=0.0
64
+ )
65
+ return response.choices[0].message.content
66
+
67
+ def detect_best_provider(args) -> tuple[str, str, str]:
68
+ """Auto-detects the best model based on the user's environment variables."""
69
+ # 1. If user passed explicit arguments, use those
70
+ if args.provider and args.provider != "auto":
71
+ return args.provider, args.model, args.key
72
+
73
+ # 2. Auto-detect based on API Keys
74
+ if os.environ.get("OPENAI_API_KEY"):
75
+ print("\n[Auto-Detect] Found OPENAI_API_KEY. Using GPT-4o.")
76
+ return "openai", "gpt-4o", os.environ.get("OPENAI_API_KEY")
77
+ elif os.environ.get("ANTHROPIC_API_KEY") and ANTHROPIC_AVAILABLE:
78
+ print("\n[Auto-Detect] Found ANTHROPIC_API_KEY. Using Claude 3.5 Sonnet.")
79
+ return "anthropic", "claude-3-5-sonnet-20241022", os.environ.get("ANTHROPIC_API_KEY")
80
+ elif os.environ.get("GEMINI_API_KEY"):
81
+ print("\n[Auto-Detect] Found GEMINI_API_KEY. Using Gemini 2.5 Flash.")
82
+ return "gemini", "gemini-2.5-flash", os.environ.get("GEMINI_API_KEY")
83
+ else:
84
+ print("\n[Auto-Detect] No API keys found. Defaulting to local Ollama (Llama 3).")
85
+ return "ollama", "llama3", "dummy_key"
86
+
87
+ def evaluate_task(llm: UniversalClient, task_file: str):
88
+ print(f"\n{'='*40}")
89
+ print(f"Starting Task: {task_file}")
90
+ print(f"{'='*40}")
91
+
92
+ env = RepoReviewerEnv(task_path=f"tasks/{task_file}")
93
+ obs = env.reset()
94
+ schema_str = json.dumps(Action.model_json_schema(), indent=2)
95
+
96
+ # --- THE FINAL BOSS PROMPT ---
97
+ system_prompt = (
98
+ "You are an automated code reviewer. You MUST follow this exact sequence:\n"
99
+ "Step 1: run_linter\n"
100
+ "Step 2: run_tests\n"
101
+ "Step 3: view_diff (You MUST do this for every file in 'files_changed' before making a final decision! Do not skip this!)\n"
102
+ "Step 4: Make a terminal decision (approve_pr, reject_pr, request_changes).\n\n"
103
+ "STRICT JSON PARAMETER RULES (NEVER FORGET THESE):\n"
104
+ "- If action is 'request_changes', your JSON MUST include BOTH 'line_number' (integer) and 'comment' (string).\n"
105
+ "- If action is 'reject_pr', your JSON MUST include a 'comment' (string).\n"
106
+ "- If action is 'view_diff', your JSON MUST include 'target_file' (string).\n\n"
107
+ "EVALUATION RULES:\n"
108
+ "- If you see a hardcoded secret/password, use 'reject_pr' and type 'secret' in the comment.\n"
109
+ "- If tests fail due to a logic bug, find the exact line causing it, use 'request_changes', provide the line number, and explain the fix.\n\n"
110
+ "You MUST respond ONLY with valid JSON matching this exact schema:\n"
111
+ f"{schema_str}"
112
+ )
113
+
114
+ messages = [{"role": "system", "content": system_prompt}]
115
+ done = False
116
+ total_reward = 0.0
117
+ step_count = 0
118
+ max_steps = 10
119
+
120
+ while not done and step_count < max_steps:
121
+ print(f"\n--- Step {step_count + 1} ---")
122
+ messages.append({
123
+ "role": "user",
124
+ "content": f"Current State: {obs.model_dump_json()}\n\nWhat is your next action based on the SOP?"
125
+ })
126
+
127
+ try:
128
+ raw_response = llm.generate_json(messages)
129
+ action_dict = json.loads(raw_response)
130
+ action = Action(**action_dict)
131
+ except (json.JSONDecodeError, ValidationError) as e:
132
+ print(f"\n[Warning] Agent generated invalid JSON. Forcing linter fallback.")
133
+ raw_response = '{"action_type":"run_linter"}'
134
+ action = Action(action_type="run_linter")
135
+ except Exception as e:
136
+ print(f"\n[Error] API Connection failed: {e}")
137
+ break
138
+
139
+ print(f"Agent Action: {action.model_dump_json(exclude_none=True)}")
140
+ messages.append({"role": "assistant", "content": raw_response})
141
+
142
+ obs, reward, done, info = env.step(action)
143
+ total_reward += reward
144
+
145
+ print(f"Step Reward: {reward} | Cumulative: {total_reward}")
146
+ if 'evaluation' in info:
147
+ print(f"Result: {info['evaluation']}")
148
+
149
+ step_count += 1
150
+
151
+ if not done:
152
+ print("\nFailed: Reached maximum steps without a terminal decision.")
153
+
154
+ print(f"\nTask Complete. Final Score: {total_reward}")
155
+ return total_reward
156
+
157
+ if __name__ == "__main__":
158
+ parser = argparse.ArgumentParser(description="Run the RepoReviewer Benchmark")
159
+ parser.add_argument("--provider", type=str, default="auto", help="openai, gemini, anthropic, ollama, or a custom base URL.")
160
+ parser.add_argument("--model", type=str, default="llama3", help="The specific model ID to evaluate.")
161
+ parser.add_argument("--key", type=str, default=None, help="Your API key (overrides environment variables).")
162
+
163
+ args = parser.parse_args()
164
+ provider, model, api_key = detect_best_provider(args)
165
+
166
+ # Initialize the universal client
167
+ llm = UniversalClient(provider=provider, model=model, api_key=api_key)
168
+
169
+ tasks = ["easy_style.json", "medium_secret.json", "hard_logic.json"]
170
+ total_benchmark_score = 0
171
+
172
+ for task in tasks:
173
+ total_benchmark_score += evaluate_task(llm, task)
174
+
175
+ print(f"\n{'*'*40}")
176
+ print(f"FINAL BENCHMARK SCORE for {model}: {total_benchmark_score}")
177
+ print(f"{'*'*40}")
easy_style.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pr": {
3
+ "title": "Add math utilities",
4
+ "author": "dev_junior",
5
+ "description": "Added a basic sum function for the calculator.",
6
+ "files_changed": ["src/math_ops.py"]
7
+ },
8
+ "rules": [
9
+ "1. All Python functions must use snake_case.",
10
+ "2. NO HARDCODED SECRETS ALLOWED.",
11
+ "3. All tests must pass."
12
+ ],
13
+ "file_system": {
14
+ "src/math_ops.py": "def calculateSum(a, b):\n return a + b\n"
15
+ },
16
+ "ci_checks": {
17
+ "linter": "Warning: src/math_ops.py line 1 uses camelCase (calculateSum). Expected snake_case.",
18
+ "tests": "1/1 tests passed."
19
+ },
20
+ "target_solution": {
21
+ "action_type": "request_changes",
22
+ "line_number": 1
23
+ }
24
+ }
env.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Tuple, Dict, Any
3
+ from models import Observation, Action, PullRequest
4
+
5
+ class RepoReviewerEnv:
6
+ def __init__(self, task_path: str):
7
+ self.task_path = task_path
8
+ self._done = False
9
+ self._current_obs = None
10
+
11
+ with open(self.task_path, 'r') as f:
12
+ self.task_data = json.load(f)
13
+
14
+ self._mock_file_system = self.task_data.get("file_system", {})
15
+ self._target_solution = self.task_data.get("target_solution", {})
16
+ self._ci_checks = self.task_data.get("ci_checks", {})
17
+
18
+ def reset(self) -> Observation:
19
+ pr_data = self.task_data["pr"]
20
+ self._current_obs = Observation(
21
+ current_pr=PullRequest(**pr_data),
22
+ repo_rules=self.task_data.get("rules", []),
23
+ terminal_output="System initialized. Awaiting review. Hint: Run the linter and tests."
24
+ )
25
+ self._done = False
26
+ return self._current_obs
27
+
28
+ def state(self) -> Observation:
29
+ return self._current_obs
30
+
31
+ def step(self, action: Action) -> Tuple[Observation, float, bool, Dict[str, Any]]:
32
+ if self._done:
33
+ return self._current_obs, 0.0, True, {"msg": "Environment already finished."}
34
+
35
+ reward = 0.0
36
+ info = {}
37
+
38
+ if action.action_type == 'view_diff':
39
+ if action.target_file in self._mock_file_system:
40
+ file_content = self._mock_file_system[action.target_file]
41
+ self._current_obs.terminal_output = f"--- {action.target_file} ---\n{file_content}"
42
+ reward = 0.1
43
+ else:
44
+ self._current_obs.terminal_output = f"Error: File '{action.target_file}' not found."
45
+ reward = -0.1
46
+
47
+ elif action.action_type == 'run_linter':
48
+ self._current_obs.terminal_output = f"Linter Output:\n{self._ci_checks.get('linter', 'No output.')}"
49
+ reward = 0.1
50
+
51
+ elif action.action_type == 'run_tests':
52
+ self._current_obs.terminal_output = f"Test Output:\n{self._ci_checks.get('tests', 'No output.')}"
53
+ reward = 0.1
54
+
55
+ elif action.action_type in ['approve_pr', 'reject_pr', 'request_changes']:
56
+ self._done = True
57
+ expected_action = self._target_solution.get("action_type")
58
+
59
+ if action.action_type != expected_action:
60
+ reward = -1.0
61
+ info['evaluation'] = f"Failure: Agent chose {action.action_type}, expected {expected_action}."
62
+ else:
63
+ is_correct = True
64
+
65
+ expected_line = self._target_solution.get("line_number")
66
+ if expected_line and action.line_number != expected_line:
67
+ is_correct = False
68
+ info['evaluation'] = f"Failure: Wrong line number. Expected {expected_line}, got {action.line_number}."
69
+
70
+ expected_keyword = self._target_solution.get("required_keyword")
71
+ comment = (action.comment or "").lower()
72
+ if expected_keyword and expected_keyword.lower() not in comment:
73
+ is_correct = False
74
+ info['evaluation'] = f"Failure: Missing context. Expected comment to mention '{expected_keyword}'."
75
+
76
+ if is_correct:
77
+ reward = 1.0
78
+ info['evaluation'] = "Success: Correct action and correctly identified the root cause."
79
+ else:
80
+ reward = -0.5
81
+
82
+ return self._current_obs, reward, self._done, info
hard_logic.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pr": {
3
+ "title": "Optimize discount logic",
4
+ "author": "dev_senior",
5
+ "description": "Refactored the apply_discount function to handle zero-value carts.",
6
+ "files_changed": ["src/billing.py"]
7
+ },
8
+ "rules": [
9
+ "1. All Python functions must use snake_case.",
10
+ "2. NO HARDCODED SECRETS ALLOWED.",
11
+ "3. All tests must pass."
12
+ ],
13
+ "file_system": {
14
+ "src/billing.py": "def apply_discount(cart_total, discount_rate):\n if cart_total >= 0:\n return cart_total - (cart_total * discount_rate)\n return cart_total\n"
15
+ },
16
+ "ci_checks": {
17
+ "linter": "No style errors found.",
18
+ "tests": "FAIL: test_negative_cart_value. Expected Exception, got 0."
19
+ },
20
+ "target_solution": {
21
+ "action_type": "request_changes",
22
+ "line_number": 2,
23
+ "required_keyword": ">"
24
+ }
25
+ }
medium_secret.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pr": {
3
+ "title": "Update database connection",
4
+ "author": "dev_mid",
5
+ "description": "Added production database credentials to the config file.",
6
+ "files_changed": ["config/settings.py"]
7
+ },
8
+ "rules": [
9
+ "1. All Python functions must use snake_case.",
10
+ "2. NO HARDCODED SECRETS ALLOWED.",
11
+ "3. All tests must pass."
12
+ ],
13
+ "file_system": {
14
+ "config/settings.py": "import os\n\nDB_HOST = 'prod-db.internal'\nDB_PASS = 'super_secret_p@ssw0rd_123'\nDEBUG = False\n"
15
+ },
16
+ "ci_checks": {
17
+ "linter": "No style errors found.",
18
+ "tests": "12/12 tests passed."
19
+ },
20
+ "target_solution": {
21
+ "action_type": "reject_pr",
22
+ "required_keyword": "secret"
23
+ }
24
+ }
models.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import Optional, List, Literal
3
+
4
+ class PullRequest(BaseModel):
5
+ title: str
6
+ author: str
7
+ description: str
8
+ files_changed: List[str]
9
+
10
+ class Observation(BaseModel):
11
+ current_pr: PullRequest
12
+ repo_rules: List[str]
13
+ terminal_output: str = Field(description="Output from previous actions")
14
+
15
+ ActionType = Literal[
16
+ 'view_diff',
17
+ 'run_linter',
18
+ 'run_tests',
19
+ 'request_changes',
20
+ 'approve_pr',
21
+ 'reject_pr'
22
+ ]
23
+
24
+ class Action(BaseModel):
25
+ action_type: ActionType
26
+ target_file: Optional[str] = Field(None, description="Required for view_diff")
27
+ line_number: Optional[int] = Field(None, description="Required for request_changes")
28
+ comment: Optional[str] = Field(None, description="Required for request_changes or reject_pr")
openenv.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: RepoReviewer
2
+ version: "1.0.0"
3
+ description: "An automated code review environment where the AI agent must inspect Pull Requests, run simulated CI checks, read code diffs, and enforce repository rules to catch bugs and security leaks."
4
+ tags:
5
+ - openenv
6
+ - coding
7
+ - security
8
+ - code-review
9
+ entrypoint: "env:RepoReviewerEnv"
10
+ action_model: "models:Action"
11
+ observation_model: "models:Observation"
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pydantic>=2.0.0
2
+ openai>=1.0.0
3
+ anthropic>=0.15.0