

# Get started with AgentCore Code Interpreter
<a name="code-interpreter-getting-started"></a>

AgentCore Code Interpreter enables your agents to execute Python code in a secure, managed environment. The agent can perform calculations, analyze data, generate visualizations, and validate answers through code execution.

This page covers the prerequisites and provides two approaches to get started:
+  **Using AWS Strands** - A high-level agent framework that simplifies building AI agents with built-in tool integration, conversation management, and automatic session handling.
+  **Direct usage** - SDK and Boto3 approaches that provide more control over session management and code execution for custom implementations.

**Topics**
+ [

## Prerequisites
](#code-interpreter-prerequisites)
+ [

## Configuring your credentials
](#code-interpreter-credentials-config)
+ [

# Using AgentCore Code Interpreter via AWS Strands
](code-interpreter-using-strands.md)
+ [

# Using AgentCore Code Interpreter directly
](code-interpreter-using-directly.md)

## Prerequisites
<a name="code-interpreter-prerequisites"></a>

Before you start, ensure you have:
+  AWS account with credentials configured. See [Configuring your credentials](#code-interpreter-credentials-config).
+ Python 3.10\$1 installed
+ Boto3 installed. See [Boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html).
+ IAM execution role with the required permissions. See [Configuring your credentials](#code-interpreter-credentials-config).
+ Model access: Anthropic Claude Sonnet 4.0 [enabled](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html) in the Amazon Bedrock console. For information about using a different model with the Strands Agents see the *Model Providers* section in the [Strands Agents SDK documentation](https://strandsagents.com/latest/documentation/docs/).
+  AWS Region where Amazon Bedrock AgentCore is available. See [Supported AWS Regions](agentcore-regions.md).

## Configuring your credentials
<a name="code-interpreter-credentials-config"></a>

Perform the following steps to configure your AWS credentials and attach the required permissions.

1.  **Verify your AWS credentials** 

   Confirm your AWS credentials are configured:

   ```
   aws sts get-caller-identity
   ```
**Note**  
Take note of the user or credentials returned here, as you’ll be using it when attaching the required permissions.

   If this command fails, configure your credentials. For more information, see [Configuration and credential file settings in the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html).

1.  **Attach required permissions** 

   Your IAM user or role needs permissions to use AgentCore Code Interpreter. Attach this policy to your IAM identity:
**Note**  
Replace `<region>` with your chosen region (for example, `us-west-2` ) and `<account_id>` with your AWS account ID in the policy below:

   ```
   {
       "Version":"2012-10-17",	
       "Statement": [
           {
               "Sid": "BedrockAgentCoreCodeInterpreterFullAccess",
               "Effect": "Allow",
               "Action": [
                   "bedrock-agentcore:CreateCodeInterpreter",
                   "bedrock-agentcore:StartCodeInterpreterSession",
                   "bedrock-agentcore:InvokeCodeInterpreter",
                   "bedrock-agentcore:StopCodeInterpreterSession",
                   "bedrock-agentcore:DeleteCodeInterpreter",
                   "bedrock-agentcore:ListCodeInterpreters",
                   "bedrock-agentcore:GetCodeInterpreter",
                   "bedrock-agentcore:GetCodeInterpreterSession",
                   "bedrock-agentcore:ListCodeInterpreterSessions"
               ],
               "Resource": "arn:aws:bedrock-agentcore:<region>:++<account_id>++:code-interpreter/*"
           }
       ]
   }
   ```

 **To attach this policy** 

Follow these steps:

1. Go to the IAM console.

1. Find your user or role from the response returned for the `get-caller-identity` API operation.

1. Choose **Add permissions** and then choose **Create inline policy** 

1. Switch to JSON view and paste the policy above

1. Name it `AgentCoreCodeInterpreterAccess` and save

**Note**  
If you’re deploying agents to Amazon Bedrock AgentCore Runtime, you’ll also eed to create an IAM execution role with a service trust policy. For more information, see [Get started with AgentCore Runtime](runtime-getting-started.md).

The following sections show you how to use the Amazon Bedrock AgentCore Code Interpreter with and without the agent framework. Using the Code Interpeter directly without an agent framework is especially useful when you want to execute specific code snippets programmatically.

# Using AgentCore Code Interpreter via AWS Strands
<a name="code-interpreter-using-strands"></a>

The following sections show you how to use the Amazon Bedrock AgentCore Code Interpreter with the Strands SDK. Before you go through the examples in this section, see [Prerequisites](code-interpreter-getting-started.md#code-interpreter-prerequisites).

**Topics**
+ [

## Step 1: Install dependencies
](#code-interpreter-strands-install)
+ [

## Step 2: Create your agent with AgentCore Code Interpreter
](#code-interpreter-strands-create)
+ [

## Step 3: Run the agent
](#code-interpreter-strands-run)

## Step 1: Install dependencies
<a name="code-interpreter-strands-install"></a>

Create a project folder and install the required packages:

**Note**  
On Windows, use: `.venv\Scripts\activate` 

```
mkdir agentcore-tools-quickstart
cd agentcore-tools-quickstart
python3 -m venv .venv
source .venv/bin/activate
```

Install the required packages:

```
pip install bedrock-agentcore strands-agents strands-agents-tools
```

These packages provide:
+  `bedrock-agentcore` : The SDK for Amazon Bedrock AgentCore tools including AgentCore Code Interpreter
+  `strands-agents` : The Strands agent framework
+  `strands-agents-tools` : The tools that the Strands agent framework offers

## Step 2: Create your agent with AgentCore Code Interpreter
<a name="code-interpreter-strands-create"></a>

Create a file named `code_interpreter_agent.py` and add the following code:

```
from strands import Agent
from strands_tools.code_interpreter import AgentCoreCodeInterpreter

# Initialize the Code Interpreter tool
code_interpreter_tool = AgentCoreCodeInterpreter(region="<Region>")

# Define the agent's system prompt
SYSTEM_PROMPT = """You are an AI assistant that validates answers through code execution.
When asked about code, algorithms, or calculations, write Python code to verify your answers."""

# Create an agent with the Code Interpreter tool
agent = Agent(
    tools=[code_interpreter_tool.code_interpreter],
    system_prompt=SYSTEM_PROMPT
)

# Test the agent with a sample prompt
prompt = "Calculate the first 10 Fibonacci numbers."
print(f"\n\nPrompt: {prompt}\n\n")

response = agent(prompt)
print(response.message["content"][0]["text"])
```

This code:
+ Initializes the AgentCore Code Interpreter tool for your region
+ Creates an agent configured to use code execution for validation
+ Sends a prompt asking the agent to calculate Fibonacci numbers
+ Prints the agent’s response

## Step 3: Run the agent
<a name="code-interpreter-strands-run"></a>

Execute the script:

```
python code_interpreter_agent.py
```

 **Expected output** 

You should see the agent’s response containing the first 10 Fibonacci numbers. The agent will write Python code to calculate the sequence and return both the code and the results.

If you encounter errors, verify:
+ Your IAM role has the correct permissions and trust policy
+ You have model access enabled in the Amazon Bedrock console
+ Your AWS credentials are properly configured

# Using AgentCore Code Interpreter directly
<a name="code-interpreter-using-directly"></a>

The following sections show you how to use the Amazon Bedrock AgentCore Code Interpreter directly without an agent framework. This is especially useful when you want to execute specific code snippets programmatically. Before you go through the examples in this section, see [Prerequisites](code-interpreter-getting-started.md#code-interpreter-prerequisites).

**Topics**
+ [

## Step 1: Choose your approach and install dependencies
](#code-interpreter-direct-install)
+ [

## Step 2: Execute code
](#code-interpreter-direct-execute)

## Step 1: Choose your approach and install dependencies
<a name="code-interpreter-direct-install"></a>

Amazon Bedrock AgentCore provides two ways to interact with AgentCore Code Interpreter: using the high-level SDK client or using boto3 directly.
+  **SDK Client** : The `bedrock_agentcore` SDK provides a simplified interface that handles session management details. Use this approach for most applications.
+  **Boto3 Client** : The AWS SDK gives you direct access to the AgentCore Code Interpreter API operations. Use this approach when you need fine-grained control over session configuration or want to integrate with existing boto3-based applications.

Create a project folder (if you didn’t create one before) and install the required packages:

```
mkdir agentcore-tools-quickstart
cd agentcore-tools-quickstart
python3 -m venv .venv
source .venv/bin/activate
```

On Windows, use: `.venv\Scripts\activate` 

Install the required packages:

```
pip install bedrock-agentcore boto3
```

These packages provide:
+  `bedrock-agentcore` : The SDK for Amazon Bedrock AgentCore tools including AgentCore Code Interpreter
+  `boto3` : AWS SDK for Python (Boto3) to create, configure, and manage AWS services

## Step 2: Execute code
<a name="code-interpreter-direct-execute"></a>

Choose one of the following approaches to execute code with AgentCore Code Interpreter:

**Note**  
Replace `<Region>` with your actual AWS Region (for example, `us-east-1` or `us-west-2` ).

**Example**  

1. Create a file named `direct_code_execution_sdk.py` and add the following code:

   ```
   from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
   import json
   
   # Initialize the Code Interpreter client for your region
   code_client = CodeInterpreter('<Region>')
   
   # Start a Code Interpreter session
   code_client.start()
   
   try:
       # Execute Python code
       response = code_client.invoke("executeCode", {
           "language": "python",
           "code": 'print("Hello World!!!")'
       })
   
       # Process and print the response
       for event in response["stream"]:
           print(json.dumps(event["result"], indent=2))
   
   finally:
       # Always clean up the session
       code_client.stop()
   ```

   This code:
   + Creates a AgentCore Code Interpreter client for your region
   + Starts a session (required before executing code)
   + Executes Python code and streams the results with full event details
   + Stops the session to clean up resources

      **Run the script** 

     Execute the following command:

     ```
     python direct_code_execution_sdk.py
     ```

      **Expected output** 

     You should see a JSON response containing the execution result with `Hello World!!!` in the output content.

1. Create a file named `direct_code_execution_boto3.py` and add the following code:

   ```
   import boto3
   import json
   
   # Code to execute
   code_to_execute = """
   print("Hello World!!!")
   """
   
   # 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="aws.codeinterpreter.v1",
       name="my-code-session",
       sessionTimeoutSeconds=900
   )
   session_id = session_response["sessionId"]
   
   print(f"Started session: {session_id}\n\n")
   
   try:
       # Execute code in the session
       execute_response = client.invoke_code_interpreter(
           codeInterpreterIdentifier="aws.codeinterpreter.v1",
           sessionId=session_id,
           name="executeCode",
           arguments={
               "language": "python",
               "code": code_to_execute
           }
       )
   
       # 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="aws.codeinterpreter.v1",
           sessionId=session_id
       )
       print(f"\n\nStopped session: {session_id}")
   ```

   This code:
   + Creates a boto3 client for the bedrock-agentcore service
   + Starts a AgentCore Code Interpreter session with a 900-second timeout
   + Executes Python code using the session ID
   + Parses the streaming response to extract text output
   + Properly stops the session to release resources

     The boto3 approach requires explicit session management. You must call `start_code_interpreter_session` before executing code and `stop_code_interpreter_session` when finished.

      **Run the script** 

     Execute the following command:

     ```
     python direct_code_execution_boto3.py
     ```

      **Expected output** 

     You should see `Hello World!!!` printed as the result of the code execution, along with the session ID information.