Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- server/code_review_environment.py +57 -229
- server/graders.py +353 -0
server/code_review_environment.py
CHANGED
|
@@ -7,8 +7,8 @@
|
|
| 7 |
"""
|
| 8 |
Code Review Environment Implementation.
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
"""
|
| 13 |
|
| 14 |
from uuid import uuid4
|
|
@@ -35,93 +35,65 @@ except ImportError:
|
|
| 35 |
|
| 36 |
import json
|
| 37 |
from pathlib import Path
|
| 38 |
-
import re
|
| 39 |
-
from difflib import SequenceMatcher
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
"use",
|
| 45 |
-
"the",
|
| 46 |
-
"a",
|
| 47 |
-
"an",
|
| 48 |
-
"to",
|
| 49 |
-
"and",
|
| 50 |
-
"or",
|
| 51 |
-
"of",
|
| 52 |
-
"in",
|
| 53 |
-
"for",
|
| 54 |
-
"with",
|
| 55 |
-
"is",
|
| 56 |
-
"it",
|
| 57 |
-
"on",
|
| 58 |
-
"at",
|
| 59 |
-
"by",
|
| 60 |
-
"from",
|
| 61 |
-
"that",
|
| 62 |
-
}
|
| 63 |
|
| 64 |
|
| 65 |
class CodeReviewEnvironment(Environment):
|
| 66 |
"""
|
| 67 |
-
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
Example:
|
| 73 |
-
>>> env = CodeReviewEnvironment()
|
| 74 |
>>> obs = env.reset()
|
| 75 |
-
>>>
|
| 76 |
-
>>>
|
| 77 |
-
>>> obs = env.step(CodeReviewAction(message="Hello"))
|
| 78 |
-
>>> print(obs.echoed_message) # "Hello"
|
| 79 |
-
>>> print(obs.message_length) # 5
|
| 80 |
"""
|
| 81 |
|
| 82 |
-
# Enable concurrent WebSocket sessions.
|
| 83 |
-
# Set to True if your environment isolates state between instances.
|
| 84 |
-
# When True, multiple WebSocket clients can connect simultaneously, each
|
| 85 |
-
# getting their own environment instance (when using factory mode in app.py).
|
| 86 |
SUPPORTS_CONCURRENT_SESSIONS: bool = True
|
| 87 |
|
| 88 |
-
def __init__(self):
|
| 89 |
-
"""
|
| 90 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 91 |
self._reset_count = 0
|
| 92 |
self.max_steps = 5
|
| 93 |
self.task_index = 0
|
|
|
|
| 94 |
with open(dataset_path) as f:
|
| 95 |
self.dataset = json.load(f)
|
|
|
|
| 96 |
self.reset()
|
| 97 |
|
| 98 |
def reset(self) -> CodeReviewObservation:
|
| 99 |
-
"""
|
| 100 |
-
Reset the environment.
|
| 101 |
-
|
| 102 |
-
Returns:
|
| 103 |
-
CodeReviewObservation with a ready message
|
| 104 |
-
"""
|
| 105 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 106 |
self._reset_count += 1
|
| 107 |
self.task_index += 1
|
| 108 |
|
| 109 |
self.sample = self.dataset[self.task_index % len(self.dataset)]
|
| 110 |
|
| 111 |
-
self.pr
|
| 112 |
-
self.gt
|
| 113 |
self.task_type = self.sample.get("task_type", "unknown")
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
self.history
|
| 116 |
-
self.step_count
|
| 117 |
-
self.done
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
self.issues_identified = []
|
| 121 |
-
self.fix_attempted = False
|
| 122 |
|
| 123 |
return CodeReviewObservation(
|
| 124 |
-
# echoed_message="Code Review environment ready!",
|
| 125 |
pr=self.pr,
|
| 126 |
previous_comments=self.history,
|
| 127 |
step_count=self.step_count,
|
|
@@ -130,41 +102,34 @@ class CodeReviewEnvironment(Environment):
|
|
| 130 |
done=False,
|
| 131 |
)
|
| 132 |
|
| 133 |
-
def step(self, action: CodeReviewAction) ->
|
| 134 |
-
"""
|
| 135 |
-
Execute a step in the environment by echoing the message.
|
| 136 |
-
|
| 137 |
-
Args:
|
| 138 |
-
action: CodeReviewAction containing the message to echo
|
| 139 |
-
|
| 140 |
-
Returns:
|
| 141 |
-
CodeReviewObservation with the echoed message and its length
|
| 142 |
-
"""
|
| 143 |
self._state.step_count += 1
|
| 144 |
-
# print("RAW ACTION TYPE:", type(action))
|
| 145 |
-
# print("RAW ACTION:", action)
|
| 146 |
|
|
|
|
|
|
|
|
|
|
| 147 |
try:
|
| 148 |
if isinstance(action, dict):
|
| 149 |
action = CodeReviewAction(**action)
|
| 150 |
-
|
| 151 |
elif isinstance(action, (list, tuple)):
|
| 152 |
action = CodeReviewAction(
|
| 153 |
action_type=action[0],
|
| 154 |
-
comment=action[1]
|
| 155 |
suggested_code=action[2] if len(action) > 2 else None,
|
| 156 |
-
decision=action[3]
|
| 157 |
)
|
| 158 |
-
|
| 159 |
elif isinstance(action, CodeReviewAction):
|
| 160 |
pass
|
| 161 |
-
|
| 162 |
else:
|
| 163 |
raise ValueError(f"Unsupported action type: {type(action)}")
|
| 164 |
except Exception as e:
|
| 165 |
-
print(f"Error
|
| 166 |
return self._invalid_step()
|
| 167 |
|
|
|
|
|
|
|
|
|
|
| 168 |
self.step_count += 1
|
| 169 |
self.history.append(action)
|
| 170 |
|
|
@@ -174,79 +139,54 @@ class CodeReviewEnvironment(Environment):
|
|
| 174 |
if action.action_type == "suggest_fix":
|
| 175 |
self.fix_attempted = True
|
| 176 |
|
| 177 |
-
|
| 178 |
-
#
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
# Encourage meaningful comments
|
| 183 |
-
if action.comment and len(action.comment) > 30:
|
| 184 |
-
bonus += 0.1
|
| 185 |
-
|
| 186 |
-
# Encourage early correct decisions
|
| 187 |
-
if action.action_type == "final_decision" and self.step_count <= 2:
|
| 188 |
-
bonus += 0.1
|
| 189 |
-
|
| 190 |
-
# Penalize useless steps
|
| 191 |
-
if not action.comment and action.action_type != "final_decision":
|
| 192 |
-
bonus -= 0.1
|
| 193 |
-
|
| 194 |
-
# Penalize long trajectories
|
| 195 |
-
if self.step_count > 3:
|
| 196 |
-
bonus -= 0.05
|
| 197 |
-
|
| 198 |
-
score += bonus
|
| 199 |
-
score = max(0.01, min(score, 0.99))
|
| 200 |
-
# print("Final Score == " , score)
|
| 201 |
|
| 202 |
done = (
|
| 203 |
-
action.action_type == "final_decision"
|
|
|
|
| 204 |
)
|
| 205 |
|
| 206 |
if done:
|
| 207 |
-
score =
|
| 208 |
-
score = max(0.01, min(score, 0.99))
|
| 209 |
|
|
|
|
|
|
|
|
|
|
| 210 |
obs = CodeReviewObservation(
|
| 211 |
pr=self.pr,
|
| 212 |
previous_comments=[a.comment for a in self.history if a.comment],
|
| 213 |
step_count=self.step_count,
|
| 214 |
max_steps=self.max_steps,
|
| 215 |
)
|
| 216 |
-
# print("Obs == " , obs)
|
| 217 |
|
| 218 |
rew = CodeReviewReward(score=score, feedback="graded")
|
| 219 |
-
print("
|
| 220 |
-
|
| 221 |
-
# print("FINAL REWARD TYPE:", type(rew))
|
| 222 |
-
# print("FINAL REWARD:", rew)
|
| 223 |
-
# print("Got the culprit I guess....")
|
| 224 |
|
| 225 |
return CodeReviewStepResponse(
|
| 226 |
observation=obs,
|
| 227 |
reward=rew.score,
|
| 228 |
done=done,
|
| 229 |
info={
|
| 230 |
-
"
|
|
|
|
| 231 |
"issues_identified": len(self.issues_identified),
|
| 232 |
-
"fix_attempted":
|
| 233 |
},
|
| 234 |
)
|
| 235 |
|
| 236 |
@property
|
| 237 |
def state(self) -> State:
|
| 238 |
-
"""
|
| 239 |
-
Get the current environment state.
|
| 240 |
-
|
| 241 |
-
Returns:
|
| 242 |
-
Current State with episode_id and step_count
|
| 243 |
-
"""
|
| 244 |
return self._state
|
| 245 |
|
| 246 |
-
def _invalid_step(self):
|
| 247 |
rew = CodeReviewReward(score=0.0, feedback="invalid action")
|
| 248 |
obs = CodeReviewObservation(
|
| 249 |
-
echoed_message="Invalid action format. Please send a valid CodeReviewAction.",
|
| 250 |
pr=self.pr,
|
| 251 |
previous_comments=[a.comment for a in self.history if a.comment],
|
| 252 |
step_count=self.step_count,
|
|
@@ -257,116 +197,4 @@ class CodeReviewEnvironment(Environment):
|
|
| 257 |
reward=rew,
|
| 258 |
done=True,
|
| 259 |
info={"error": "invalid_action"},
|
| 260 |
-
)
|
| 261 |
-
|
| 262 |
-
def grade_action(self, action, ground_truth):
|
| 263 |
-
score = 0.0
|
| 264 |
-
|
| 265 |
-
# print("Action === ", action)
|
| 266 |
-
# print("Ground truth === ", ground_truth)
|
| 267 |
-
|
| 268 |
-
# ------------------------------
|
| 269 |
-
# ISSUE DETECTION (40%)
|
| 270 |
-
# ------------------------------
|
| 271 |
-
issue_score = self.score_issues(action.comment, ground_truth)
|
| 272 |
-
score += 0.4 * issue_score
|
| 273 |
-
# print("After Issue Score == ", issue_score)
|
| 274 |
-
|
| 275 |
-
# ------------------------------
|
| 276 |
-
# FIX QUALITY (30%)
|
| 277 |
-
# ------------------------------
|
| 278 |
-
fix_score = self.score_fix(action.suggested_code, ground_truth)
|
| 279 |
-
score += 0.3 * fix_score
|
| 280 |
-
|
| 281 |
-
# print("After Fix Score == ", fix_score)
|
| 282 |
-
|
| 283 |
-
# ------------------------------
|
| 284 |
-
# DECISION (30%)
|
| 285 |
-
# ------------------------------
|
| 286 |
-
decision_score = self.score_decision(action, ground_truth)
|
| 287 |
-
score += 0.3 * decision_score
|
| 288 |
-
|
| 289 |
-
# print("After Decision Score == ", decision_score)
|
| 290 |
-
|
| 291 |
-
# ------------------------------
|
| 292 |
-
# CLAMP SCORE
|
| 293 |
-
# ------------------------------
|
| 294 |
-
score = max(0.01, min(score, 0.99))
|
| 295 |
-
|
| 296 |
-
return score
|
| 297 |
-
|
| 298 |
-
def normalize(self, text):
|
| 299 |
-
return (text or "").lower().strip()
|
| 300 |
-
|
| 301 |
-
# ==============================
|
| 302 |
-
# ISSUE MATCH (PARTIAL CREDIT)
|
| 303 |
-
# ==============================
|
| 304 |
-
def score_issues(self, comment, ground_truth):
|
| 305 |
-
issues = ground_truth.get("issues", [])
|
| 306 |
-
if not comment or not issues:
|
| 307 |
-
return 0.0
|
| 308 |
-
|
| 309 |
-
comment = self.normalize(comment)
|
| 310 |
-
|
| 311 |
-
matches = sum(1 for issue in issues if self.normalize(issue) in comment)
|
| 312 |
-
|
| 313 |
-
return matches / len(issues)
|
| 314 |
-
|
| 315 |
-
# ==============================
|
| 316 |
-
# FIX MATCH (FUZZY)
|
| 317 |
-
# ==============================
|
| 318 |
-
def score_fix(self, suggested_code: str, ground_truth: dict) -> float:
|
| 319 |
-
if not suggested_code:
|
| 320 |
-
return 0.0
|
| 321 |
-
|
| 322 |
-
expected_fix = self.normalize(ground_truth.get("fix", ""))
|
| 323 |
-
suggested_code = self.normalize(suggested_code)
|
| 324 |
-
|
| 325 |
-
if not expected_fix:
|
| 326 |
-
return 0.0
|
| 327 |
-
|
| 328 |
-
# 1. Exact / substring match — full score
|
| 329 |
-
if expected_fix in suggested_code:
|
| 330 |
-
return 1.0
|
| 331 |
-
|
| 332 |
-
# 2. Token overlap ignoring stop words
|
| 333 |
-
def code_tokens(text: str) -> list[str]:
|
| 334 |
-
tokens = re.findall(r"[a-zA-Z_]\w*|\d+|[=<>!+\-*/]+", text)
|
| 335 |
-
return [t for t in tokens if t.lower() not in STOP_WORDS]
|
| 336 |
-
|
| 337 |
-
expected_tokens = code_tokens(expected_fix)
|
| 338 |
-
suggested_tokens = set(code_tokens(suggested_code))
|
| 339 |
-
|
| 340 |
-
if not expected_tokens:
|
| 341 |
-
return 0.0
|
| 342 |
-
|
| 343 |
-
token_score = sum(1 for t in expected_tokens if t in suggested_tokens) / len(
|
| 344 |
-
expected_tokens
|
| 345 |
-
)
|
| 346 |
-
|
| 347 |
-
# 3. Sequence similarity as a secondary signal
|
| 348 |
-
seq_score = SequenceMatcher(None, expected_fix, suggested_code).ratio()
|
| 349 |
-
|
| 350 |
-
# Weighted: token overlap matters more than character similarity
|
| 351 |
-
return round(0.7 * token_score + 0.3 * seq_score, 4)
|
| 352 |
-
|
| 353 |
-
# ==============================
|
| 354 |
-
# DECISION MATCH
|
| 355 |
-
# ==============================
|
| 356 |
-
def score_decision(self, action, ground_truth):
|
| 357 |
-
expected = ground_truth.get("decision")
|
| 358 |
-
|
| 359 |
-
# Not a decision step → no contribution
|
| 360 |
-
if action.action_type != "final_decision":
|
| 361 |
-
return 0.0
|
| 362 |
-
|
| 363 |
-
# Missing decision → small penalty
|
| 364 |
-
if not action.decision:
|
| 365 |
-
return 0.0
|
| 366 |
-
|
| 367 |
-
# Correct decision
|
| 368 |
-
if action.decision == expected:
|
| 369 |
-
return 1.0
|
| 370 |
-
|
| 371 |
-
# Wrong decision → partial penalty (not negative)
|
| 372 |
-
return 0.2
|
|
|
|
| 7 |
"""
|
| 8 |
Code Review Environment Implementation.
|
| 9 |
|
| 10 |
+
Supports three grader difficulty levels: "easy", "medium", "hard".
|
| 11 |
+
Pass `grader_level` to the constructor to select the desired tier.
|
| 12 |
"""
|
| 13 |
|
| 14 |
from uuid import uuid4
|
|
|
|
| 35 |
|
| 36 |
import json
|
| 37 |
from pathlib import Path
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
try:
|
| 40 |
+
from .graders import get_grader
|
| 41 |
+
except ImportError:
|
| 42 |
+
from graders import get_grader
|
| 43 |
|
| 44 |
+
dataset_path = Path(__file__).parent.parent / "dataset" / "dataset.json"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
|
| 47 |
class CodeReviewEnvironment(Environment):
|
| 48 |
"""
|
| 49 |
+
Code Review environment with configurable grading difficulty.
|
| 50 |
|
| 51 |
+
Args:
|
| 52 |
+
grader_level: Grading difficulty — one of "easy", "medium", "hard".
|
| 53 |
+
Defaults to "medium".
|
| 54 |
|
| 55 |
Example:
|
| 56 |
+
>>> env = CodeReviewEnvironment(grader_level="hard")
|
| 57 |
>>> obs = env.reset()
|
| 58 |
+
>>> obs = env.step(CodeReviewAction(action_type="final_decision", decision="approve"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
"""
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
SUPPORTS_CONCURRENT_SESSIONS: bool = True
|
| 62 |
|
| 63 |
+
def __init__(self, grader_level: str = "medium"):
|
| 64 |
+
"""Initialise the environment with the chosen grader tier."""
|
| 65 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 66 |
self._reset_count = 0
|
| 67 |
self.max_steps = 5
|
| 68 |
self.task_index = 0
|
| 69 |
+
|
| 70 |
with open(dataset_path) as f:
|
| 71 |
self.dataset = json.load(f)
|
| 72 |
+
|
| 73 |
self.reset()
|
| 74 |
|
| 75 |
def reset(self) -> CodeReviewObservation:
|
| 76 |
+
"""Reset the environment and advance to the next task."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 78 |
self._reset_count += 1
|
| 79 |
self.task_index += 1
|
| 80 |
|
| 81 |
self.sample = self.dataset[self.task_index % len(self.dataset)]
|
| 82 |
|
| 83 |
+
self.pr = CodeReviewPullRequest(**self.sample["pr"])
|
| 84 |
+
self.gt = self.sample["ground_truth"]
|
| 85 |
self.task_type = self.sample.get("task_type", "unknown")
|
| 86 |
+
grader_level = self.task_type if self.task_type in ("easy", "medium", "hard") else "medium"
|
| 87 |
+
self.grader = get_grader(grader_level)
|
| 88 |
+
self.grader_level = grader_level
|
| 89 |
|
| 90 |
+
self.history = []
|
| 91 |
+
self.step_count = 0
|
| 92 |
+
self.done = False
|
| 93 |
+
self.issues_identified = []
|
| 94 |
+
self.fix_attempted = False
|
|
|
|
|
|
|
| 95 |
|
| 96 |
return CodeReviewObservation(
|
|
|
|
| 97 |
pr=self.pr,
|
| 98 |
previous_comments=self.history,
|
| 99 |
step_count=self.step_count,
|
|
|
|
| 102 |
done=False,
|
| 103 |
)
|
| 104 |
|
| 105 |
+
def step(self, action: CodeReviewAction) -> CodeReviewStepResponse: # type: ignore[override]
|
| 106 |
+
"""Execute one step: grade the action and return an observation + reward."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
self._state.step_count += 1
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
# ------------------------------------------------------------------
|
| 110 |
+
# Normalise action into a CodeReviewAction object
|
| 111 |
+
# ------------------------------------------------------------------
|
| 112 |
try:
|
| 113 |
if isinstance(action, dict):
|
| 114 |
action = CodeReviewAction(**action)
|
|
|
|
| 115 |
elif isinstance(action, (list, tuple)):
|
| 116 |
action = CodeReviewAction(
|
| 117 |
action_type=action[0],
|
| 118 |
+
comment=action[1] if len(action) > 1 else None,
|
| 119 |
suggested_code=action[2] if len(action) > 2 else None,
|
| 120 |
+
decision=action[3] if len(action) > 3 else None,
|
| 121 |
)
|
|
|
|
| 122 |
elif isinstance(action, CodeReviewAction):
|
| 123 |
pass
|
|
|
|
| 124 |
else:
|
| 125 |
raise ValueError(f"Unsupported action type: {type(action)}")
|
| 126 |
except Exception as e:
|
| 127 |
+
print(f"Error processing action: {e}")
|
| 128 |
return self._invalid_step()
|
| 129 |
|
| 130 |
+
# ------------------------------------------------------------------
|
| 131 |
+
# Update state
|
| 132 |
+
# ------------------------------------------------------------------
|
| 133 |
self.step_count += 1
|
| 134 |
self.history.append(action)
|
| 135 |
|
|
|
|
| 139 |
if action.action_type == "suggest_fix":
|
| 140 |
self.fix_attempted = True
|
| 141 |
|
| 142 |
+
# ------------------------------------------------------------------
|
| 143 |
+
# Score via the active grader
|
| 144 |
+
# ------------------------------------------------------------------
|
| 145 |
+
score = self.grader.grade_action(action, self.gt)
|
| 146 |
+
bonus = self.grader.compute_step_bonus(action, self.step_count, self.history)
|
| 147 |
|
| 148 |
+
score = max(0.01, min(score + bonus, 0.99))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
done = (
|
| 151 |
+
action.action_type == "final_decision"
|
| 152 |
+
or self.step_count >= self.max_steps
|
| 153 |
)
|
| 154 |
|
| 155 |
if done:
|
| 156 |
+
score = self.grader.compute_done_score(self.history, self.gt)
|
|
|
|
| 157 |
|
| 158 |
+
# ------------------------------------------------------------------
|
| 159 |
+
# Build response
|
| 160 |
+
# ------------------------------------------------------------------
|
| 161 |
obs = CodeReviewObservation(
|
| 162 |
pr=self.pr,
|
| 163 |
previous_comments=[a.comment for a in self.history if a.comment],
|
| 164 |
step_count=self.step_count,
|
| 165 |
max_steps=self.max_steps,
|
| 166 |
)
|
|
|
|
| 167 |
|
| 168 |
rew = CodeReviewReward(score=score, feedback="graded")
|
| 169 |
+
# print(f"[{self.grader_level.upper()}] Step {self.step_count} — Score: {rew.score:.4f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
return CodeReviewStepResponse(
|
| 172 |
observation=obs,
|
| 173 |
reward=rew.score,
|
| 174 |
done=done,
|
| 175 |
info={
|
| 176 |
+
"grader_level": self.grader_level,
|
| 177 |
+
"task_type": self.task_type,
|
| 178 |
"issues_identified": len(self.issues_identified),
|
| 179 |
+
"fix_attempted": self.fix_attempted,
|
| 180 |
},
|
| 181 |
)
|
| 182 |
|
| 183 |
@property
|
| 184 |
def state(self) -> State:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
return self._state
|
| 186 |
|
| 187 |
+
def _invalid_step(self) -> CodeReviewStepResponse:
|
| 188 |
rew = CodeReviewReward(score=0.0, feedback="invalid action")
|
| 189 |
obs = CodeReviewObservation(
|
|
|
|
| 190 |
pr=self.pr,
|
| 191 |
previous_comments=[a.comment for a in self.history if a.comment],
|
| 192 |
step_count=self.step_count,
|
|
|
|
| 197 |
reward=rew,
|
| 198 |
done=True,
|
| 199 |
info={"error": "invalid_action"},
|
| 200 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/graders.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Graders for the Code Review Environment.
|
| 9 |
+
|
| 10 |
+
Three difficulty tiers:
|
| 11 |
+
- EasyGrader : Forgiving. Substring matching, partial credit for wrong decisions.
|
| 12 |
+
- MediumGrader : Balanced. Token overlap, line-level fix matching, recency weighting.
|
| 13 |
+
- HardGrader : Strict. No wrong-decision credit, final-step-only done scoring.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import re
|
| 17 |
+
from difflib import SequenceMatcher
|
| 18 |
+
|
| 19 |
+
STOP_WORDS = {
|
| 20 |
+
"use", "the", "a", "an", "to", "and", "or", "of", "in",
|
| 21 |
+
"for", "with", "is", "it", "on", "at", "by", "from", "that",
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _normalize(text: str) -> str:
|
| 26 |
+
return (text or "").lower().strip()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _code_tokens(text: str) -> list[str]:
|
| 30 |
+
tokens = re.findall(r"[a-zA-Z_]\w*|\d+|[=<>!+\-*/]+", text)
|
| 31 |
+
return [t for t in tokens if t.lower() not in STOP_WORDS]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ==============================================================================
|
| 35 |
+
# Base Grader
|
| 36 |
+
# ==============================================================================
|
| 37 |
+
|
| 38 |
+
class BaseGrader:
|
| 39 |
+
"""
|
| 40 |
+
Shared helpers. Subclasses override score_* and compute_* methods
|
| 41 |
+
to implement their difficulty level.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
# Subclasses set these to configure weights (must sum to 1.0)
|
| 45 |
+
ISSUE_WEIGHT: float = 0.40
|
| 46 |
+
FIX_WEIGHT: float = 0.30
|
| 47 |
+
DECISION_WEIGHT: float = 0.30
|
| 48 |
+
|
| 49 |
+
def grade_action(self, action, ground_truth: dict) -> float:
|
| 50 |
+
score = (
|
| 51 |
+
self.ISSUE_WEIGHT * self.score_issues(action.comment, ground_truth)
|
| 52 |
+
+ self.FIX_WEIGHT * self.score_fix(action.suggested_code, ground_truth)
|
| 53 |
+
+ self.DECISION_WEIGHT * self.score_decision(action, ground_truth)
|
| 54 |
+
)
|
| 55 |
+
return max(0.01, min(score, 0.99))
|
| 56 |
+
|
| 57 |
+
def score_issues(self, comment: str, ground_truth: dict) -> float:
|
| 58 |
+
raise NotImplementedError
|
| 59 |
+
|
| 60 |
+
def score_fix(self, suggested_code: str, ground_truth: dict) -> float:
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
|
| 63 |
+
def score_decision(self, action, ground_truth: dict) -> float:
|
| 64 |
+
raise NotImplementedError
|
| 65 |
+
|
| 66 |
+
def compute_step_bonus(self, action, step_count: int, history: list) -> float:
|
| 67 |
+
raise NotImplementedError
|
| 68 |
+
|
| 69 |
+
def compute_done_score(self, history: list, ground_truth: dict) -> float:
|
| 70 |
+
raise NotImplementedError
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ==============================================================================
|
| 74 |
+
# Easy Grader
|
| 75 |
+
# ==============================================================================
|
| 76 |
+
|
| 77 |
+
class EasyGrader(BaseGrader):
|
| 78 |
+
"""
|
| 79 |
+
Lenient grader. Best for round-1 filtering / warm-up tasks.
|
| 80 |
+
|
| 81 |
+
- Issue detection : simple substring match
|
| 82 |
+
- Fix quality : token overlap + sequence similarity
|
| 83 |
+
- Wrong decision : 0.2 partial credit
|
| 84 |
+
- Done scoring : max over entire history (most forgiving)
|
| 85 |
+
- Bonuses : generous, long trajectories are acceptable
|
| 86 |
+
|
| 87 |
+
Weights: issues=40%, fix=30%, decision=30%
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
ISSUE_WEIGHT = 0.40
|
| 91 |
+
FIX_WEIGHT = 0.30
|
| 92 |
+
DECISION_WEIGHT = 0.30
|
| 93 |
+
|
| 94 |
+
def score_issues(self, comment: str, ground_truth: dict) -> float:
|
| 95 |
+
issues = ground_truth.get("issues", [])
|
| 96 |
+
if not comment or not issues:
|
| 97 |
+
return 0.0
|
| 98 |
+
comment_norm = _normalize(comment)
|
| 99 |
+
matches = sum(1 for issue in issues if _normalize(issue) in comment_norm)
|
| 100 |
+
return matches / len(issues)
|
| 101 |
+
|
| 102 |
+
def score_fix(self, suggested_code: str, ground_truth: dict) -> float:
|
| 103 |
+
if not suggested_code:
|
| 104 |
+
return 0.0
|
| 105 |
+
expected = _normalize(ground_truth.get("fix", ""))
|
| 106 |
+
suggested = _normalize(suggested_code)
|
| 107 |
+
if not expected:
|
| 108 |
+
return 0.0
|
| 109 |
+
if expected in suggested:
|
| 110 |
+
return 1.0
|
| 111 |
+
exp_tok = _code_tokens(expected)
|
| 112 |
+
sug_tok = set(_code_tokens(suggested))
|
| 113 |
+
token_score = (
|
| 114 |
+
sum(1 for t in exp_tok if t in sug_tok) / len(exp_tok) if exp_tok else 0.0
|
| 115 |
+
)
|
| 116 |
+
seq_score = SequenceMatcher(None, expected, suggested).ratio()
|
| 117 |
+
return round(0.7 * token_score + 0.3 * seq_score, 4)
|
| 118 |
+
|
| 119 |
+
def score_decision(self, action, ground_truth: dict) -> float:
|
| 120 |
+
if action.action_type != "final_decision" or not action.decision:
|
| 121 |
+
return 0.0
|
| 122 |
+
if action.decision == ground_truth.get("decision"):
|
| 123 |
+
return 1.0
|
| 124 |
+
return 0.2 # generous partial credit for wrong decision
|
| 125 |
+
|
| 126 |
+
def compute_step_bonus(self, action, step_count: int, history: list) -> float:
|
| 127 |
+
bonus = 0.0
|
| 128 |
+
if action.comment and len(action.comment) > 30:
|
| 129 |
+
bonus += 0.15
|
| 130 |
+
if action.action_type == "final_decision" and step_count <= 3:
|
| 131 |
+
bonus += 0.10
|
| 132 |
+
if not action.comment and action.action_type != "final_decision":
|
| 133 |
+
bonus -= 0.05
|
| 134 |
+
return bonus
|
| 135 |
+
|
| 136 |
+
def compute_done_score(self, history: list, ground_truth: dict) -> float:
|
| 137 |
+
"""Most forgiving: best single action across all of history."""
|
| 138 |
+
scores = [self.grade_action(a, ground_truth) for a in history] or [0.0]
|
| 139 |
+
return max(0.01, min(max(scores), 0.99))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ==============================================================================
|
| 143 |
+
# Medium Grader
|
| 144 |
+
# ==============================================================================
|
| 145 |
+
|
| 146 |
+
class MediumGrader(BaseGrader):
|
| 147 |
+
"""
|
| 148 |
+
Balanced grader. Suitable for main competition rounds.
|
| 149 |
+
|
| 150 |
+
- Issue detection : token overlap + substring fallback
|
| 151 |
+
- Fix quality : token overlap + line-level + sequence similarity
|
| 152 |
+
- Wrong decision : 0.1 partial credit
|
| 153 |
+
- Done scoring : recency-weighted (recent actions matter more)
|
| 154 |
+
- Bonuses : moderate, efficiency is rewarded
|
| 155 |
+
|
| 156 |
+
Weights: issues=42%, fix=30%, decision=28%
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
ISSUE_WEIGHT = 0.42
|
| 160 |
+
FIX_WEIGHT = 0.30
|
| 161 |
+
DECISION_WEIGHT = 0.28
|
| 162 |
+
|
| 163 |
+
def score_issues(self, comment: str, ground_truth: dict) -> float:
|
| 164 |
+
issues = ground_truth.get("issues", [])
|
| 165 |
+
if not comment or not issues:
|
| 166 |
+
return 0.0
|
| 167 |
+
comment_text = _normalize(comment)
|
| 168 |
+
comment_tokens = set(re.findall(r"[a-zA-Z_]\w*", comment_text)) - STOP_WORDS
|
| 169 |
+
best_scores = []
|
| 170 |
+
for issue in issues:
|
| 171 |
+
issue_text = _normalize(issue)
|
| 172 |
+
issue_tokens = set(re.findall(r"[a-zA-Z_]\w*", issue_text)) - STOP_WORDS
|
| 173 |
+
if not issue_tokens:
|
| 174 |
+
continue
|
| 175 |
+
overlap = len(issue_tokens & comment_tokens) / len(issue_tokens)
|
| 176 |
+
substring = 1.0 if issue_text in comment_text else 0.0
|
| 177 |
+
best_scores.append(max(overlap, substring))
|
| 178 |
+
return round(sum(best_scores) / len(issues), 4) if best_scores else 0.0
|
| 179 |
+
|
| 180 |
+
def score_fix(self, suggested_code: str, ground_truth: dict) -> float:
|
| 181 |
+
if not suggested_code:
|
| 182 |
+
return 0.0
|
| 183 |
+
expected = _normalize(ground_truth.get("fix", ""))
|
| 184 |
+
suggested = _normalize(suggested_code)
|
| 185 |
+
if not expected:
|
| 186 |
+
return 0.0
|
| 187 |
+
if expected in suggested:
|
| 188 |
+
return 1.0
|
| 189 |
+
exp_lines = [l.strip() for l in expected.splitlines() if l.strip()]
|
| 190 |
+
sug_lines = [l.strip() for l in suggested.splitlines() if l.strip()]
|
| 191 |
+
line_score = (
|
| 192 |
+
sum(1 for l in exp_lines if l in sug_lines) / len(exp_lines)
|
| 193 |
+
if exp_lines else 0.0
|
| 194 |
+
)
|
| 195 |
+
exp_tok = _code_tokens(expected)
|
| 196 |
+
sug_tok = set(_code_tokens(suggested))
|
| 197 |
+
token_score = (
|
| 198 |
+
sum(1 for t in exp_tok if t in sug_tok) / len(exp_tok) if exp_tok else 0.0
|
| 199 |
+
)
|
| 200 |
+
seq_score = SequenceMatcher(None, expected, suggested).ratio()
|
| 201 |
+
return round(0.4 * token_score + 0.3 * seq_score + 0.3 * line_score, 4)
|
| 202 |
+
|
| 203 |
+
def score_decision(self, action, ground_truth: dict) -> float:
|
| 204 |
+
if action.action_type != "final_decision" or not action.decision:
|
| 205 |
+
return 0.0
|
| 206 |
+
if action.decision == ground_truth.get("decision"):
|
| 207 |
+
return 1.0
|
| 208 |
+
return 0.1 # reduced partial credit
|
| 209 |
+
|
| 210 |
+
def compute_step_bonus(self, action, step_count: int, history: list) -> float:
|
| 211 |
+
bonus = 0.0
|
| 212 |
+
if action.comment and len(action.comment) > 40:
|
| 213 |
+
bonus += 0.10
|
| 214 |
+
if action.action_type == "final_decision":
|
| 215 |
+
if step_count == 1:
|
| 216 |
+
bonus += 0.10
|
| 217 |
+
elif step_count == 2:
|
| 218 |
+
bonus += 0.05
|
| 219 |
+
if step_count > 3:
|
| 220 |
+
bonus -= 0.04
|
| 221 |
+
if not action.comment and action.action_type != "final_decision":
|
| 222 |
+
bonus -= 0.08
|
| 223 |
+
return bonus
|
| 224 |
+
|
| 225 |
+
def compute_done_score(self, history: list, ground_truth: dict) -> float:
|
| 226 |
+
"""Recency-weighted: later actions in history count for more."""
|
| 227 |
+
n = max(len(history), 1)
|
| 228 |
+
weighted = [
|
| 229 |
+
self.grade_action(a, ground_truth) * (0.6 + 0.4 * (i / n))
|
| 230 |
+
for i, a in enumerate(history)
|
| 231 |
+
]
|
| 232 |
+
return max(0.01, min(max(weighted), 0.99))
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# ==============================================================================
|
| 236 |
+
# Hard Grader
|
| 237 |
+
# ==============================================================================
|
| 238 |
+
|
| 239 |
+
class HardGrader(BaseGrader):
|
| 240 |
+
"""
|
| 241 |
+
Strict grader. For finals / advanced rounds.
|
| 242 |
+
|
| 243 |
+
- Issue detection : token overlap + seq similarity with a minimum threshold
|
| 244 |
+
- Fix quality : line-level match dominant, no free token credit
|
| 245 |
+
- Wrong decision : 0.0 (no credit at all)
|
| 246 |
+
- Done scoring : final step only (harshest)
|
| 247 |
+
- Bonuses : minimal, escalating penalty for long trajectories
|
| 248 |
+
|
| 249 |
+
Weights: issues=45%, fix=28%, decision=27%
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
ISSUE_WEIGHT = 0.45
|
| 253 |
+
FIX_WEIGHT = 0.28
|
| 254 |
+
DECISION_WEIGHT = 0.27
|
| 255 |
+
|
| 256 |
+
# Minimum combined score an issue match must clear to get any credit
|
| 257 |
+
ISSUE_THRESHOLD = 0.30
|
| 258 |
+
|
| 259 |
+
def score_issues(self, comment: str, ground_truth: dict) -> float:
|
| 260 |
+
issues = ground_truth.get("issues", [])
|
| 261 |
+
if not comment or not issues:
|
| 262 |
+
return 0.0
|
| 263 |
+
comment_text = _normalize(comment)
|
| 264 |
+
comment_tokens = set(re.findall(r"[a-zA-Z_]\w*", comment_text)) - STOP_WORDS
|
| 265 |
+
scores = []
|
| 266 |
+
for issue in issues:
|
| 267 |
+
issue_text = _normalize(issue)
|
| 268 |
+
issue_tokens = set(re.findall(r"[a-zA-Z_]\w*", issue_text)) - STOP_WORDS
|
| 269 |
+
if not issue_tokens:
|
| 270 |
+
continue
|
| 271 |
+
token_overlap = len(issue_tokens & comment_tokens) / len(issue_tokens)
|
| 272 |
+
seq_sim = SequenceMatcher(None, issue_text, comment_text).ratio()
|
| 273 |
+
combined = 0.7 * token_overlap + 0.3 * seq_sim
|
| 274 |
+
# Must clear threshold to get any credit — no partial reward for vague hints
|
| 275 |
+
scores.append(combined if combined >= self.ISSUE_THRESHOLD else 0.0)
|
| 276 |
+
return round(sum(scores) / len(issues), 4) if scores else 0.0
|
| 277 |
+
|
| 278 |
+
def score_fix(self, suggested_code: str, ground_truth: dict) -> float:
|
| 279 |
+
if not suggested_code:
|
| 280 |
+
return 0.0
|
| 281 |
+
expected = _normalize(ground_truth.get("fix", ""))
|
| 282 |
+
suggested = _normalize(suggested_code)
|
| 283 |
+
if not expected:
|
| 284 |
+
return 0.0
|
| 285 |
+
if expected in suggested:
|
| 286 |
+
return 1.0
|
| 287 |
+
exp_lines = [l.strip() for l in expected.splitlines() if l.strip()]
|
| 288 |
+
sug_lines = set(l.strip() for l in suggested.splitlines() if l.strip())
|
| 289 |
+
line_score = (
|
| 290 |
+
sum(1 for l in exp_lines if l in sug_lines) / len(exp_lines)
|
| 291 |
+
if exp_lines else 0.0
|
| 292 |
+
)
|
| 293 |
+
exp_tok = _code_tokens(expected)
|
| 294 |
+
sug_tok = set(_code_tokens(suggested))
|
| 295 |
+
token_score = (
|
| 296 |
+
sum(1 for t in exp_tok if t in sug_tok) / len(exp_tok) if exp_tok else 0.0
|
| 297 |
+
)
|
| 298 |
+
seq_score = SequenceMatcher(None, expected, suggested).ratio()
|
| 299 |
+
# Line-level match is dominant in hard mode
|
| 300 |
+
return round(0.5 * line_score + 0.3 * token_score + 0.2 * seq_score, 4)
|
| 301 |
+
|
| 302 |
+
def score_decision(self, action, ground_truth: dict) -> float:
|
| 303 |
+
if action.action_type != "final_decision" or not action.decision:
|
| 304 |
+
return 0.0
|
| 305 |
+
return 1.0 if action.decision == ground_truth.get("decision") else 0.0
|
| 306 |
+
|
| 307 |
+
def compute_step_bonus(self, action, step_count: int, history: list) -> float:
|
| 308 |
+
bonus = 0.0
|
| 309 |
+
if action.action_type == "final_decision" and step_count == 1:
|
| 310 |
+
bonus += 0.05 # only reward decisive first-step finishes
|
| 311 |
+
if step_count > 2:
|
| 312 |
+
bonus -= 0.05 * (step_count - 2) # escalating penalty
|
| 313 |
+
if not action.comment and action.action_type != "final_decision":
|
| 314 |
+
bonus -= 0.12
|
| 315 |
+
return bonus
|
| 316 |
+
|
| 317 |
+
def compute_done_score(self, history: list, ground_truth: dict) -> float:
|
| 318 |
+
"""Strictest: only the final action in the episode counts."""
|
| 319 |
+
if not history:
|
| 320 |
+
return 0.01
|
| 321 |
+
return max(0.01, min(self.grade_action(history[-1], ground_truth), 0.99))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# ==============================================================================
|
| 325 |
+
# Factory
|
| 326 |
+
# ==============================================================================
|
| 327 |
+
|
| 328 |
+
GRADER_REGISTRY: dict[str, type[BaseGrader]] = {
|
| 329 |
+
"easy": EasyGrader,
|
| 330 |
+
"medium": MediumGrader,
|
| 331 |
+
"hard": HardGrader,
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def get_grader(level: str = "medium") -> BaseGrader:
|
| 336 |
+
"""
|
| 337 |
+
Return a grader instance for the given difficulty level.
|
| 338 |
+
|
| 339 |
+
Args:
|
| 340 |
+
level: One of "easy", "medium", or "hard".
|
| 341 |
+
|
| 342 |
+
Returns:
|
| 343 |
+
An instantiated grader.
|
| 344 |
+
|
| 345 |
+
Raises:
|
| 346 |
+
ValueError: If the level is not recognised.
|
| 347 |
+
"""
|
| 348 |
+
level = level.lower()
|
| 349 |
+
if level not in GRADER_REGISTRY:
|
| 350 |
+
raise ValueError(
|
| 351 |
+
f"Unknown grader level '{level}'. Choose from: {list(GRADER_REGISTRY)}"
|
| 352 |
+
)
|
| 353 |
+
return GRADER_REGISTRY[level]()
|