File size: 5,111 Bytes
2a54d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
---

title: AI Code Review Environment
emoji: πŸ”
colorFrom: blue
colorTo: indigo
sdk: docker
sdk_version: latest
pinned: false
---


# AI Code Review Environment

## Environment Overview and Motivation

This is a realistic reinforcement learning environment built for the OpenEnv Hackathon. An AI agent acts as a code reviewer: it receives code snippets containing real bugs and must flag, explain, and fix issues β€” earning rewards for accuracy and losing points for false alarms.

Every engineering team does code review. It's a high-value, well-defined task with:
- Clear correct/incorrect states (expected issues are ground-truth)
- Progressive difficulty (syntax β†’ logic β†’ architecture)
- Deterministic grading (no human judgment needed)
- Rich reward signal (partial credit, severity weighting)

This environment teaches an AI agent to review code the way a senior engineer would: systematically, precisely, and with clear explanations.

## Action and Observation Spaces

### Observation
```python

class Observation(BaseModel):

    code_snippet: str          # The code to review

    step_number: int           # Current step in the episode

    max_steps: int             # Maximum steps allowed

    issues_found_so_far: List[int]  # Line numbers of issues already flagged

    task_name: str             # Difficulty level: "easy", "medium", or "hard"

```

### Action
```python

class Action(BaseModel):

    action_type: str           # Currently "FLAG_BUG"

    line_number: Optional[int] # Line number to flag (1-based)

    issue_type: Optional[str]  # Type of issue (e.g., "syntax", "logic", "security")

    comment: Optional[str]     # Explanation of the issue

```

### Reward
- +1.0: Correctly flagging a new issue
- -0.2: Incorrectly flagging a line or taking invalid action
- Rewards are given per step, encouraging incremental progress

## Tasks

### Task 1 β€” Easy: fix_syntax_and_obvious_bugs
**Code**: A short Python function to calculate an average  
**Issues (3)**:
- Off-by-one error in range() β†’ IndexError
- Syntax error: = instead of == in if condition
- Potential ZeroDivisionError for empty input  
**Max steps**: 8  
**Grader**: issues_correctly_found / 3

### Task 2 β€” Medium: logic_and_security_review

**Code**: A Flask-style route handler querying a database  

**Issues (4)**:

- SQL Injection via f-string interpolation (critical)

- No authentication check before returning user data

- Implicit None return instead of 404 response

- Database connection never closed (resource leak)  

**Max steps**: 12  

**Grader**: issues_correctly_found / 4



### Task 3 β€” Hard: design_and_architecture_review
**Code**: An OrderProcessor class managing a pipeline  
**Issues (5)**:
- Hardcoded database password in source code
- Mutable default argument (pending_orders=[])

- SRP violation: email sending inside order processor

- Swallowed exception with bare except: pass

- Thread-safety bug: read-modify-write without lock  

**Max steps**: 18  

**Grader**: issues_correctly_found / 5



## Setup and Usage



### Local Development

1. Install dependencies:

   ```bash

   pip install -r requirements.txt

   ```



2. Run the environment server:

   ```bash

   python -m server.app

   ```



3. In another terminal, run the baseline inference:

   ```bash

   export HF_TOKEN="your-huggingface-token"
   python inference.py
   ```



### Docker

```bash

docker build -t ai-code-review .

docker run -p 7860:7860 ai-code-review

```

### OpenEnv Validation
```bash

pip install openenv-core

openenv validate

```

## Baseline Performance Scores

When an agent correctly identifies all bugs in each task:

| Task | Difficulty | Issues | Perfect Score |
|------|-----------|--------|---------------|
| Easy | ⭐ | 3/3 | **100.0%** |
| Medium | ⭐⭐ | 4/4 | **100.0%** |
| Hard | ⭐⭐⭐ | 5/5 | **100.0%** |
| **Overall Average** | - | - | **100.0%** |

### Scoring Mechanism

- **+1.0 reward**: Each correctly flagged bug (first time only)
- **-0.2 penalty**: False alarms or invalid actions
- **Final score**: (bugs_correctly_found / total_bugs_in_task)

- **Score range**: 0.0 (no issues) to 1.0 (all issues found perfectly)



### Example Agent Performance



Using Google Flan-T5-Base via Hugging Face API with initial prompt engineering:

- Easy: 0.333 (1/3 issues found)

- Medium: 0.250 (1/4 issues found)  

- Hard: 0.200 (1/5 issues found)

- Average: 0.261



*Note: Baseline scores depend on model capability and prompt engineering. The environment cycles through tasks during inference, evaluating all three difficulty levels in sequence.*



## Alternative Models



You can use different Hugging Face models by setting:

```bash

export MODEL_NAME="microsoft/codebert-base"  # or other HF models
```



## Deployment



This environment is designed for deployment on Hugging Face Spaces. Tag your space with `openenv` for discoverability.



The containerized application exposes a FastAPI server on port 7860 with endpoints for reset, step, state, and score.