File size: 1,031 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
id: python_runner
title: Python Runner (unsafe)
author: admin
description: Execute Python code in a subprocess and capture output.
version: 0.1.0
license: Proprietary
"""

import subprocess
import tempfile
import textwrap


class Tools:
    def run(self, code: str) -> dict:
        """Run Python code; returns stdout, stderr, exit_code."""
        # Dedent to reduce quoting issues when LLM provides indented code
        code = textwrap.dedent(code)
        with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
            f.write(code)
            path = f.name
        try:
            p = subprocess.run(
                ["python3", path], capture_output=True, text=True, timeout=120
            )
            return {"stdout": p.stdout, "stderr": p.stderr, "exit_code": p.returncode}
        except subprocess.TimeoutExpired as e:
            return {
                "stdout": e.stdout or "",
                "stderr": (e.stderr or "") + "\n[timeout]",
                "exit_code": 124,
            }