-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpython_code_interpreter_tool.py
More file actions
66 lines (58 loc) · 2.28 KB
/
python_code_interpreter_tool.py
File metadata and controls
66 lines (58 loc) · 2.28 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# https://github.com/openai/openai-cookbook/blob/main/examples/object_oriented_agentic_approach/resources/registry/tools/python_code_interpreter_tool.py
import subprocess
from typing import Tuple, Dict, Any
class PythonExecTool:
"""
A Tool that executes Python code securely in a container.
"""
def get_definition(self) -> Dict[str, Any]:
"""
Return the JSON/dict definition of the tool's function
in the format expected by the OpenAI function calling API.
"""
return {
"type": "function",
"function": {
"name": "execute_python_code",
"description": "Executes Python code securely in a container. Python version 3.10 is installed in the container. pandas, numpy, matplotlib, seaborn, and scikit-learn are installed in the container.",
"parameters": {
"type": "object",
"properties": {
"python_code": {
"type": "string",
"description": "The Python code to execute"
}
},
"required": ["python_code"]
}
}
}
def run(self, arguments: Dict[str, Any]) -> str:
"""
Execute the Python code in a Docker container and return the output.
"""
python_code = arguments["python_code"]
python_code_stripped = python_code.strip('"""')
output, errors = self._run_code_in_container(python_code_stripped)
if errors:
return f"[Error]\n{errors}"
return output
@staticmethod
def _run_code_in_container(code: str, container_name: str = "sandbox") -> Tuple[str, str]:
"""
Helper function that actually runs Python code inside a Docker container named `sandbox` (by default).
"""
cmd = [
"docker", "exec", "-i",
container_name,
"python", "-c", "import sys; exec(sys.stdin.read())"
]
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
out, err = process.communicate(code)
return out, err