jatinror commited on
Commit
7e558fd
·
verified ·
1 Parent(s): f070999

Update tools/python_runner.py

Browse files
Files changed (1) hide show
  1. tools/python_runner.py +36 -40
tools/python_runner.py CHANGED
@@ -1,57 +1,53 @@
1
  from typing import Any, Dict
 
2
  import io
3
- import traceback
4
  import contextlib
 
5
  import signal
6
 
7
- # ---- your safe executor ----
8
-
9
  class TimeoutException(Exception):
10
  pass
11
 
12
  def timeout_handler(signum, frame):
13
  raise TimeoutException("Execution timed out.")
14
 
15
- def run_python(code: str, timeout: int = 5) -> Dict[str, Any]:
16
- safe_globals = {
17
- "__builtins__": {
18
- "print": print,
19
- "range": range,
20
- "len": len,
21
- "int": int,
22
- "float": float,
23
- "str": str,
24
- "list": list,
25
- "dict": dict,
26
- "sum": sum,
27
- "min": min,
28
- "max": max,
29
- "abs": abs,
 
 
 
 
 
 
 
 
30
  }
31
- }
32
-
33
- stdout_buffer = io.StringIO()
34
-
35
- try:
36
- signal.signal(signal.SIGALRM, timeout_handler)
37
- signal.alarm(timeout)
38
-
39
- with contextlib.redirect_stdout(stdout_buffer):
40
- exec(code, safe_globals, {})
41
 
42
- signal.alarm(0)
43
- return {"status": "success", "output": stdout_buffer.getvalue()}
44
 
45
- except TimeoutException as e:
46
- return {"status": "error", "output": str(e)}
47
 
48
- except Exception:
49
- return {"status": "error", "output": traceback.format_exc()}
50
 
 
 
51
 
52
- # ---- THIS PART REGISTERS THE TOOL ----
53
- def python_runner(code: str) -> Dict[str, Any]:
54
- """
55
- Executes safe Python code and returns stdout or errors.
56
- """
57
- return run_python(code)
 
1
  from typing import Any, Dict
2
+ from smolagents.tools import Tool
3
  import io
 
4
  import contextlib
5
+ import traceback
6
  import signal
7
 
 
 
8
  class TimeoutException(Exception):
9
  pass
10
 
11
  def timeout_handler(signum, frame):
12
  raise TimeoutException("Execution timed out.")
13
 
14
+ class PythonRunnerTool(Tool):
15
+ name = "python_runner"
16
+ description = "Executes Python code safely and returns stdout or errors."
17
+ inputs = {'code': {'type': 'string', 'description': 'Python code to execute'}}
18
+ output_type = "string"
19
+
20
+ def forward(self, code: str) -> str:
21
+ stdout_buffer = io.StringIO()
22
+ safe_globals = {
23
+ "__builtins__": {
24
+ "print": print,
25
+ "range": range,
26
+ "len": len,
27
+ "int": int,
28
+ "float": float,
29
+ "str": str,
30
+ "list": list,
31
+ "dict": dict,
32
+ "sum": sum,
33
+ "min": min,
34
+ "max": max,
35
+ "abs": abs,
36
+ }
37
  }
38
+ try:
39
+ signal.signal(signal.SIGALRM, timeout_handler)
40
+ signal.alarm(5) # 5 second timeout
 
 
 
 
 
 
 
41
 
42
+ with contextlib.redirect_stdout(stdout_buffer):
43
+ exec(code, safe_globals, {})
44
 
45
+ signal.alarm(0)
46
+ return stdout_buffer.getvalue()
47
 
48
+ except TimeoutException as e:
49
+ return f"Error: {str(e)}"
50
 
51
+ except Exception:
52
+ return traceback.format_exc()
53