-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode_interpreter_tools.py
More file actions
72 lines (57 loc) · 2.21 KB
/
code_interpreter_tools.py
File metadata and controls
72 lines (57 loc) · 2.21 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
67
68
69
70
71
72
"""Core Code Interpreter tools for AgentCore."""
import json
import logging
logger = logging.getLogger(__name__)
class CodeInterpreterTools:
"""Tools for code execution via AgentCore Code Interpreter."""
def __init__(self, region: str):
"""
Initialize the code interpreter tools.
Args:
region: AWS region for code interpreter
"""
self.region = region
self._code_client = None
def _get_code_interpreter_client(self):
"""Get or create code interpreter client."""
if self._code_client is None:
from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
self._code_client = CodeInterpreter(self.region)
self._code_client.start()
logger.info(f"Started code interpreter in {self.region}")
return self._code_client
def cleanup(self):
"""
Clean up code interpreter session.
Note: AgentCore automatically cleans up inactive sessions after timeout,
so manual cleanup is optional but recommended for immediate resource release.
"""
if self._code_client:
self._code_client.stop()
self._code_client = None
def execute_python_securely(self, code: str) -> str:
"""
Execute Python code in a secure AgentCore CodeInterpreter sandbox.
Args:
code: Python code to execute
Returns:
JSON string with execution result
"""
client = self._get_code_interpreter_client()
try:
response = client.invoke(
"executeCode",
{"code": code, "language": "python", "clearContext": False},
)
results = []
for event in response["stream"]:
if "result" in event:
results.append(event["result"])
return (
json.dumps(results, indent=2)
if results
else json.dumps({"error": "No results returned"}, indent=2)
)
except Exception as e:
logger.error(f"Code execution failed: {e}")
return json.dumps({"error": f"Code execution failed: {str(e)}"}, indent=2)