Spaces:
Sleeping
Sleeping
Update environment.py
Browse files1234567891011121314151659 unmodified lines7677787980811 unmodified line83848586878889909192931 unmodified line959697989910010110210310410510 unmodified lines116117118119120121122123124125126127128129130131132133from typing import Tuple, Dict, Anyfrom models import Observation, Action, Reward, Statefrom grader import grade_comment, grade_question, grade_fixclass CodeReviewEnv:def __init__(self, task: str = "easy"):self.task = taskself.reset()def set_task(self, task: str):if task not in ["easy", "medium", "hard", "harder", "hardest"]:raise ValueError(f"Unknown task: {task}")self.task = taskdef reset(self) -> Observation:if self.task is None:59 unmodified linesreward = 0.2 # dense bonus for writingquality_score = grade_comment(self.agent_comment, self.expected_keywords, self.expert_comment)reward += quality_scoreself.done = Trueelif action.action_type == "ask_question":1 unmodified linereward = -0.1else:q_score = grade_question(action.question)reward = 0.1 + q_score # small bonus + quality# Simulate a helpful answeranswer = self._answer_question(action.question)self.comments.append(f"Agent: {action.question}")self.comments.append(f"Env: {answer}")self.step_count += 1# Episode continues, not done1 unmodified lineif not action.fix_code:reward = -0.2else:# We'll use a simple keyword check for demonstration# In a full version, you'd run unit testsfix_score = grade_fix(action.fix_code, self.expected_fix_keywords, None)reward = 0.3 + fix_scoreself.test_results = f"Fix evaluated with score {fix_score:.2f}"self.done = Trueelif action.action_type == "skip":10 unmodified linesobs = self._get_observation()return obs, Reward(value=reward), self.done, infodef _answer_question(self, question: str) -> str:# Simple rule‑based answers – you can expandq = question.lower()if "what" in q and "purpose" in q:return "The purpose of this function is to retrieve a user by ID from a dictionary."elif "expected" in q:return "The function should return the user object if the ID exists, otherwise raise a KeyError."elif "how" in q and "fix" in q:return "You might consider adding a check for missing keys or using a safer dictionary method like `get`."else:return "I'm not sure. Could you be more specific?"def _get_observation(self) -> Observation:return Observation(pr_title=self.pr_title,12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612759 unmodified lines1871881891901911921931941951961 unmodified line1981992002012022032042052062072081 unmodified line21021121221321421521621721821922022122222310 unmodified lines234235236237238239from typing import Tuple, Dict, Any, List, Optionalfrom models import Observation, Action, Reward, Statefrom grader import grade_comment, grade_question, grade_fiximport sysimport ioimport contextlib# ------------------------- Simulated CI / Unit tests -------------------------def run_unit_tests(fix_code: str, task: str) -> float:"""Runs a small set of unit tests for the given task.Returns a score in [0,1] based on passed tests."""# Define tests per tasktest_code = ""if task == "easy":# Test that the function handles missing keystest_code = f"""{fix_code}def test():try:users = {{"alice": "Alice"}}result = get_user("bob")return False # should not get here if key missingexcept KeyError:return True # expected: KeyErrorexcept Exception:return False"""elif task == "medium":test_code = f"""{fix_code}def test():items = [1,2,3]# We cannot directly test the loop, but we can check that 'process' is called correctly.# For demonstration, we'll assume the fix uses 'enumerate' or 'for item in'.# Here we just check that the code compiles and runs without error.try:exec(compile("{fix_code}", "<string>", "exec"))return Trueexcept Exception:return False"""elif task == "hard":test_code = f"""{fix_code}def test():# Test empty listtry:result = calculate_average([])return result == 0 # expect 0 or some defaultexcept ZeroDivisionError:return False"""elif task == "harder":test_code = f"""{fix_code}def test():# Check that a lock is usedif "lock" in "{fix_code}".lower():return Truereturn False"""else: # hardesttest_code = f"""{fix_code}def test():# Check for lock order mentionif "same order" in "{fix_code}".lower() or "lock order" in "{fix_code}".lower():return Truereturn False"""# Execute the test in a safe sandboxtry:# Capture stdout/stderrf = io.StringIO()with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):exec(test_code, {})# Check if test function returns Truelocal_ns = {}exec(test_code, {}, local_ns)if 'test' in local_ns and callable(local_ns['test']):passed = local_ns['test']()return 1.0 if passed else 0.0else:return 0.0except Exception:return 0.0# ------------------------- Simulated PR Author -------------------------class SimulatedAuthor:"""Responds to the agent's questions and comments as if they were the PR author."""def __init__(self, task: str):self.task = taskdef respond(self, agent_comment: str, agent_question: str = None) -> str:if agent_question:q = agent_question.lower()if "what" in q and "purpose" in q:return "The purpose is to retrieve a user safely."elif "expected" in q:return "It should return the user or raise KeyError."else:return "Could you be more specific?"else:# Generic response to a commentif "good" in agent_comment.lower():return "Thanks for the feedback!"else:return "I'll consider your suggestion."# ------------------------- Main Environment -------------------------class CodeReviewEnv:def __init__(self, task: str = "easy"):self.task = taskself.author = Noneself.reset()def set_task(self, task: str):if task not in ["easy", "medium", "hard", "harder", "hardest"]:raise ValueError(f"Unknown task: {task}")self.task = taskself.author = SimulatedAuthor(task)def reset(self) -> Observation:if self.task is None:59 unmodified linesreward = 0.2 # dense bonus for writingquality_score = grade_comment(self.agent_comment, self.expected_keywords, self.expert_comment)reward += quality_score# Simulate author responseauthor_response = self.author.respond(self.agent_comment)self.comments.append(f"Agent: {self.agent_comment}")self.comments.append(f"Author: {author_response}")self.done = Trueelif action.action_type == "ask_question":1 unmodified linereward = -0.1else:q_score = grade_question(action.question)reward = 0.1 + q_score# Get answer from simulated authoranswer = self.author.respond(agent_question=action.question)self.comments.append(f"Agent: {action.question}")self.comments.append(f"Author: {answer}")self.step_count += 1# Episode continues, not done1 unmodified lineif not action.fix_code:reward = -0.2else:# Run CI teststest_score = run_unit_tests(action.fix_code, self.task)# Also keyword match for partial creditkw_score = grade_fix(action.fix_code, self.expected_fix_keywords, None)# Combined score: 70% tests, 30% keywordscombined_score = 0.7 * test_score + 0.3 * kw_scorereward = 0.3 + combined_scoreself.test_results = f"CI tests passed: {test_score:.0%}, Keywords: {kw_score:.0%}"self.done = Trueelif action.action_type == "skip":10 unmodified linesobs = self._get_observation()return obs, Reward(value=reward), self.done, infodef _get_observation(self) -> Observation:return Observation(pr_title=self.pr_title,
environment.py+128-22