vinith17 commited on
Commit
5235bfa
·
1 Parent(s): ea723d2

feat: complete pivot to strictly compliant OpenEnv hackathon submission

Browse files
Files changed (8) hide show
  1. Dockerfile +10 -0
  2. README.md +45 -40
  3. client.py +34 -0
  4. environment.py +87 -167
  5. inference.py +78 -0
  6. main.py +4 -0
  7. models.py +17 -0
  8. openenv.yaml +6 -0
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+ COPY requirements.txt .
5
+ RUN pip install --no-cache-dir -r requirements.txt
6
+ RUN pip install openenv-core>=0.2.2 fastapi uvicorn pydantic
7
+
8
+ COPY . .
9
+ # 7860 is standard port for HuggingFace Spaces
10
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,40 +1,45 @@
1
- # RL Code Reviewer
2
-
3
- An RL-trained AI agent that reviews code like a senior engineer.
4
- Built for the Code With Antigravity Hackathon.
5
-
6
- ## What it does
7
- - Reviews Python, JS, Java and other code files for bugs
8
- - Catches security vulnerabilities (SQL injection, plain-text passwords)
9
- - Finds logic errors (off-by-one, wrong operators)
10
- - Suggests fixes with a before/after diff view
11
- - Trained with Reinforcement Learning — gets smarter every episode
12
-
13
- ## Tech Stack
14
- - Python + Flask backend
15
- - Anthropic Claude API (claude-haiku) for AI reviews
16
- - Vanilla JavaScript frontend
17
- - RL environment with custom reward function
18
- - Chart.js for training visualization
19
-
20
- ## How to run locally
21
- 1. Install dependencies: `pip install -r requirements.txt`
22
- 2. Set API keys:
23
- - `set ANTHROPIC_API_KEY=your_key_here` (Windows)
24
- - `export ANTHROPIC_API_KEY=your_key_here` (Mac/Linux)
25
- 3. Run the server: `python app.py`
26
- 4. Open http://localhost:5000
27
-
28
- ## Project Structure
29
- - `bug_bank.py` — bug injection engine
30
- - `environment.py` — RL environment (exam room)
31
- - `grader.py` — reward function
32
- - `agent.py` — AI reviewer (calls Claude API)
33
- - `training_loop.py` — training loop
34
- - `app.py` — Flask web server
35
- - `templates/` — HTML landing & dashboard
36
-
37
- ## Built with
38
- Google Antigravity IDE + Claude AI
39
-
40
- © 2025 RL Code Reviewer. Built with ♥ for Antigravity Hackathon.
 
 
 
 
 
 
1
+ # CodeBug - OpenEnv Hackathon Submission
2
+
3
+ CodeBug is an RL environment designed to train agents to analyze and review Python code. The goal is to detect underlying issues within code snippets, determining category, severity, and the specific line where the bug resides.
4
+
5
+ ## Action & Observation Spaces
6
+
7
+ ### Observation Space (`CodeReviewObservation`)
8
+ Provides the agent with the contextual tools to analyze the bug:
9
+ - `code_snippet` (str): The snippet containing a logic, security, or syntax risk.
10
+ - `difficulty` (str): Represents the difficulty of the task (easy, medium, hard).
11
+ - `feedback` (str): Feedback string returned from the environment upon grading an action.
12
+
13
+ ### Action Space (`CodeReviewAction`)
14
+ The agent's review and determination is returned:
15
+ - `category` (str): Type of the bug (logic, security, style, approve).
16
+ - `severity` (int): Scale of 1 to 5.
17
+ - `line_hint` (int): Exact line number containing the vulnerability.
18
+ - `comment` (str): Short explanation of the bug found.
19
+
20
+ ## Setup Instructions
21
+
22
+ ### Installation
23
+
24
+ Install dependencies natively:
25
+ ```bash
26
+ pip install -r requirements.txt
27
+ ```
28
+
29
+ ### Running the Server locally
30
+
31
+ Start the OpenEnv FastAPI backend server locally on port 7860:
32
+ ```bash
33
+ uvicorn main:app --host 0.0.0.0 --port 7860
34
+ ```
35
+
36
+ ### Baseline Inference
37
+
38
+ You can run the baseline inference script strictly with an OpenAI compatible API:
39
+ ```bash
40
+ export API_BASE_URL="https://api.openai.com/v1"
41
+ export MODEL_NAME="gpt-4o-mini"
42
+ export HF_TOKEN="sk-your-huggingface-or-openai-key"
43
+
44
+ python inference.py
45
+ ```
client.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openenv.core.env_client import EnvClient
2
+ from openenv.core.client_types import StepResult
3
+ from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
4
+
5
+ class CodeBugClient(EnvClient[CodeReviewAction, CodeReviewObservation, CodeReviewState]):
6
+ def _step_payload(self, action: CodeReviewAction) -> dict:
7
+ return {
8
+ "category": action.category,
9
+ "severity": action.severity,
10
+ "line_hint": action.line_hint,
11
+ "comment": action.comment
12
+ }
13
+
14
+ def _parse_result(self, payload: dict) -> StepResult:
15
+ obs_data = payload.get("observation", {})
16
+ return StepResult(
17
+ observation=CodeReviewObservation(
18
+ done=payload.get("done", False),
19
+ reward=payload.get("reward"),
20
+ code_snippet=obs_data.get("code_snippet", ""),
21
+ difficulty=obs_data.get("difficulty", ""),
22
+ feedback=obs_data.get("feedback", "")
23
+ ),
24
+ reward=payload.get("reward"),
25
+ done=payload.get("done", False)
26
+ )
27
+
28
+ def _parse_state(self, payload: dict) -> CodeReviewState:
29
+ return CodeReviewState(
30
+ episode_id=payload.get("episode_id"),
31
+ step_count=payload.get("step_count", 0),
32
+ current_task_idx=payload.get("current_task_idx", 0),
33
+ total_score=payload.get("total_score", 0.0)
34
+ )
environment.py CHANGED
@@ -1,174 +1,94 @@
1
- """
2
- environment.py — Code-review RL environment.
3
-
4
- Key improvements:
5
- - reset() uses a shuffled queue that exhausts all episodes before cycling,
6
- preventing repeated sampling of the same snippet within an epoch.
7
- - Episode/answer paths come from config.py.
8
- - Type annotations on all public methods.
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import json
14
- import random
15
- from typing import Any
16
-
17
- from config import ANSWERS_FILE, EPISODES_FILE
18
- from grader import GradeResult, grade
19
-
20
-
21
- class CodeReviewEnv:
22
- def __init__(
23
- self,
24
- episodes_path: str = EPISODES_FILE,
25
- answers_path: str = ANSWERS_FILE,
26
- ) -> None:
27
- with open(episodes_path, "r") as f:
28
- self.episodes: list[dict] = json.load(f)
29
- with open(answers_path, "r") as f:
30
- self.answers: list[dict] = json.load(f)
31
-
32
- # Strip \r artifacts that cause terminal issues on Windows
33
- for ep in self.episodes:
34
- ep["code"] = ep["code"].replace("\r", "")
35
- for ans in self.answers:
36
- if "buggy_code" in ans:
37
- ans["buggy_code"] = ans["buggy_code"].replace("\r", "")
38
-
39
- self.current_episode: dict | None = None
40
- self.episode_index = 0
41
- self.total_reward = 0
42
- self.correct_count = 0
43
- self.best_score = -float("inf")
44
- self.worst_score = float("inf")
45
-
46
- # Shuffled queue — exhausted before refilling (deduplication)
47
- self._queue: list[dict] = []
48
-
49
- # ------------------------------------------------------------------
50
- # Internal helpers
51
- # ------------------------------------------------------------------
52
-
53
- def _refill_queue(self) -> None:
54
- """Shuffle a fresh copy of all episodes into the queue."""
55
- self._queue = list(self.episodes)
56
- random.shuffle(self._queue)
57
-
58
- # ------------------------------------------------------------------
59
- # Public API
60
- # ------------------------------------------------------------------
61
-
62
- def reset(self) -> dict[str, Any]:
63
- """
64
- Pick the next unseen episode from this epoch's shuffled queue.
65
- Once all episodes have been seen, reshuffle and start a new epoch.
66
- """
67
- if not self._queue:
68
- self._refill_queue()
69
-
70
- self.current_episode = self._queue.pop()
71
-
72
- return {
73
- "code": self.current_episode["code"],
74
- "episode_id": self.current_episode["episode_id"],
75
- "snippet_id": self.current_episode["snippet_id"],
76
- "instructions": (
77
- "Review this code. Find bugs, security issues, or logic errors. "
78
- "Respond in JSON with keys: type (flag or approve), "
79
- "category (security/logic/style/ok), "
80
- "line_hint (brief description of where the issue is), "
81
- "comment (your explanation), severity (1-5)"
82
- ),
83
  }
 
84
 
85
- def step(self, ai_action: dict) -> tuple[int, bool, dict]:
86
- """Execute one review step and return (reward, done, info)."""
87
- ground_truth = self._get_answer(self.current_episode["episode_id"])
88
-
89
- result = grade(ai_action, ground_truth)
90
- reward = result.reward
91
 
92
- self.total_reward += reward
93
- self.episode_index += 1
94
-
95
- if result.correct:
96
- self.correct_count += 1
97
-
98
- if reward > self.best_score:
99
- self.best_score = reward
100
- if reward < self.worst_score:
101
- self.worst_score = reward
 
 
 
 
 
102
 
103
- if ground_truth and "bug" in ground_truth:
104
- truth_str = f"{ground_truth['bug']['type']} severity {ground_truth['bug']['severity']}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  else:
106
- truth_str = "None"
107
-
108
- info = {
109
- "episode_id": self.current_episode["episode_id"],
110
- "ai_said": f"{ai_action.get('type')} / {ai_action.get('category')}",
111
- "truth": truth_str,
112
- "correct": result.correct,
113
- "breakdown": result.breakdown,
114
- }
115
-
116
- return reward, True, info
117
-
118
- def _get_answer(self, episode_id: str) -> dict | None:
119
- for ans in self.answers:
120
- if ans["episode_id"] == episode_id:
121
- return ans
122
- return None
123
-
124
- def get_stats(self) -> dict:
125
- avg_r = self.total_reward / self.episode_index if self.episode_index > 0 else 0
126
- accuracy = self.correct_count / self.episode_index if self.episode_index > 0 else 0
127
- return {
128
- "total_reward": self.total_reward,
129
- "episodes_run": self.episode_index,
130
- "average_reward": avg_r,
131
- "accuracy": accuracy,
132
- "best_score": self.best_score if self.best_score != -float("inf") else 0,
133
- "worst_score": self.worst_score if self.worst_score != float("inf") else 0,
134
- }
135
-
136
- def render(self, observation: dict, ai_action: dict, reward: int, info: dict) -> None:
137
- lines = observation["code"].splitlines()
138
- code_preview = "".join(f" {l}\n" for l in lines[:3])
139
-
140
- print("\n" + "-" * 40)
141
- print(f"Episode: {observation['episode_id']}")
142
- print("Code snippet:")
143
- print(code_preview, end="")
144
- print(" ...")
145
- print(f"\nAI said: {info['ai_said']}")
146
- print(f"Truth was: {info['truth']}")
147
- print(f"Correct: {info['correct']}")
148
- print(f"Reward: {reward:+d}")
149
- print(f"Total so far: {self.total_reward}")
150
- print("-" * 40)
151
-
152
-
153
- # ---------------------------------------------------------------------------
154
- # Test block
155
- # ---------------------------------------------------------------------------
156
-
157
- if __name__ == "__main__":
158
- env = CodeReviewEnv()
159
- print("Starting 5-episode simulation (shuffled queue)...\n")
160
-
161
- for i in range(5):
162
- obs = env.reset()
163
- fake_action = (
164
- {"type": "flag", "category": "security", "line_hint": "line 3",
165
- "comment": "Possible SQL injection vulnerability", "severity": 5}
166
- if i % 2 == 0
167
- else {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0}
168
  )
169
- reward, done, info = env.step(fake_action)
170
- env.render(obs, fake_action, reward, info)
171
 
172
- print("\nFinal Stats:")
173
- import pprint
174
- pprint.pprint(env.get_stats())
 
1
+ import uuid
2
+ from openenv.core.env_server import Environment
3
+ from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
4
+
5
+ class CodeBugEnvironment(Environment):
6
+ SUPPORTS_CONCURRENT_SESSIONS = True
7
+
8
+ # 3 minimum tasks: easy -> medium -> hard
9
+ TASKS = [
10
+ {
11
+ "difficulty": "easy",
12
+ "snippet": "def transfer(from_account, to_account, amount):\n if from_account.balance > amount:\n from_account.balance -= amount\n to_account.balance += amount\n return True\n return False",
13
+ "truth": {"category": "logic", "severity": 4, "line_hint": 2}
14
+ },
15
+ {
16
+ "difficulty": "medium",
17
+ "snippet": "def find_max(numbers):\n if not numbers:\n return None\n max_val = numbers[0]\n for i in range(len(numbers) - 1):\n if numbers[i] > max_val:\n max_val = numbers[i]\n return max_val",
18
+ "truth": {"category": "logic", "severity": 3, "line_hint": 5}
19
+ },
20
+ {
21
+ "difficulty": "hard",
22
+ "snippet": "def login(username, password):\n query = f\"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'\"\n user = db.execute(query)\n if user:\n return True\n return False",
23
+ "truth": {"category": "security", "severity": 5, "line_hint": 3}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
+ ]
26
 
27
+ def __init__(self):
28
+ self._state = CodeReviewState()
 
 
 
 
29
 
30
+ def reset(self, seed=None, episode_id=None, **kwargs) -> CodeReviewObservation:
31
+ self._state = CodeReviewState(
32
+ episode_id=episode_id or str(uuid.uuid4()),
33
+ step_count=0,
34
+ current_task_idx=0,
35
+ total_score=0.0
36
+ )
37
+ task = self.TASKS[0]
38
+ return CodeReviewObservation(
39
+ done=False,
40
+ reward=None,
41
+ code_snippet=task["snippet"],
42
+ difficulty=task["difficulty"],
43
+ feedback="Scan the snippet and provide your code review action (category, severity, line_hint)."
44
+ )
45
 
46
+ def step(self, action: CodeReviewAction, timeout_s=None, **kwargs) -> CodeReviewObservation:
47
+ self._state.step_count += 1
48
+
49
+ idx = self._state.current_task_idx
50
+ task = self.TASKS[idx]
51
+ truth = task["truth"]
52
+
53
+ # Reward Scale 0.0 -> 1.0 (strict Hackathon requirement)
54
+ reward = 0.0
55
+
56
+ is_correct_category = action.category.strip().lower() == truth["category"]
57
+ if is_correct_category:
58
+ reward += 0.5
59
+
60
+ severity_diff = abs(action.severity - truth["severity"])
61
+ if severity_diff == 0:
62
+ reward += 0.3
63
+ elif severity_diff == 1:
64
+ reward += 0.15
65
+
66
+ if action.line_hint == truth["line_hint"]:
67
+ reward += 0.2
68
+
69
+ self._state.total_score += reward
70
+ self._state.current_task_idx += 1
71
+
72
+ done = self._state.current_task_idx >= len(self.TASKS)
73
+
74
+ if done:
75
+ next_snippet = ""
76
+ next_diff = ""
77
+ feedback = f"Final evaluation complete! Score for this run: {self._state.total_score:.2f} / {len(self.TASKS)}"
78
  else:
79
+ next_task = self.TASKS[self._state.current_task_idx]
80
+ next_snippet = next_task["snippet"]
81
+ next_diff = next_task["difficulty"]
82
+ feedback = f"Task graded! Reward received: {reward:.2f}. Proceed to the next snippet."
83
+
84
+ return CodeReviewObservation(
85
+ done=done,
86
+ reward=reward,
87
+ code_snippet=next_snippet,
88
+ difficulty=next_diff,
89
+ feedback=feedback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
 
 
91
 
92
+ @property
93
+ def state(self) -> CodeReviewState:
94
+ return self._state
inference.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from openai import OpenAI
4
+ from environment import CodeBugEnvironment
5
+ from models import CodeReviewAction
6
+
7
+ def run_inference():
8
+ # Read required environment variables
9
+ api_base = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
10
+ model_name = os.environ.get("MODEL_NAME", "gpt-3.5-turbo")
11
+ hf_token = os.environ.get("HF_TOKEN")
12
+
13
+ # Initialize OpenEnv environment locally for baseline test
14
+ env = CodeBugEnvironment()
15
+ obs = env.reset()
16
+
17
+ print(f"[START] Episode {env.state.episode_id}")
18
+
19
+ client = OpenAI(
20
+ api_key=hf_token, # HF_TOKEN acts as the API key per instructions
21
+ base_url=api_base
22
+ )
23
+
24
+ total_reward = 0.0
25
+ step_count = 0
26
+
27
+ while not obs.done:
28
+ step_count += 1
29
+
30
+ prompt = f"""
31
+ You are a code review agent. Difficulty: {obs.difficulty}.
32
+ Given this code snippet:
33
+ {obs.code_snippet}
34
+
35
+ Output a valid JSON matching this schema exactly:
36
+ {{
37
+ "category": "logic | security | style | approve",
38
+ "severity": 1-5 (int),
39
+ "line_hint": line number where bug exists (int),
40
+ "comment": "short description"
41
+ }}
42
+ """
43
+
44
+ try:
45
+ response = client.chat.completions.create(
46
+ model=model_name,
47
+ messages=[{"role": "user", "content": prompt}],
48
+ response_format={ "type": "json_object" }
49
+ )
50
+ raw_action = json.loads(response.choices[0].message.content)
51
+
52
+ action = CodeReviewAction(
53
+ category=raw_action.get("category", "style"),
54
+ severity=int(raw_action.get("severity", 1)),
55
+ line_hint=int(raw_action.get("line_hint", 0)) if raw_action.get("line_hint") else None,
56
+ comment=raw_action.get("comment", "")
57
+ )
58
+ except Exception as e:
59
+ # Fallback action on parsing failure
60
+ action = CodeReviewAction(
61
+ category="approve",
62
+ severity=1,
63
+ line_hint=None,
64
+ comment="Failed to parse LLM output."
65
+ )
66
+
67
+ print(f"[STEP] Sending Action -> Category: {action.category}, Severity: {action.severity}")
68
+
69
+ # Step environment
70
+ obs = env.step(action)
71
+ total_reward += obs.reward or 0.0
72
+
73
+ print(f"[STEP] Result -> Reward: {obs.reward:.2f} | Info: {obs.feedback}")
74
+
75
+ print(f"[END] Total Reward: {total_reward:.2f}")
76
+
77
+ if __name__ == "__main__":
78
+ run_inference()
main.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from openenv.core.env_server import create_fastapi_app
2
+ from environment import CodeBugEnvironment
3
+
4
+ app = create_fastapi_app(CodeBugEnvironment)
models.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from openenv.core.env_server import Action, Observation, State
3
+
4
+ class CodeReviewAction(Action):
5
+ category: str # E.g., 'security', 'logic', 'style', 'approve'
6
+ severity: int # 1 to 5 (5 is most severe)
7
+ line_hint: Optional[int]
8
+ comment: str # Short explanation of the bug
9
+
10
+ class CodeReviewObservation(Observation):
11
+ code_snippet: str
12
+ difficulty: str # 'easy', 'medium', 'hard'
13
+ feedback: str # Message to the agent
14
+
15
+ class CodeReviewState(State):
16
+ current_task_idx: int = 0
17
+ total_score: float = 0.0
openenv.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ name: "CodeBug Review Environment"
2
+ version: "1.0.0"
3
+ description: "AI Agent performs Code Review (finding logic, security bugs) across 3 distinct tasks of sequential difficulties (easy, medium, hard)."
4
+ entry_point: "main:app"
5
+ author: "CodeBug Team"
6
+ tags: ["rl", "code-review", "agent", "security"]