Files
agent-claw/agentclaw/app/agent_claw_main/tools/code_interpreter.py

43 lines
1.4 KiB
Python

"""Code interpreter tool — runs Python code in AgentCore managed sandbox.
Follows the AWS-recommended pattern:
https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/code-interpreter-building-agents.html
"""
import json
import os
from strands import tool
from bedrock_agentcore.tools.code_interpreter_client import code_session
@tool
def run_code(code: str, description: str = '') -> str:
"""Execute Python code in a secure AgentCore managed sandbox and return the output.
State is maintained within a single session but not across separate calls.
Supports data analysis, calculations, file I/O, and most common Python libraries.
Args:
code: Python code to execute.
description: Optional description prepended as a comment.
Returns:
JSON result with stdout, stderr, exitCode, and executionTime.
"""
if description:
code = f'# {description}\n{code}'
print(f'[run_code] executing {len(code)}c')
region = os.environ.get('AWS_REGION', 'us-east-1')
with code_session(region) as client:
response = client.invoke('executeCode', {
'code': code,
'language': 'python',
'clearContext': False,
})
for event in response['stream']:
return json.dumps(event['result'])
return json.dumps({'isError': True, 'content': [{'type': 'text', 'text': 'No output from code interpreter'}]})