MCPcopy Create free account
hub / github.com/PRIME-RL/PRIME / PythonREPL

Class PythonREPL

eval/utils/python_interpreter.py:79–134  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

77
78import os
79class PythonREPL():
80 def __init__(self, timeout=5, tmp_file="cache/tmp"):
81 self.timeout = timeout
82 self.tmp_file = tmp_file
83 os.system(f"touch {self.tmp_file}.py" )
84
85 @contextmanager
86 def time_limit(self, seconds):
87 def signal_handler(signum, frame):
88 raise TimeoutError(f"Timed out after {seconds} seconds.")
89
90 signal.signal(signal.SIGALRM, signal_handler)
91 signal.alarm(seconds)
92 try:
93 yield
94 finally:
95 signal.alarm(0) # Disable the alarm
96
97 def __call__(self, query: str) -> str:
98 query = query.strip().split("\n")
99 if "print(" not in query[-1]:
100 query[-1] = "print(" + query[-1] + ")"
101 query = "\n".join(query)
102
103 with open(f'{self.tmp_file}.py', "w") as f:
104 f.write(query)
105
106 with self.time_limit(self.timeout):
107 result = subprocess.run(
108 ['python3', f'{self.tmp_file}.py'], capture_output=True, check=False, text=True, timeout=self.timeout)
109
110 if result.returncode == 0:
111 output = result.stdout
112 return True, output.strip()
113 else:
114 error_msg = result.stderr.strip()
115 msgs = error_msg.split("\n")
116 new_msgs = []
117 want_next = False
118 for m in msgs:
119 if "Traceback" in m:
120 new_msgs.append(m)
121 elif m == msgs[-1]:
122 new_msgs.append(m)
123 elif self.tmp_file in m:
124 st = m.index('"/') + 1 if '"/' in m else 0
125 ed = m.index(f'/{self.tmp_file}.py') + 1 if f'/{self.tmp_file}.py' in m else None
126 clr = m[st:ed] if not ed else m[st:]
127 m = m.replace(clr, "")
128 new_msgs.append(m)
129 want_next = True
130 elif want_next:
131 new_msgs.append(m)
132 want_next = False
133 error_msg = "\n".join(new_msgs)
134 return False, error_msg.strip()
135
136

Callers 1

postprocess_completionsFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected