Skip to content

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.

  • 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
%pip install -q llama-index llama-index-tools-aws-bedrock-agentcore llama-index-llms-bedrock-converse

Create 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]}")

You can call the tool spec methods directly without an agent. This is useful for scripting or when you want precise control.

result = tool_spec.execute_code("print('Hello from AgentCore!')")
print(result)
result = tool_spec.execute_code(
"""
import math
print(f"Factorial of 10: {math.factorial(10)}")
print(f"Pi to 15 digits: {math.pi:.15f}")
"""
)
print(result)
# Write a file to the sandbox
result = tool_spec.write_files(
[{"path": "hello.txt", "text": "Hello from the code interpreter sandbox!"}]
)
print(result)
# List files
result = tool_spec.list_files()
print(result)
# Read the file back
result = tool_spec.read_files(["hello.txt"])
print(result)
# Upload a file with a semantic description
csv_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 back
result = tool_spec.download_file("people.csv")
print(result)
# Install a package and verify it's available
result = tool_spec.install_packages(["sympy"])
print(result)
result = tool_spec.execute_code(
"""
from sympy import symbols, expand
x, y = symbols('x y')
expr = expand((x + y) ** 3)
print(f"(x + y)^3 = {expr}")
"""
)
print(result)

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 BedrockConverse
from llama_index.core.agent.workflow import FunctionAgent
llm = BedrockConverse(model="us.anthropic.claude-sonnet-4-20250514-v1:0")
agent = FunctionAgent(
tools=tools,
llm=llm,
)

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))

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))

Always clean up code interpreter sessions when done to release resources.

await tool_spec.cleanup()
print("Code interpreter sessions cleaned up.")