

# Resource and session management
<a name="code-interpreter-resource-session-management"></a>

The following topics show how the Amazon Bedrock AgentCore Code Interpreter works and how you can create the resources and manage sessions.

**Topics**
+ [IAM permissions](#code-interpreter-iam-permissions)
+ [How it works](#code-interpreter-how-it-works)
+ [Creating a Code Interpreter and starting a session](#code-interpreter-create-session)
+ [Resource management](code-interpreter-resource-management.md)
+ [Session management](code-interpreter-session-characteristics.md)

## IAM permissions
<a name="code-interpreter-iam-permissions"></a>

The following IAM policy provides the necessary permissions for using the AgentCore Code Interpreter:

```
{
"Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "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:us-east-1:111122223333:code-interpreter/*"
        }
    ]
}
```

You should also add the following trust policy to the execution role:

```
{
"Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Sid": "BedrockAgentCoreBuiltInTools",
        "Effect": "Allow",
        "Principal": {
            "Service": "bedrock-agentcore.amazonaws.com"
        },
        "Action": "sts:AssumeRole",
        "Condition": {
            "StringEquals": {
                "aws:SourceAccount": "111122223333"
            },
            "ArnLike": {
                "aws:SourceArn": "arn:aws:bedrock-agentcore:us-east-1:111122223333:*"
            }
        }
    }]
}
```

## How it works
<a name="code-interpreter-how-it-works"></a>

1.  **Create a Code Interpreter** 

   Build your own Code Interpreter or use the System Code Interpreter to enable capabilities such as writing and running code or performing complex calculations. The Code Interpreter allows you to augment your agent runtime to securely execute code in a fully managed environment with low latency.

1.  **Integrate it within an agent to invoke** 

   Copy the built-in tool resource ID into your runtime agent code to invoke it as part of your session. For Code Interpreter tools, you can execute code and view the results in real-time.

1.  **Assess performance using observability** 

   Monitor key metrics for each tool in CloudWatch to get real-time performance insights.

## Creating a Code Interpreter and starting a session
<a name="code-interpreter-create-session"></a>

1.  **Create a Code Interpreter** 

   When configuring a Code Interpreter, you can choose network settings (Sandbox or Public), and the execution role role that defines what AWS resources the Code Interpreter can access.

1.  **Start a session** 

   The Code Interpreter uses a session-based model. After creating a Code Interpreter, you start a session with a configurable timeout period (default is 15 minutes). Sessions automatically terminate after the timeout period. Multiple sessions can be active simultaneously for a single Code Interpreter, with each session maintaining its own state and environment.

1.  **Execute code** 

   Within an active session, you can execute code in supported languages (Python, JavaScript, TypeScript), and maintain state between executions. You can also perform file upload/download operations, and use the support provided for the shell commands and AWS CLI commands.

1.  **Stop session and clean up** 

   When you’re finished using a session, you should stop it to release resources and avoid unnecessary charges. You can also delete the Code Interpreter if you no longer intend to use it.

# Resource management
<a name="code-interpreter-resource-management"></a>

The AgentCore Code Interpreter provides two types of resources:

System ARNs  
System ARNs are default resources pre-created for ease of use. These ARNs have default configuration with the most restrictive options and are available for all regions where Amazon Bedrock AgentCore is available.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/code-interpreter-resource-management.html)

Custom ARNs  
Custom ARNs allow you to configure a code interpreter with your own settings. You can choose network settings (Sandbox or Public), and the execution role that defines what AWS resources the code interpreter can access.

**Topics**
+ [Network settings](#code-interpreter-network-settings)
+ [Creating an AgentCore Code Interpreter](code-interpreter-create.md)
+ [Listing AgentCore Code Interpreter tools](code-interpreter-list.md)
+ [Deleting an AgentCore Code Interpreter](code-interpreter-delete.md)

## Network settings
<a name="code-interpreter-network-settings"></a>

The AgentCore Code Interpreter supports the following network modes:

Sandbox mode  
Provides limited external network access. In Sandbox mode, the code interpreter can access Amazon S3 for data operations and perform DNS resolution.

Public network mode  
Allows the tool to access public internet resources. This option enables integration with external APIs and services but introduces potential security considerations.

VPC mode  
Connects the tool to your Virtual Private Cloud (VPC), allowing access to private resources within your AWS environment such as databases, internal APIs, and other services while maintaining network isolation from the public internet. This option requires additional VPC configuration.

The following topics show you how to create and manage Code Interpreters, start and stop sessions, and how to execute code.

# Creating an AgentCore Code Interpreter
<a name="code-interpreter-create"></a>

You can create a Code Interpreter using the Amazon Bedrock AgentCore console, AWS CLI, or AWS SDK.

**Example**  

1. ====== To create a Code Interpreter using the console

1. Open the AgentCore console at [https://console.aws.amazon.com/bedrock-agentcore/home\$1](https://console.aws.amazon.com/bedrock-agentcore/home#).

1. In the navigation pane, choose **Built-in tools**.

1. Choose **Create Code Interpreter tool**.

1. Provide a unique **Tool name** and optional **Description**.

1. Under **Network settings** , choose one of the following options:
   +  **Sandbox** - Environment with limited external network access
   +  **Public network** - Allows access to public internet resources

1. Under **Permissions** , specify an IAM runtime role that defines what AWS resources the Code Interpreter can access.

1. Choose **Create**.

   After creating a Code Interpreter tool, the console displays important details about the tool:
The Amazon Resource Name (ARN) that uniquely identifies the Code Interpreter tool resource (e.g., arn:aws:bedrock-agentcore:<Region>:123456789012:code-interpreter/code-interpreter-custom).
The unique identifier for the Code Interpreter tool, used in API calls (e.g., code-interpreter-custom-abc123).
The IAM role that the Code Interpreter assumes when executing code, determining what AWS resources it can access.
The network configuration for the Code Interpreter (Sandbox or Public).
The date and time when the Code Interpreter tool was created.

1. To create a Code Interpreter using the AWS CLI, use the `create-code-interpreter` command:

   ```
   aws bedrock-agentcore create-code-interpreter \
     --region <Region> \
     --name "my-code-interpreter" \
     --description "My Code Interpreter for data analysis" \
     --network-configuration '{
       "networkMode": "PUBLIC"
     }' \
     --execution-role-arn "arn:aws:iam::123456789012:role/my-execution-role"
   ```

1. To create a Code Interpreter using the AWS SDK for Python, use the `create_code_interpreter` method:

   ```
   import boto3
   
   # Initialize the boto3 client
   cp_client = boto3.client(
       'bedrock-agentcore-control',
       region_name="<Region>",
       endpoint_url="https://bedrock-agentcore-control.<Region>.amazonaws.com"
   )
   
   # Create a Code Interpreter
   response = cp_client.create_code_interpreter(
       name="myTestSandbox1",
       description="Test code sandbox for development",
       executionRoleArn="arn:aws:iam::123456789012:role/my-execution-role",
       networkConfiguration={
           "networkMode": "PUBLIC"
       }
   )
   
   # Print the Code Interpreter ID
   code_interpreter_id = response["codeInterpreterId"]
   print(f"Code Interpreter ID: {code_interpreter_id}")
   ```

1. To create a new Code Interpreter instance using the API, use the following call:

   ```
   # Using awscurl
   awscurl -X PUT "https://bedrock-agentcore-control.<Region>.amazonaws.com/code-interpreters" \
   -H "Content-Type: application/json" \
   --region <Region> \
   --service bedrock-agentcore \
   -d '{
       "name": "codeinterpreter'$(date +%m%d%H%M%S)'",
       "description": "Test code sandbox for development",
       "executionRoleArn": "'${ROLE_ARN}'",
       "networkConfiguration": {
           "networkMode": "PUBLIC"
       }
   }'
   ```

# Listing AgentCore Code Interpreter tools
<a name="code-interpreter-list"></a>

You can view a list of all your Code Interpreter tools to manage and monitor them.

**Example**  

1. ====== To list code interpreters using the console

1. Open the AgentCore console at [https://console.aws.amazon.com/bedrock-agentcore/home\$1](https://console.aws.amazon.com/bedrock-agentcore/home#).

1. In the navigation pane, choose **Built-in tools**.

1. The console displays a list of all your Code Interpreter tools, including their names, IDs, creation dates, and status.

1. You can use the search box to filter the list by name or other attributes.

1. Select a Code Interpreter to view its details, including active sessions and configuration settings.

1. To list Code Interpreters using the AWS CLI, use the `list-code-interpreters` command:

   ```
   aws bedrock-agentcore list-code-interpreters \
     --region <Region> \
     --max-results 10
   ```

   You can use the `--next-token` parameter for pagination if you have more than the maximum results:

   ```
   aws bedrock-agentcore list-code-interpreters \
     --region <Region> \
     --max-results 10 \
     --next-token "<your-pagination-token>"
   ```

1. To list Code Interpreters using the AWS SDK for Python, use the `list_code_interpreters` method:

   ```
   import boto3
   
   # Initialize the boto3 client
   cp_client = boto3.client(
       'bedrock-agentcore-control',
       region_name="<Region>",
       endpoint_url="https://bedrock-agentcore-control.<Region>.amazonaws.com"
   )
   
   # List Code Interpreters
   response = cp_client.list_code_interpreters()
   
   # Print the Code Interpreters
   for interpreter in response.get('codeInterpreterSummaries', []):
       print(f"Name: {interpreter.get('name')}")
       print(f"ID: {interpreter.get('codeInterpreterId')}")
       print(f"Creation Time: {interpreter.get('createdAt')}")
       print(f"Status: {interpreter.get('status')}")
       print("---")
   
   # If there are more results, get the next page using the next_token
   if 'nextToken' in response:
       next_page = cp_client.list_code_interpreters(
           nextToken=response['nextToken']
       )
       # Process next_page...
   ```

1. To list Code Interpreter instances using the API, use the following call:
**Note**  
For pagination, include the nextToken parameter.

   ```
   # Using awscurl
   awscurl -X POST "https://bedrock-agentcore-control.<Region>.amazonaws.com/code-interpreters" \
     -H "Accept: application/json" \
     --service bedrock-agentcore \
     --region <Region>
   ```

# Deleting an AgentCore Code Interpreter
<a name="code-interpreter-delete"></a>

When you no longer need a Code Interpreter, you can delete it to free up resources and avoid unnecessary charges.

**Important**  
Deleting a Code Interpreter permanently removes it and all its configuration. This action cannot be undone. Make sure all active sessions are stopped before deleting a Code Interpreter.

**Example**  

1. ====== To delete a Code Interpreter using the console

1. Open the AgentCore console at [https://console.aws.amazon.com/bedrock-agentcore/home\$1](https://console.aws.amazon.com/bedrock-agentcore/home#).

1. In the navigation pane, choose **Built-in tools**.

1. From the list of code interpreter tools, select the tool you want to delete.

1. Choose **Delete**.

1. In the confirmation dialog, enter the name of the code interpreter to confirm deletion.

1. Choose **Delete** to permanently delete the Code Interpreter.

1. To delete a Code Interpreter using the AWS CLI, use the `delete-code-interpreter` command:

   ```
   aws bedrock-agentcore delete-code-interpreter \
     --region <Region> \
     --code-interpreter-id "<your-code-interpreter-id>"
   ```

1. To delete a Code Interpreter using the AWS SDK for Python, use the `delete_code_interpreter` method:

   ```
   import boto3
   
   # Initialize the boto3 client
   cp_client = boto3.client(
       'bedrock-agentcore-control',
       region_name="<Region>",
       endpoint_url="https://bedrock-agentcore-control.<Region>.amazonaws.com"
   )
   
   # Delete a Code Interpreter
   response = cp_client.delete_code_interpreter(
       codeInterpreterId="<your-code-interpreter-id>"
   )
   
   print("Code Interpreter deleted successfully")
   ```

1. To delete a Code Interpreter instance using the API, use the following call:

   ```
   # Using awscurl
   awscurl -X DELETE "https://bedrock-agentcore-control.<Region>.amazonaws.com/code-interpreters/<your-code-interpreter-id>" \
   -H "Accept: application/json" \
   --service bedrock-agentcore \
   --region <Region>
   ```

# Session management
<a name="code-interpreter-session-characteristics"></a>

The AgentCore Code Interpreter sessions have the following characteristics:

Session timeout  
Default: 900 seconds (15 minutes)  
Configurable: Can be adjusted when creating sessions, up to 8 hours

Session persistence  
Files and data created during a session are available throughout the session’s lifetime. When the session is terminated, the session no longer persists and the data is cleaned up.

Automatic termination  
Sessions automatically terminate after the configured timeout period

Multiple sessions  
Multiple sessions can be active simultaneously for a single code interpreter. Each session maintains its own state and environment

Retention policy  
The time to live (TTL) retention policy for the session data is 30 days.

**Topics**
+ [Using isolated sessions](#code-interpreter-isolated-sessions)
+ [Starting a AgentCore Code Interpreter session](code-interpreter-start-session.md)
+ [Executing code](code-interpreter-execute-code.md)
+ [Runtime selection](code-interpreter-runtime-selection.md)
+ [Stopping a AgentCore Code Interpreter session](code-interpreter-stop-session.md)

## Using isolated sessions
<a name="code-interpreter-isolated-sessions"></a>

AgentCore Tools enable isolation of each user session to ensure secure and consistent reuse of context across multiple tool invocations. Session isolation is especially important for AI agent workloads due to their dynamic and multi-step execution patterns.

Each tool session runs in a dedicated microVM with isolated CPU, memory, and filesystem resources. This architecture guarantees that one user’s tool invocation cannot access data from another user’s session. Upon session completion, the microVM is fully terminated, and its memory is sanitized, thereby eliminating any risk of cross-session data leakage.

# Starting a AgentCore Code Interpreter session
<a name="code-interpreter-start-session"></a>

After creating a Code Interpreter, you can start a session to execute code.

**Example**  

1. To start a Code Interpreter session using the AWS CLI, use the `start-code-interpreter-session` command:

   ```
   aws bedrock-agentcore start-code-interpreter-session \
     --region <Region> \
     --code-interpreter-id "<your-code-interpreter-id>" \
     --name "my-code-session" \
     --description "My Code Interpreter session for data analysis" \
     --session-timeout-seconds 900
   ```

1. To start a Code Interpreter session using the AWS SDK for Python, use the `start_code_interpreter_session` method:

   ```
   import boto3
   
   # Initialize the boto3 client
   dp_client = boto3.client(
       'bedrock-agentcore',
       region_name="<Region>",
       endpoint_url="https://bedrock-agentcore.<Region>.amazonaws.com"
   )
   
   # Start a Code Interpreter session
   response = dp_client.start_code_interpreter_session(
       codeInterpreterIdentifier="aws.codeinterpreter.v1",
       name="sandbox-session-1",
       sessionTimeoutSeconds=3600
   )
   
   # Print the session ID
   session_id = response["sessionId"]
   print(f"Session created: {session_id}")
   ```

1. To start a new Code Interpreter session using the API, use the following call:

   ```
   # Using awscurl
   awscurl -X PUT \
     "https://bedrock-agentcore.<Region>.amazonaws.com/code-interpreters/aws.codeinterpreter.v1/sessions/start" \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     --service bedrock-agentcore \
     --region <Region> \
     -d '{
       "name": "code-session-abc12345",
       "description": "code sandbox session",
       "sessionTimeoutSeconds": 900
     }'
   ```
**Note**  
You can use the managed resource ID `aws.codeinterpreter.v1` or a resource ID you get by creating a code interpreter with `CreateCodeInterpreter`.

# Executing code
<a name="code-interpreter-execute-code"></a>

Once you have started a Code Interpreter session, you can execute code in the session.

**Example**  

1. To execute code using the AWS SDK for Python, use the `invoke_code_interpreter` method:

   ```
   import boto3
   import json
   
   # Initialize the boto3 client
   dp_client = boto3.client(
       'bedrock-agentcore',
       region_name="<Region>",
       endpoint_url="https://bedrock-agentcore.<Region>.amazonaws.com"
   )
   
   # Execute code in the Code Interpreter session
   response = dp_client.invoke_code_interpreter(
       codeInterpreterIdentifier="aws.codeinterpreter.v1",
       sessionId="<your-session-id>",
       name="executeCode",
       arguments={
           "language": "python",
           "code": 'print("Hello World!!!")'
       }
   )
   
   # Process the event stream
   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"])
   ```

1. To execute code in a code interpreter session using the API, use the following call:

   ```
   # Using awscurl
   awscurl -X POST \
     "https://bedrock-agentcore.<Region>.amazonaws.com/code-interpreters/aws.codeinterpreter.v1/tools/invoke" \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "x-amzn-code-interpreter-session-id: your-session-id" \
     --service bedrock-agentcore \
     --region <Region> \
     -d '{
       "id": "1",
       "name": "executeCode",
       "arguments": {
         "language": "python",
         "code": "print(\"Hello, world!\")"
       }
     }'
   ```

# Runtime selection
<a name="code-interpreter-runtime-selection"></a>

For a language, you can optionally specify a particular runtime. The following table shows the supported languages and their available runtimes.


| Language | Available runtimes | 
| --- | --- | 
|  Python  |   `python`   | 
|  JavaScript  |   `nodejs` , `deno`   | 
|  TypeScript  |   `nodejs` , `deno`   | 

**Note**  
For the `nodejs` runtime, we support CommonJS (CJS) modules for JavaScript and ECMAScript (ESM) modules for TypeScript.

# Stopping a AgentCore Code Interpreter session
<a name="code-interpreter-stop-session"></a>

When you are finished using a Code Interpreter session, you should stop it to release resources and avoid unnecessary charges.

**Example**  

1. To stop a code interpreter session using the AWS CLI, use the `stop-code-interpreter-session` command:

   ```
   aws bedrock-agentcore stop-code-interpreter-session \
     --region <Region> \
     --code-interpreter-id "<your-code-interpreter-id>" \
     --session-id "<your-session-id>"
   ```

1. To stop a Code Interpreter session using the AWS SDK for Python, use the `stop_code_interpreter_session` method:

   ```
   import boto3
   
   # Initialize the boto3 client
   dp_client = boto3.client(
       'bedrock-agentcore',
       region_name="<Region>",
       endpoint_url="https://bedrock-agentcore.<Region>.amazonaws.com"
   )
   
   # Stop the Code Interpreter session
   response = dp_client.stop_code_interpreter_session(
       codeInterpreterIdentifier="aws.codeinterpreter.v1",
       sessionId="<your-session-id>"
   )
   
   print("Session stopped successfully")
   ```

1. To stop a code interpreter session using the API, use the following call:

   ```
   # Using awscurl
   awscurl -X PUT \
     "https://bedrock-agentcore.<Region>.amazonaws.com/code-interpreters/aws.codeinterpreter.v1/sessions/stop?sessionId=<your-session-id>" \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     --service bedrock-agentcore \
     --region <Region>
   ```