Spaces:
Sleeping
Sleeping
Update environment.py
Browse files123451 unmodified line789101112134 unmodified lines18192021222324252627282930313233346 unmodified lines414243444546474812 unmodified lines616263646566676869707172737475767778798081828384852 unmodified lines88899091929394from typing import Tuple, Dict, Anyfrom models import Observation, Action, Reward, Stateclass CodeReviewEnv:def __init__(self, task: str = "easy"):1 unmodified lineself.reset()def set_task(self, task: str):if task not in ["easy", "medium", "hard"]:raise ValueError(f"Unknown task: {task}")self.task = task4 unmodified linesself.agent_comment = Noneself.done = Falseif self.task == "easy":self.pr_code = "def get_user(id):\n return users[id] # missing null check"self.comments = ["Looks good!", "Maybe add a comment?"]elif self.task == "medium":self.pr_code = "for i in range(len(items)):\n process(items[i])\n# O(n^2) when it could be O(n)"self.comments = ["Nice code"]elif self.task == "hard":self.pr_code = "def calculate_average(data):\n total = sum(data)\n return total / len(data) # what if data is empty?"self.comments = ["LGTM"]else:raise RuntimeError(f"Invalid task: {self.task}")return self._get_observation()6 unmodified linesif action.action_type == "write_comment":self.agent_comment = action.comment_text or ""reward = 0.2quality_score = self._grade_comment(self.agent_comment)reward += quality_scoreif reward > 1.0:reward = 1.012 unmodified linesobs = self._get_observation()return obs, Reward(value=reward), self.done, infodef _grade_comment(self, comment: str) -> float:if self.task == "easy":keywords = ["null", "key", "missing", "check", "exists", "handle"]matched = sum(1 for kw in keywords if kw in comment.lower())return min(1.0, matched / 3)elif self.task == "medium":keywords = ["enumerate", "for item in", "range", "inefficient", "optimize"]matched = sum(1 for kw in keywords if kw in comment.lower())return min(1.0, matched / 3)elif self.task == "hard":keywords = ["empty", "zero", "length", "check", "handle", "exception"]matched = sum(1 for kw in keywords if kw in comment.lower())return min(1.0, matched / 3)else:return 0.0def _get_observation(self) -> Observation:return Observation(pr_code=self.pr_code,comments=self.comments,agent_comment=self.agent_comment,step=self.step_count,2 unmodified linesdef state(self) -> State:return State(pr_code=self.pr_code,comments=self.comments,agent_comment=self.agent_comment,step=self.step_count,1234561 unmodified line8910111213144 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646 unmodified lines7172737475767778798081828312 unmodified lines969798991001011021031041051062 unmodified lines109110111112113114115116117from typing import Tuple, Dict, Anyfrom models import Observation, Action, Reward, Statefrom grader import grade_commentclass CodeReviewEnv:def __init__(self, task: str = "easy"):1 unmodified lineself.reset()def set_task(self, task: str):if task not in ["easy", "medium", "hard", "harder", "hardest"]:raise ValueError(f"Unknown task: {task}")self.task = task4 unmodified linesself.agent_comment = Noneself.done = False# Task definitions with richer contextif self.task == "easy":self.pr_title = "Fix missing null check in user lookup"self.pr_description = "The current code does not handle missing user IDs. It raises a KeyError."self.code_snippet = "def get_user(id):\n return users[id] # missing null check"self.comments = ["Looks good!", "Maybe add a comment?"]self.expected_keywords = ["null", "key", "missing", "check", "exists", "handle"]self.expert_comment = "Add a check to ensure the key exists before accessing the dictionary to avoid KeyError."elif self.task == "medium":self.pr_title = "Improve loop efficiency"self.pr_description = "The loop uses `range(len(items))` which is inefficient and less readable."self.code_snippet = "for i in range(len(items)):\n process(items[i])\n# O(n^2) when it could be O(n)"self.comments = ["Nice code"]self.expected_keywords = ["enumerate", "for item in", "range", "inefficient", "optimize"]self.expert_comment = "Use `for item in items:` for a more Pythonic and efficient loop."elif self.task == "hard":self.pr_title = "Handle division by zero in average calculation"self.pr_description = "The function crashes when the input list is empty."self.code_snippet = "def calculate_average(data):\n total = sum(data)\n return total / len(data) # what if data is empty?"self.comments = ["LGTM"]self.expected_keywords = ["empty", "zero", "length", "check", "handle", "exception"]self.expert_comment = "Check if the list is empty and return a sensible default (e.g., 0) or raise a descriptive error."elif self.task == "harder":self.pr_title = "Fix race condition in counter increment"self.pr_description = "Multiple threads increment a counter without synchronization, causing lost updates."self.code_snippet = "counter = 0\ndef increment():\n global counter\n counter += 1\n# called from multiple threads"self.comments = ["Simple code, should be fine?"]self.expected_keywords = ["thread", "lock", "synchronization", "atomic", "race", "concurrent"]self.expert_comment = "Use a threading.Lock to protect the counter increment, or use an atomic operation like `threading.atomic`."else: # hardestself.pr_title = "Fix deadlock in database transaction"self.pr_description = "Two threads acquire locks in opposite order, leading to potential deadlock."self.code_snippet = "with lock1:\n with lock2:\n do_work()\n# another thread does lock2 then lock1"self.comments = ["Seems okay?"]self.expected_keywords = ["deadlock", "lock order", "acquire", "release", "trylock", "timeout"]self.expert_comment = "Ensure all threads acquire locks in the same order to prevent deadlock. Consider using a timeout or a single lock."return self._get_observation()6 unmodified linesif action.action_type == "write_comment":self.agent_comment = action.comment_text or ""reward = 0.2 # dense bonus for writing# Semantic graderquality_score = grade_comment(self.agent_comment,self.expected_keywords,self.expert_comment)reward += quality_scoreif reward > 1.0:reward = 1.012 unmodified linesobs = self._get_observation()return obs, Reward(value=reward), self.done, infodef _get_observation(self) -> Observation:return Observation(pr_title=self.pr_title,pr_description=self.pr_description,code_snippet=self.code_snippet,comments=self.comments,agent_comment=self.agent_comment,step=self.step_count,2 unmodified linesdef state(self) -> State:return State(pr_title=self.pr_title,pr_description=self.pr_description,code_snippet=self.code_snippet,comments=self.comments,agent_comment=self.agent_comment,step=self.step_count,
environment.py+49-26