Create python_runner.py
#593
by
jatinror - opened
- tools/python_runner.py +52 -0
tools/python_runner.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|