Getting Started with Amazon Bedrock AgentCore Code Interpreter
Introduction
AI agents are becoming more capable, but they often struggle with tasks that require precise computation, data analysis, or code execution. Instead of relying solely on a model’s reasoning to perform calculations (which can be unreliable), you can give your agent the ability to actually run code in a secure sandbox environment and access your real data while doing it.
Amazon Bedrock AgentCore Code Interpreter is a managed service that provides isolated sandbox environments where agents can write and execute code securely. It supports Python, JavaScript, and TypeScript, comes with pre-installed libraries for data analysis and visualization, and handles all the infrastructure for you.
This article is part of a series I am writing about different aspects of Amazon Bedrock AgentCore. Here, we focus on how to use Code Interpreter to solve the problem described above. For a broader understanding of AgentCore and its components, check out the other articles in this series:
Network Modes
When creating a custom Code Interpreter, you choose a network mode that determines what the sandbox can access:
- Sandbox — Restricted environment with network access limited to Amazon S3 only. No internet, no other AWS services. This is the most secure option and reduces potential risks.
- Public — Allows access to the public internet and all AWS service endpoints. Use this when your Code Interpreter needs to interact with services beyond S3 (such as DynamoDB, APIs, or external URLs).
- VPC — Deploy within a Virtual Private Cloud for secure, private communication with resources in your network.
In this article, we explore three approaches:
- First, we use Sandbox mode for a simple and secure demonstration. The Code Interpreter accesses a CSV file stored in S3, downloads it into the sandbox using the AWS CLI, and analyzes it with Pandas.
- Then, we use Public mode to demonstrate how a Code Interpreter can access AWS services beyond S3. In this scenario, the Code Interpreter queries a DynamoDB table containing car inventory data, performs statistical analysis, and returns results. This connects to the car dealership agent scenario introduced in Running Your First Agent on Amazon Bedrock AgentCore, where we created a Harness for a used car sales assistant.
- Finally, we integrate the Code Interpreter as a tool in the Harness and let the AI agent autonomously generate and execute code to answer a customer question about car financing.
Important: Code Interpreter is for Computation, Not Data Retrieval
The AWS documentation describes Code Interpreter as a tool that extends problem-solving capabilities by allowing agents to “solve computational problems that are difficult to address through reasoning alone” and enabling “precise mathematical calculations and data processing at scale.” It is designed to complement an agent’s reasoning with actual code execution.
In the examples below (Steps 3 and 5), we invoke the Code Interpreter directly from our local machine to demonstrate the capabilities of the resource and how different network modes work. However, in a production agent scenario (like the car dealership assistant we are building across this series), the recommended pattern is for data retrieval to come from dedicated tools (such as MCP servers or AgentCore Gateway) and for the Code Interpreter to handle only the computational tasks (calculations, data transformation, statistical analysis). This separation of concerns will be explored in future articles. In Step 7, we show a preview of this pattern: the agent receives data in its prompt and uses Code Interpreter exclusively for a financing calculation.
What is AgentCore Code Interpreter?
Amazon Bedrock AgentCore is a platform for building, deploying, and operating AI agents at scale. It includes multiple modular services that work together or independently. Code Interpreter is one of these services.
The Code Interpreter follows a resource and session-based model:
- You create a Code Interpreter resource (custom or use the system default)
- You start a session with a configurable timeout (default 15 minutes)
- Within that session, you execute code and maintain state between executions
- Multiple sessions can run simultaneously, each with its own isolated environment
- When done, you stop the session to release resources
When you create a custom Code Interpreter, you configure the network mode and assign an IAM execution role. In Sandbox mode, the execution role defines which S3 buckets the interpreter can access. After creation, the console provides a unique Code Interpreter Tool ID that you use in all API calls.
Key Features
- Secure execution in containerized environments
- Support for Python, JavaScript, and TypeScript
- Pre-installed libraries (NumPy, Pandas, Matplotlib, and more)
- File upload/download operations (up to 100 MB inline, up to 5 GB via S3)
- Terminal command execution
- Default execution timeout of 15 minutes (extendable up to 8 hours)
- CloudTrail logging for audit
Prerequisites
- AWS account with credentials configured
- IAM user or role with permissions to use Amazon Bedrock AgentCore Code Interpreter. For details on the required IAM actions, see the Code Interpreter IAM permissions documentation
- Python 3.10+ installed
- Git installed
- AWS Region where AgentCore is available (us-east-1, us-west-2, ap-southeast-2, or eu-central-1)
Step 1: Clone the Repository and Install Dependencies
Clone the companion repository and set up the Python environment:
git clone https://github.com/biagolini/PythonAwsBedrockAgentCoreCodeInterpreter.git
cd PythonAwsBedrockAgentCoreCodeInterpreter
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtOn Windows, replace the activation command with .venv\Scripts\activate.
Step 2: Create a Code Interpreter in the Console
Before executing code, you need to create a Code Interpreter resource. In this step, you will use the Amazon Bedrock AgentCore console to create a custom Code Interpreter tool.
2.1 Navigate to Code Interpreter
2.1.1. Open the Amazon Bedrock AgentCore console
2.1.2. In the left navigation pane, under Built-in tools, click Code Interpreter
2.1.3. Click the Create button in the top-right corner of the Code Interpreter list
2.2 Configure the Code Interpreter Tool
The creation form has three sections: tool details, tool configurations, and permissions.
2.2.1. In the Tool name field, enter a name for your interpreter (example: code_interpreter_tool_demo). Valid characters are a-z, A-Z, 0-9 and _ (underscore). The name can have up to 48 characters
2.2.2. Optionally, add a description in the Tool description field
2.2.3. Under Tool configurations, in the Security section, select the network mode:
- Sandbox — Restricted environment with network access limited to AWS S3 service (recommended for this tutorial)
- Public — Allows internet access, suitable for less sensitive or open-use scenarios
- VPC (Virtual Private Cloud) — Deploy within a VPC for secure, private communication
2.2.4. Under Permissions, in the IAM permissions section, click Create new role. This opens a dialog to configure the role and its policy:
The console pre-fills the Role name with a default value. You can update it to follow naming best practices — for example, AgentCoreCodeInterpreter-S3-ReadOnly clearly conveys the service, resource scope, and permission level. The trust policy is configured automatically (allowing bedrock-agentcore.amazonaws.com to assume the role). You need to define the Policy that determines what AWS resources the Code Interpreter can access during execution.
In this tutorial, the Code Interpreter needs to read a CSV file from S3. Replace the default policy content with the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3ReadAccess",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::<your-bucket-name>",
"arn:aws:s3:::<your-bucket-name>/*"
]
}
]
}Replace <your-bucket-name> with the S3 bucket name you configured in the .env file. This follows the principle of least privilege, granting only the read permissions needed for this tutorial.
Click Create role to confirm.
2.2.5. Back on the main creation form, click the Create button at the bottom of the page
2.3 Copy the Code Interpreter Tool ID
After creation, the console displays the tool details page. Copy the Code interpreter tool ID value — you will use this identifier in all API calls.
Step 3: Execute Code with Boto3
All scripts in this step read the CODE_INTERPRETER_ID from the .env file. Make sure you have added the tool ID you copied in Step 2.3:
CODE_INTERPRETER_ID=<your-code-interpreter-id>3.1 Basic Hello World
The file code_interpreter_hello.py demonstrates the simplest possible interaction: start a session, execute a print statement, and stop the session.
import boto3
import os
from dotenv import load_dotenv
load_dotenv()
CODE_INTERPRETER_ID = os.getenv("CODE_INTERPRETER_ID")
REGION = os.getenv("AWS_REGION")
# Initialize the bedrock-agentcore client
client = boto3.client("bedrock-agentcore", region_name=REGION)
# Start a Code Interpreter session
session_response = client.start_code_interpreter_session(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
name="my-first-session",
sessionTimeoutSeconds=900,
)
session_id = session_response["sessionId"]
print(f"Started session: {session_id}\n")
try:
# Execute Python code
execute_response = client.invoke_code_interpreter(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
name="executeCode",
arguments={
"language": "python",
"code": 'print("Hello from AgentCore Code Interpreter!")',
},
)
# Extract and print the text output from the stream
for event in execute_response["stream"]:
if "result" in event:
result = event["result"]
if "content" in result:
for content_item in result["content"]:
if content_item["type"] == "text":
print(content_item["text"])
finally:
# Stop the session when done
client.stop_code_interpreter_session(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
)
print(f"\nStopped session: {session_id}")Run the script:
python code_interpreter_hello.pyExpected output:
Started session: <session-id>
Hello from AgentCore Code Interpreter!
Stopped session: <session-id>3.2 Analyze S3 Data
Now let’s use the Code Interpreter to access real data. The file code_interpreter_s3.py downloads a CSV from your S3 bucket using AWS CLI inside the sandbox, then analyzes it with Pandas.
The key concept here is that the sandbox has the AWS CLI available and uses the execution role you configured in Step 2 to authenticate. This means you can use executeCommand with AWS CLI commands to interact with any AWS resource the role has access to.
import boto3
import os
from dotenv import load_dotenv
load_dotenv()
CODE_INTERPRETER_ID = os.getenv("CODE_INTERPRETER_ID")
REGION = os.getenv("AWS_REGION")
BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
client = boto3.client("bedrock-agentcore", region_name=REGION)
# Start session
session_response = client.start_code_interpreter_session(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
name="s3-analysis-session",
sessionTimeoutSeconds=900,
)
session_id = session_response["sessionId"]
print(f"Started session: {session_id}\n")
def execute_command(command):
"""Execute a terminal command in the sandbox and print results."""
response = client.invoke_code_interpreter(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
name="executeCommand",
arguments={"command": command},
)
for event in response["stream"]:
if "result" in event:
result = event["result"]
if "content" in result:
for content_item in result["content"]:
if content_item["type"] == "text":
print(content_item["text"])
def execute_code(code):
"""Execute Python code in the sandbox and print results."""
response = client.invoke_code_interpreter(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
name="executeCode",
arguments={"language": "python", "code": code},
)
for event in response["stream"]:
if "result" in event:
result = event["result"]
if "content" in result:
for content_item in result["content"]:
if content_item["type"] == "text":
print(content_item["text"])
try:
# Step 1: Download the CSV from S3 using AWS CLI
print("--- Downloading CSV from S3 ---")
execute_command(f"aws s3 cp s3://{BUCKET_NAME}/data/sales_report.csv ./sales_report.csv")
# Step 2: Analyze the data with Pandas
print("\n--- Analyzing Sales Data ---")
execute_code("""
import pandas as pd
df = pd.read_csv("sales_report.csv")
print("=== Sales Report Summary ===")
print(f"Total records: {len(df)}")
print(f"Date range: {df['month'].min()} to {df['month'].max()}")
print(f"Products: {', '.join(df['product'].unique())}")
print(f"\\nTotal Revenue: ${df['revenue'].sum():,.2f}")
print(f"Total Units Sold: {df['units_sold'].sum():,}")
print()
print("=== Revenue by Product ===")
product_summary = df.groupby('product').agg(
total_revenue=('revenue', 'sum'),
total_units=('units_sold', 'sum'),
avg_monthly_revenue=('revenue', 'mean')
).round(2)
print(product_summary.to_string())
print()
print("=== Revenue by Region ===")
region_summary = df.groupby('region')['revenue'].sum().sort_values(ascending=False)
print(region_summary.to_string())
""")
finally:
client.stop_code_interpreter_session(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
)
print(f"\nStopped session: {session_id}")Run the full script:
python code_interpreter_s3.pyStep 4: Session Management with AWS CLI
In a real scenario, you will often manage sessions from your terminal using the AWS CLI. Here are useful commands for session management.
4.1 List Active Sessions
Use the AWS CLI to list active sessions for your Code Interpreter:
aws bedrock-agentcore list-code-interpreter-sessions \
--region us-east-1 \
--code-interpreter-id "<your-code-interpreter-id>"You should see sessions with status READY (active) or TERMINATED (completed/timed out).
Sessions automatically terminate after the configured timeout (default 900 seconds = 15 minutes). You can confirm this by checking the status after the timeout period, confirming that automatic termination works as expected.
4.2 Stop a Session via AWS CLI
If you need to stop a session before it times out, use the stop-code-interpreter-session command:
aws bedrock-agentcore stop-code-interpreter-session \
--region us-east-1 \
--code-interpreter-id "<your-code-interpreter-id>" \
--session-id "<your-session-id>"This is the recommended way to release resources when you are done. Even though sessions auto-terminate after the timeout, stopping them immediately avoids unnecessary charges during the wait period.
Step 5: Public Mode with DynamoDB Access
In the previous steps, we used a Code Interpreter in Sandbox mode, which restricts network access to S3 only. Now we introduce a second scenario using Public mode. In this mode, the Code Interpreter sandbox has access to the public internet and all AWS service endpoints. This allows the sandbox to interact with services like DynamoDB, SQS, or any external API.
Get Carlos Biagolini’s stories in your inbox
Join Medium for free to get updates from this writer.
This example connects to the car dealership agent use case from the previous article in this series, where we created a Harness to serve as a sales assistant. Here, we demonstrate how a Code Interpreter configured as a tool could access the dealership’s inventory database in DynamoDB and perform data analysis. In a production setup, this Code Interpreter could be attached to the Harness as a tool, allowing the AI agent to query real inventory data and run calculations when responding to customer questions.
5.1 Create the DynamoDB Table
For this demonstration, we need a DynamoDB table with car inventory data. In a previous article, we built a serverless MCP server on AWS that exposes a car inventory DynamoDB database through API Gateway and Lambda, secured with IAM authentication. The complete Terraform infrastructure is available at https://github.com/biagolini/TerraformAwsMcpServerlessKiroCli. You can use that Terraform code to provision the table automatically, but it also creates additional resources (API Gateway, Lambda, IAM roles for the MCP server) that are not needed for this article.
To create only the DynamoDB table, follow these manual steps in the AWS Console:
5.1.1. Navigate to Amazon DynamoDB > Tables in the AWS Console
5.1.2. Click Create table
5.1.3. Configure the table:
- Table name:
mcp-cars-dev - Partition key:
car_id(String) - Table settings: Select Customize settings, then under Read/write capacity settings, select On-demand (serverless, pay-per-request)
5.1.4. Click Create table
5.1.5. Populate the table with sample data. The seed script is available at https://github.com/biagolini/TerraformAwsMcpServerlessKiroCli/blob/main/seed/seed_cars.sh. This script inserts hypothetical used car records with attributes like brand, model, year, price, color, body type, mileage, and availability status.
5.2 Create a Code Interpreter with Public Mode
Now create a second Code Interpreter configured for Public network access and DynamoDB permissions.
5.2.1. Navigate to Amazon Bedrock AgentCore > Built-in tools > Code Interpreter
5.2.2. Click Create
5.2.3. In the Tool name field, enter code_interpreter_public_dynamo
5.2.4. Under Tool configurations > Security, select Public as the network mode
5.2.5. Under Permissions, click Create new role. Name the role AgentCoreCodeInterpreter-DynamoDB-ReadOnly and use the following policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DynamoDBReadAccess",
"Effect": "Allow",
"Action": [
"dynamodb:Scan",
"dynamodb:Query",
"dynamodb:GetItem",
"dynamodb:DescribeTable"
],
"Resource": [
"arn:aws:dynamodb:us-east-1:<your-account-id>:table/mcp-cars-dev",
"arn:aws:dynamodb:us-east-1:<your-account-id>:table/mcp-cars-dev/index/*"
]
}
]
}5.2.6. Click Create role, then Create the Code Interpreter
5.2.7. Copy the Code interpreter tool ID from the details page. Add it to your .env file:
CODE_INTERPRETER_PUBLIC_ID=<your-public-code-interpreter-id>
DYNAMODB_TABLE_NAME=mcp-cars-dev5.3 Query DynamoDB from the Code Interpreter
The file code_interpreter_dynamodb.py demonstrates how a Code Interpreter in Public mode can query DynamoDB, scan the car inventory table, and perform statistical analysis. The code inside the sandbox uses boto3 to connect to DynamoDB using the execution role credentials.
import boto3
import os
from dotenv import load_dotenv
load_dotenv()
CODE_INTERPRETER_ID = os.getenv("CODE_INTERPRETER_PUBLIC_ID")
REGION = os.getenv("AWS_REGION")
DYNAMODB_TABLE = os.getenv("DYNAMODB_TABLE_NAME")
client = boto3.client("bedrock-agentcore", region_name=REGION)
# Start session
session_response = client.start_code_interpreter_session(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
name="dynamodb-analysis-session",
sessionTimeoutSeconds=900,
)
session_id = session_response["sessionId"]
print(f"Started session: {session_id}\n")
def execute_code(code):
"""Execute Python code in the sandbox and print results."""
response = client.invoke_code_interpreter(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
name="executeCode",
arguments={"language": "python", "code": code},
)
for event in response["stream"]:
if "result" in event:
result = event["result"]
if "content" in result:
for content_item in result["content"]:
if content_item["type"] == "text":
print(content_item["text"])
try:
# Query DynamoDB table using boto3 inside the Code Interpreter
print("--- Querying DynamoDB Car Inventory ---")
execute_code(
"import boto3\n"
"\n"
f"dynamodb = boto3.resource('dynamodb', region_name='{REGION}')\n"
f"table = dynamodb.Table('{DYNAMODB_TABLE}')\n"
"\n"
"# Scan the entire table\n"
"response = table.scan()\n"
"items = response['Items']\n"
"\n"
"print(f'Total cars in inventory: {len(items)}')\n"
"print()\n"
"\n"
"# Display inventory summary\n"
"print('=== Car Inventory Summary ===')\n"
"print(f\"{'Brand':<12} {'Model':<12} {'Year':<6} {'Price':<10} {'Color':<8} {'Body Type':<10} {'Available'}\")\n"
"print('-' * 80)\n"
"for car in sorted(items, key=lambda x: x['brand']):\n"
" print(f\"{car['brand']:<12} {car['model']:<12} {car['year']:<6} ${int(car['price']):,}{'':<5} {car['color']:<8} {car['body_type']:<10} {car['available']}\")\n"
)
# Perform analysis
print("\n--- Performing Price Analysis ---")
execute_code(
"import boto3\n"
"from collections import Counter\n"
"\n"
f"dynamodb = boto3.resource('dynamodb', region_name='{REGION}')\n"
f"table = dynamodb.Table('{DYNAMODB_TABLE}')\n"
"\n"
"response = table.scan()\n"
"items = response['Items']\n"
"\n"
"# Price analysis\n"
"prices = [int(item['price']) for item in items]\n"
"print('=== Price Analysis ===')\n"
"print(f'Average price: ${sum(prices) / len(prices):,.2f}')\n"
"print(f'Lowest price: ${min(prices):,}')\n"
"print(f'Highest price: ${max(prices):,}')\n"
"print()\n"
"\n"
"# Group by body type\n"
"body_types = Counter(item['body_type'] for item in items)\n"
"print('=== Inventory by Body Type ===')\n"
"for body_type, count in body_types.most_common():\n"
" avg_price = sum(int(item['price']) for item in items if item['body_type'] == body_type) / count\n"
" print(f' {body_type:<10}: {count} car(s), avg price ${avg_price:,.2f}')\n"
"print()\n"
"\n"
"# Available vs sold\n"
"available = sum(1 for item in items if item['available'] == 'yes')\n"
"print('=== Availability ===')\n"
"print(f' Available: {available}')\n"
"print(f' Sold: {len(items) - available}')\n"
)
finally:
client.stop_code_interpreter_session(
codeInterpreterIdentifier=CODE_INTERPRETER_ID,
sessionId=session_id,
)
print(f"\nStopped session: {session_id}")Run the script:
python code_interpreter_dynamodb.pyExpected output:
Started session: <session-id
--- Querying DynamoDB Car Inventory ---
Total cars in inventory: 10
=== Car Inventory Summary ===
Brand Model Year Price Color Body Type Available
--------------------------------------------------------------------------------
Chevrolet Tahoe 2018 $29,000 white suv yes
Ford Mustang 2019 $27,500 red coupe yes
Ford F-150 2019 $29,000 gray truck yes
...
--- Performing Price Analysis ---
=== Price Analysis ===
Average price: $24,580.00
Lowest price: $13,500
Highest price: $32,000
=== Inventory by Body Type ===
suv : 3 car(s), avg price $28,333.33
sedan : 3 car(s), avg price $16,600.00
coupe : 1 car(s), avg price $27,500.00
...
=== Availability ===
Available: 9
Sold: 1
Stopped session: <session-id>The key difference from the Sandbox mode example is that the Code Interpreter can now access any AWS service that the execution role permits. The sandbox uses the IAM execution role to authenticate API calls. In this case, it calls dynamodb:Scan on the mcp-cars-dev table, retrieves all items, and processes them with Python.
This pattern enables powerful use cases where an AI agent can:
- Query live databases to answer customer questions with real data
- Perform calculations over actual inventory (pricing analysis, availability summaries)
- Generate reports from production data sources without exposing raw database credentials
Step 6: Clean Up and Create a Sandbox Code Interpreter for the Harness
Before integrating the Code Interpreter with our Harness, let us clean up the custom Code Interpreters created in the previous steps. Then we will create a new one specifically designed for the agent use case: a Sandbox mode Code Interpreter with no access to S3 or DynamoDB. In our architecture, data will come from other tools (MCP servers, Gateway) in future articles. The Code Interpreter’s job is purely computational.
6.1 Delete Previous Code Interpreters
6.1.1. Navigate to Amazon Bedrock AgentCore > Built-in tools > Code Interpreter
6.1.2. Select the Code Interpreters created in previous steps (e.g., code_interpreter_tool_demo and code_interpreter_public_dynamo)
6.1.3. Click Delete and confirm
6.2 Create a New Sandbox Code Interpreter (No External Access)
6.2.1. Click Create
6.2.2. In the Tool name field, enter code_interpreter_sandbox_ci
6.2.3. Under Tool configurations > Security, select Sandbox as the network mode
6.2.4. Leave all remaining settings at their defaults
6.2.5. Click Create the Code Interpreter
This new Code Interpreter is a pure computation sandbox. It can run Python, JavaScript, or TypeScript code but cannot access any external resources. This is exactly what we want for the Harness integration: the agent will use it solely for calculations and data processing.
Step 7: Integrating Code Interpreter with the Harness
Now we connect the Code Interpreter as a tool to the Harness we created in the first article of this series. The agent (our car dealership assistant) will autonomously decide to write and execute Python code when it needs to perform precise calculations. We do not write the code ourselves. The AI generates it, sends it to the Code Interpreter sandbox for execution, reads the result, and formulates a response.
In this example, the agent does not need database access because the data (car prices) is provided directly in the user’s question. In future articles, we will explore how to combine data retrieval tools (like MCP servers or AgentCore Gateway) with the Code Interpreter, where one tool fetches data and the other performs calculations.
7.1 Edit the Harness to Add Code Interpreter
7.1.1. Open the Amazon Bedrock AgentCore Harness console
7.1.2. Click on your Harness name (car_agent) to open its details page. If you deleted it after the previous article, create a new one following the same steps from that article.
7.1.3. On the Harness details page, click the Edit button in the top-right area
7.1.4. On the Edit Harness page, scroll down to the Tools section and expand it
7.1.5. Enable the Code interpreter tool toggle. In the dropdown that appears, select the Code Interpreter you created in Step 6 (code_interpreter_sandbox_ci). You can also select the system default AgentCore Code Interpreter if you prefer not to create a custom one.
7.1.6. Click Save Harness at the bottom of the page. Once the update completes, you will see a confirmation message:
car_agent, Version 2 was successfully updated. A default endpoint is also in progress and will be associated with Version 2.Wait for the status to return to Ready before proceeding.
7.2 Test with a Financing Calculation
7.2.1. Once the Harness is Ready, click the Test Harness button in the top-right corner
7.2.2. In the chat interface, enter the following prompt:
A customer is deciding between three cars from our inventory:
1. Honda Civic 2019 - $17,800
2. Mazda Mazda3 2021 - $22,500
3. Toyota RAV4 2021 - $28,500
A bank offered a financing rate of 7.5% per year (compound interest). The customer wants to finance the car over 3 years (36 monthly payments). They said their maximum budget is $700 per month for the installment.
Please calculate the monthly payment for each car and determine which ones fit within the customer's budget. Show the total amount paid over the financing period for each option.7.2.3. Observe the agent’s response. The test interface will show indicators like “Code Interpreter x3”, confirming that the agent invoked the Code Interpreter multiple times to perform the calculations. In the response, you can see the agent reasoning about the compound interest formula and working through each car’s monthly payment. At the end, it presents an elaborated response indicating which cars fit within the customer’s budget and which do not.
7.2.4. If the results are not satisfactory (incorrect calculations, incomplete reasoning, or too many Code Interpreter retries), you can go back to the Harness edit page and select a different model. In this test, we used amazon.nova-micro-v1:0, which is the most cost-effective option with lower latency but limited reasoning capabilities. Larger models like Nova Pro or Claude Sonnet produce more accurate code on the first attempt and require fewer retries, but cost more per token and may have higher latency. Choose the model that best balances cost, accuracy, and response time for your use case.
7.3 Verify in Observability
You can confirm that the Code Interpreter was actually invoked by checking the observability metrics. Navigate to Amazon Bedrock AgentCore > Built-in tools > Code Interpreter, select your Code Interpreter, and check the observability section. After a few minutes, the metrics will show the invocation activity.
Note that observability data may take a couple of minutes to appear. If you do not see the metrics immediately after the test, wait and reload the page.
The key insight here is that you never wrote the financing calculation code. The agent decided it needed to run code, generated a Python script with the standard amortization formula, executed it in the sandbox, and used the results to answer the customer’s question accurately. This is the difference between using Code Interpreter as a direct execution engine (Steps 3–5) versus using it as an autonomous tool for an AI agent.
Conclusion
In this article, you explored three ways to use the Amazon Bedrock AgentCore Code Interpreter:
- Sandbox mode with direct invocation (Steps 2–4): A restricted environment where the Code Interpreter can only access S3. You created a custom Code Interpreter, configured an IAM execution role for S3 read access, and used terminal commands inside the sandbox to download and analyze a CSV file with Pandas.
- Public mode with direct invocation (Step 5): An open environment where the Code Interpreter can access any AWS service or the public internet. You created a second Code Interpreter with DynamoDB read permissions and used it to query a live car inventory table, performing statistical analysis on the data.
- Harness integration with autonomous code generation (Steps 6–7): The most powerful pattern. You created a pure computation sandbox (no external access), attached it to the Harness via the AWS Console, and let the AI agent autonomously write and execute a financing calculation to answer a customer question.
The key takeaways are:
- Direct invocation (Steps 3–5) is useful for scripted pipelines where you control what code runs. You write the code, the sandbox executes it.
- Harness integration (Step 7) is the agentic pattern. The AI decides when and what code to write. The Code Interpreter provides computational accuracy that complements the model’s reasoning capabilities.
- Network mode determines the blast radius. Use Sandbox when no external access is needed (or when data comes from other tools). Use Public when the sandbox itself needs to reach AWS services or the internet.
- Data retrieval and computation are separate concerns. In production, use dedicated tools (MCP servers, Gateway) to fetch data and the Code Interpreter for calculations. The Code Interpreter is designed for computation, not data retrieval. This separation follows security best practices and will be explored in future articles.
References
Stay Connected
If you found this article helpful and want to learn more about AWS, cloud architecture, AI, infrastructure as code, and cloud security, follow the author for future content and tutorials:
- LinkedIn: https://www.linkedin.com/in/biagolini
- Medium: https://medium.com/@biagolini
- GitHub: https://github.com/biagolini
- YouTube (PT-BR): https://www.youtube.com/@BiagoliniTech
- AWS Builder Center (PT-BR): https://builder.aws.com/community/@cbiagolini
Stay tuned for more practical walkthroughs and solutions for cloud infrastructure and DevOps challenges.
Happy building on AWS! 🚀☁️










