Amazon Bedrock AgentCore Code Interpreter Tools
This notebook demonstrates how to use the Amazon Bedrock AgentCore Code Interpreter tools with LlamaIndex. The toolkit provides secure, sandboxed code execution, file management, and package installation in a remote environment.
Prerequisites
Section titled “Prerequisites”- An AWS account with Amazon Bedrock AgentCore access
- Configured AWS credentials (via
~/.aws/credentials, environment variables, or IAM role) - Required IAM permissions:
bedrock-agentcore:InvokeCodeInterpreter
Install Dependencies
Section titled “Install Dependencies”%pip install -q llama-index llama-index-tools-aws-bedrock-agentcore llama-index-llms-bedrock-converseCreate an AgentCoreCodeInterpreterToolSpec instance. A sandboxed code interpreter session is started lazily on first tool use.
from llama_index.tools.aws_bedrock_agentcore import ( AgentCoreCodeInterpreterToolSpec,)
tool_spec = AgentCoreCodeInterpreterToolSpec(region="us-west-2")tools = tool_spec.to_tool_list()
print(f"Available tools: {[t.metadata.name for t in tools]}")Direct Tool Usage
Section titled “Direct Tool Usage”You can call the tool spec methods directly without an agent. This is useful for scripting or when you want precise control.
Execute Code
Section titled “Execute Code”result = tool_spec.execute_code("print('Hello from AgentCore!')")print(result)result = tool_spec.execute_code( """import mathprint(f"Factorial of 10: {math.factorial(10)}")print(f"Pi to 15 digits: {math.pi:.15f}")""")print(result)File Operations
Section titled “File Operations”# Write a file to the sandboxresult = tool_spec.write_files( [{"path": "hello.txt", "text": "Hello from the code interpreter sandbox!"}])print(result)
# List filesresult = tool_spec.list_files()print(result)
# Read the file backresult = tool_spec.read_files(["hello.txt"])print(result)Upload and Download Files
Section titled “Upload and Download Files”# Upload a file with a semantic descriptioncsv_content = ( "Name,Age,City\nAlice,30,Seattle\nBob,25,Portland\nCharlie,35,Denver")result = tool_spec.upload_file( path="people.csv", content=csv_content, description="CSV file with name, age, and city data for three people",)print(result)
# Download it backresult = tool_spec.download_file("people.csv")print(result)Install Packages
Section titled “Install Packages”# Install a package and verify it's availableresult = tool_spec.install_packages(["sympy"])print(result)
result = tool_spec.execute_code( """from sympy import symbols, expandx, y = symbols('x y')expr = expand((x + y) ** 3)print(f"(x + y)^3 = {expr}")""")print(result)Agent Integration
Section titled “Agent Integration”Combine the code interpreter tools with a FunctionAgent and BedrockConverse LLM to let the agent autonomously write and execute code.
from llama_index.llms.bedrock_converse import BedrockConversefrom llama_index.core.agent.workflow import FunctionAgent
llm = BedrockConverse(model="us.anthropic.claude-sonnet-4-20250514-v1:0")
agent = FunctionAgent( tools=tools, llm=llm,)Data Analysis Task
Section titled “Data Analysis Task”Ask the agent to create a CSV dataset, analyze it with pandas, and report findings.
response = await agent.run( "Create a CSV file with 20 rows of sample sales data (date, product, quantity, price). " "Then use pandas to calculate total revenue by product and show the top 3.")print(str(response))Plot Generation
Section titled “Plot Generation”Ask the agent to generate a matplotlib chart. Each agent.run() call is independent, so the task must be self-contained.
response = await agent.run( "Generate a matplotlib bar chart comparing the populations of Tokyo, Delhi, Shanghai, " "São Paulo, and Mexico City. Save the chart as 'populations.png'.")print(str(response))Cleanup
Section titled “Cleanup”Always clean up code interpreter sessions when done to release resources.
await tool_spec.cleanup()print("Code interpreter sessions cleaned up.")