File size: 709 Bytes
81b2f25
 
dfe015f
 
 
 
 
81b2f25
 
dfe015f
 
81b2f25
 
 
 
 
 
 
dfe015f
 
 
 
 
 
 
 
 
81b2f25
dfe015f
 
 
 
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
from langchain.tools import BaseTool

import subprocess
import tempfile


class PythonExecTool(BaseTool):
    name = "Python Execution Tool"
    description = "Executes Python code"

    def _run(self, code: str):

        with tempfile.NamedTemporaryFile(
            mode="w",
            suffix=".py",
            delete=False
        ) as file:

            file.write(code)
            file_path = file.name

        try:
            result = subprocess.check_output(
                ["python", file_path],
                stderr=subprocess.STDOUT,
                text=True,
            )

            return result

        except subprocess.CalledProcessError as error:
            return error.output