

# Execute code and analyze data using Amazon Bedrock AgentCore Code Interpreter
<a name="code-interpreter-tool"></a>

The Amazon Bedrock AgentCore Code Interpreter enables AI agents to write and execute code securely in sandbox environments, enhancing their accuracy and expanding their ability to solve complex end-to-end tasks. This is critical in Agentic AI applications where the agents may execute arbitrary code that can lead to data compromise or security risks. The AgentCore Code Interpreter tool provides secure code execution, which helps you avoid running into these issues.

The Code Interpreter comes with pre-built runtimes for multiple languages and advanced features, including large file support and internet access, and CloudTrail logging capabilities. For inline upload, the file size can be up to 100 MB. And for uploading to Amazon S3 through terminal commands, the file size can be as large as 5 GB.

Developers can customize environments with session properties and network modes to meet their enterprise and security requirements. The AgentCore Code Interpreter reduces manual intervention while enabling sophisticated AI development without compromising security or performance.

**Topics**
+ [Overview](#code-interpreter-overview)
+ [Why use Code Interpreter in agent development](#code-interpreter-why-important)
+ [Best practices](#code-interpreter-best-practices)
+ [Pre-installed libraries](code-interpreter-preinstalled-libraries.md)
+ [Get started with AgentCore Code Interpreter](code-interpreter-getting-started.md)
+ [Run code in Code Interpreter from Agents](code-interpreter-building-agents.md)
+ [Write files to a session](code-interpreter-file-operations.md)
+ [Using Terminal Commands with an execution role](code-interpreter-s3-integration.md)
+ [Resource and session management](code-interpreter-resource-session-management.md)
+ [Code Interpreter API Reference Examples](code-interpreter-api-reference-examples.md)
+ [Observability](code-interpreter-observability.md)
+ [Configure Root Certificate Authority for Amazon Bedrock AgentCore Code Interpreter](code-interpreter-root-ca-certificates.md)
+ [Troubleshoot AgentCore Code Interpreter](code-interpreter-troubleshooting.md)

## Overview
<a name="code-interpreter-overview"></a>

The AgentCore Code Interpreter is a capability that allows AI agents to write, execute, and debug code securely in sandbox environments. It provides a bridge between natural language understanding and computational execution, enabling agents to manipulate data and perform calculations programmatically.

The AgentCore Code Interpreter runs in a containerized environment within Amazon Bedrock AgentCore, ensuring that code execution remains isolated and secure.

![\[Architecture showing the built-in tools offering and Browser and CI tools.\]](http://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/images/code-interpreter.png)


## Why use Code Interpreter in agent development
<a name="code-interpreter-why-important"></a>

The AgentCore Code Interpreter enhances agent development in the following ways:
+ Execute code securely: Develop agents that can perform complex workflows and data analysis in sandbox environments, while accessing internal data sources without exposing sensitive data or compromising security.
+ Multiple programming languages: The Code Interpreter supports various programming languages including Python, JavaScript, and TypeScript, making it versatile for different use cases.
+ Monitoring and large-scale data processing: Track and troubleshoot code execution. When working with large datasets, you can easily reference files stored in Amazon S3, enabling efficient processing of gigabyte-scale data without API limitations.
+ Ease of use: Use a fully managed default mode with pre-built execution runtimes that support popular programming languages with common libraries pre-installed.
+ Extends problem-solving capabilities: Allows agents to solve computational problems that are difficult to address through reasoning alone and enables precise mathematical calculations and data processing at scale.
+ Long execution duration support: The Code Interpreter tool provides support for a default execution time of 15 minutes, which can be extended for up to eight hours.
+ Handles structured data: Processes CSV, Excel, JSON, and other data formats, and performs data cleaning, and analysis.
+ Enables complex workflows: Allows multi-step problem solving that combines reasoning with computation and facilitates iterative development and debugging.

The AgentCore Code Interpreter makes agents more powerful by complementing their reasoning abilities with computational execution, allowing them to tackle a much wider range of tasks effectively.

## Best practices
<a name="code-interpreter-best-practices"></a>

To get the most out of the AgentCore Code Interpreter:
+ Keep code snippets concise and focused on specific tasks
+ Use comments to document your code
+ Optimize code for performance when working with large datasets
+ Save intermediate results when performing complex operations
+ Use the `code_session` context manager to ensure proper cleanup
+ Include try/except blocks in code to handle errors gracefully
+ Code execution results are returned and processed as streams
+ Clean up temporary files when no longer needed
+ Close sessions when you’re done to release resources

# Pre-installed libraries
<a name="code-interpreter-preinstalled-libraries"></a>

The AgentCore Code Interpreter comes with pre-installed libraries for both Python and Node.js. These libraries are available immediately without requiring additional installation.

## Python libraries
<a name="code-interpreter-python-libraries"></a>

The AgentCore Code Interpreter includes a comprehensive set of pre-installed Python libraries to support various data analysis, machine learning, and development tasks.

### Data Analysis and Visualization
<a name="code-interpreter-data-analysis-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `pandas`   |  Data manipulation and analysis  | 
|   `numpy`   |  Numerical computing  | 
|   `matplotlib`   |  Plotting and visualization  | 
|   `matplotlib-inline`   |  Matplotlib backend for Jupyter  | 
|   `matplotlib-venn`   |  Venn diagram plotting  | 
|   `plotly`   |  Interactive visualizations  | 
|   `bokeh`   |  Interactive visualization library  | 
|   `scipy`   |  Scientific computing  | 
|   `statsmodels`   |  Statistical modeling  | 
|   `sympy`   |  Symbolic mathematics  | 
|   `numba`   |  Just-in-time compilation for numerical functions  | 
|   `pyarrow`   |  Columnar data processing  | 
|   `numexpr`   |  Fast numerical expression evaluator  | 
|   `mizani`   |  Scales for Python graphics  | 
|   `contourpy`   |  Contour line generation  | 
|   `cycler`   |  Composable style cycles  | 
|   `fonttools`   |  Font manipulation library  | 
|   `kiwisolver`   |  Constraint solver  | 
|   `pyparsing`   |  Parsing library  | 
|   `python-dateutil`   |  Date/time utilities  | 
|   `pytz`   |  Timezone definitions  | 
|   `tzdata`   |  Timezone data  | 
|   `patsy`   |  Statistical model specification  | 
|   `threadpoolctl`   |  Thread pool control  | 
|   `joblib`   |  Parallel computing utilities  | 
|   `mpmath`   |  Arbitrary-precision arithmetic  | 
|   `llvmlite`   |  LLVM binding for Numba  | 

### Machine Learning and AI
<a name="code-interpreter-ml-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `scikit-learn`   |  Machine learning algorithms  | 
|   `scikit-image`   |  Image processing  | 
|   `torch`   |  PyTorch deep learning framework  | 
|   `torchvision`   |  Computer vision for PyTorch  | 
|   `torchaudio`   |  Audio processing for PyTorch  | 
|   `xgboost`   |  Gradient boosting framework  | 
|   `openai`   |  OpenAI API client  | 
|   `spacy`   |  Natural language processing  | 
|   `spacy-legacy`   |  Legacy components for spaCy  | 
|   `spacy-loggers`   |  Logging utilities for spaCy  | 
|   `nltk`   |  Natural language toolkit  | 
|   `textblob`   |  Text processing  | 
|   `catalogue`   |  Tiny library for function registries  | 
|   `confection`   |  Configuration system  | 
|   `cymem`   |  Memory management for Cython  | 
|   `murmurhash`   |  Cython bindings for MurmurHash  | 
|   `preshed`   |  Cython hash tables  | 
|   `srsly`   |  Serialization utilities  | 
|   `thinc`   |  Machine learning library  | 
|   `wasabi`   |  Lightweight console printing  | 
|   `weasel`   |  Command-line interface for spaCy projects  | 
|   `blis`   |  BLAS-like linear algebra library  | 
|   `langcodes`   |  Language code utilities  | 
|   `language_data`   |  Language data for langcodes  | 
|   `marisa-trie`   |  Trie data structure  | 
|   `absl-py`   |  Abseil Python common libraries  | 
|   `mcp`   |  Model Context Protocol  | 

### Mathematical and Optimization
<a name="code-interpreter-mathematical-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `cvxpy`   |  Convex optimization  | 
|   `ortools`   |  Operations research tools  | 
|   `pulp`   |  Linear programming  | 
|   `galois`   |  Galois field arithmetic  | 
|   `z3-solver`   |  Theorem prover  | 
|   `python_constraint2`   |  Constraint satisfaction problems  | 
|   `gapstatistics`   |  Gap statistic for clustering  | 
|   `oeis`   |  Online Encyclopedia of Integer Sequences  | 
|   `networkx`   |  Network analysis  | 
|   `igraph`   |  Graph analysis and visualization  | 

### Web and API Development
<a name="code-interpreter-web-data-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `requests`   |  HTTP library  | 
|   `beautifulsoup4`   |  Web scraping  | 
|   `fastapi`   |  Modern web framework  | 
|   `Flask`   |  Lightweight web framework  | 
|   `Flask-Cors`   |  Cross-origin resource sharing for Flask  | 
|   `Flask-Login`   |  User session management for Flask  | 
|   `Django`   |  Full-featured web framework  | 
|   `httpx`   |  Async HTTP client  | 
|   `httpcore`   |  HTTP core library  | 
|   `starlette`   |  ASGI framework  | 
|   `uvicorn`   |  ASGI server  | 
|   `gunicorn`   |  WSGI HTTP server  | 
|   `Hypercorn`   |  ASGI server  | 
|   `asgiref`   |  ASGI reference implementation  | 
|   `Werkzeug`   |  WSGI utility library  | 
|   `Jinja2`   |  Template engine  | 
|   `MarkupSafe`   |  Safe string handling  | 
|   `itsdangerous`   |  Cryptographic signing  | 
|   `blinker`   |  Signal/event dispatching  | 
|   `click-plugins`   |  Click plugin system  | 
|   `tornado`   |  Web framework and async networking  | 
|   `sqlparse`   |  SQL parser  | 
|   `greenlet`   |  Lightweight coroutines  | 
|   `aiosignal`   |  Async signal dispatching  | 
|   `anyio`   |  Async compatibility layer  | 
|   `certifi`   |  Certificate bundle  | 
|   `dnspython`   |  DNS toolkit  | 
|   `email_validator`   |  Email validation  | 
|   `frozenlist`   |  Immutable list implementation  | 
|   `h11`   |  HTTP/1.1 protocol implementation  | 
|   `h2`   |  HTTP/2 protocol implementation  | 
|   `hpack`   |  HTTP/2 header compression  | 
|   `httptools`   |  Fast HTTP parsing  | 
|   `hyperframe`   |  HTTP/2 framing layer  | 
|   `idna`   |  Internationalized domain names  | 
|   `multidict`   |  Multi-value dictionary  | 
|   `priority`   |  HTTP/2 priority tree  | 
|   `python-dotenv`   |  Environment variable management  | 
|   `python-multipart`   |  Multipart form data parser  | 
|   `shellingham`   |  Shell detection library  | 
|   `sniffio`   |  Async library detection  | 
|   `sse-starlette`   |  Server-sent events for Starlette  | 
|   `urllib3`   |  HTTP client library  | 
|   `uvloop`   |  Fast event loop for asyncio  | 
|   `watchfiles`   |  File watching library  | 
|   `wsproto`   |  WebSocket protocol implementation  | 
|   `yarl`   |  URL parsing library  | 

### Cloud and Database
<a name="code-interpreter-cloud-database-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `boto3`   |   AWS SDK for Python (boto3)  | 
|   `duckdb`   |  In-process SQL database  | 
|   `SQLAlchemy`   |  SQL toolkit and ORM  | 
|   `pymongo`   |  MongoDB driver  | 
|   `redis`   |  Redis client  | 
|   `psycopg2-binary`   |  PostgreSQL adapter  | 

### File Processing and Documents
<a name="code-interpreter-file-processing-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `openpyxl`   |  Excel file processing  | 
|   `xlrd`   |  Excel file reading  | 
|   `XlsxWriter`   |  Excel file writing  | 
|   `pyxlsb`   |  Excel binary format reader  | 
|   `et-xmlfile`   |  XML file handling for openpyxl  | 
|   `PyPDF2`   |  PDF processing  | 
|   `pdfplumber`   |  PDF text extraction  | 
|   `pdf2image`   |  PDF to image conversion  | 
|   `pdfkit`   |  HTML to PDF conversion  | 
|   `pypdfium2`   |  PDF processing library  | 
|   `pdfminer.six`   |  PDF text extraction  | 
|   `pdfrw`   |  PDF reader/writer  | 
|   `python-docx`   |  Word document processing  | 
|   `docx2txt`   |  Word document text extraction  | 
|   `reportlab`   |  PDF generation  | 
|   `fpdf`   |  Simple PDF generation  | 
|   `rarfile`   |  RAR archive processing  | 
|   `xml-python`   |  XML processing  | 
|   `svglib`   |  SVG to PDF/bitmap conversion  | 
|   `svgwrite`   |  SVG creation library  | 
|   `proglog`   |  Progress logging  | 
|   `lazy_loader`   |  Lazy module loading  | 

### Image and Media Processing
<a name="code-interpreter-media-processing-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `pillow`   |  Image processing  | 
|   `opencv-python`   |  Computer vision  | 
|   `imageio`   |  Image I/O  | 
|   `imageio-ffmpeg`   |  FFmpeg plugin for imageio  | 
|   `moviepy`   |  Video editing  | 
|   `ffmpeg-python`   |  FFmpeg wrapper  | 
|   `ffmpy`   |  FFmpeg wrapper  | 
|   `pydub`   |  Audio manipulation  | 
|   `gtts`   |  Google Text-to-Speech  | 
|   `mutagen`   |  Audio metadata handling  | 
|   `Wand`   |  ImageMagick binding  | 
|   `imgkit`   |  HTML to image conversion  | 
|   `pypng`   |  PNG image processing  | 
|   `PyWavelets`   |  Wavelet transforms  | 
|   `tifffile`   |  TIFF file processing  | 

### Development Tools and Utilities
<a name="code-interpreter-utility-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `pydantic`   |  Data validation using type hints  | 
|   `pydantic-settings`   |  Settings management for Pydantic  | 
|   `pydantic_core`   |  Core validation logic for Pydantic  | 
|   `jsonschema`   |  JSON schema validation  | 
|   `PyYAML`   |  YAML processing  | 
|   `orjson`   |  Fast JSON library  | 
|   `ujson`   |  Ultra fast JSON encoder/decoder  | 
|   `click`   |  Command line interface creation  | 
|   `typer`   |  Modern CLI framework  | 
|   `tqdm`   |  Progress bars  | 
|   `loguru`   |  Logging library  | 
|   `rich`   |  Rich text and beautiful formatting  | 
|   `ipython`   |  Interactive Python shell  | 
|   `Faker`   |  Fake data generation  | 
|   `qrcode`   |  QR code generation  | 
|   `retrying`   |  Retry decorator  | 
|   `tenacity`   |  Retry library  | 
|   `backoff`   |  Backoff and retry  | 
|   `more_itertools`   |  Additional iterator tools  | 
|   `cryptography`   |  Cryptographic recipes and primitives  | 
|   `bcrypt`   |  Password hashing  | 
|   `PyNaCl`   |  Networking and Cryptography library  | 
|   `pyOpenSSL`   |  OpenSSL wrapper  | 
|   `cffi`   |  C Foreign Function Interface  | 
|   `pycparser`   |  C parser in Python  | 
|   `annotated-types`   |  Reusable constraint types  | 
|   `typing_extensions`   |  Backported typing features  | 
|   `typing_inspection`   |  Runtime inspection of typing  | 
|   `astor`   |  AST to source code converter  | 
|   `asttokens`   |  Annotate AST with source tokens  | 
|   `executing`   |  Get currently executing AST node  | 
|   `pure-eval`   |  Safe evaluation of expressions  | 
|   `stack-data`   |  Extract data from stack frames  | 
|   `decorator`   |  Decorator utilities  | 
|   `entrypoints`   |  Discover entry points  | 
|   `jedi`   |  Code completion library  | 
|   `parso`   |  Python parser  | 
|   `prompt_toolkit`   |  Interactive command line toolkit  | 
|   `traitlets`   |  Configuration system  | 
|   `wcwidth`   |  Terminal width calculation  | 
|   `Pygments`   |  Syntax highlighting  | 
|   `mdurl`   |  URL utilities for Markdown  | 
|   `texttable`   |  Text table formatting  | 
|   `xyzservices`   |  Source of XYZ tile services  | 
|   `attrs`   |  Classes without boilerplate  | 
|   `cachetools`   |  Extensible memoizing collections  | 
|   `cloudpathlib`   |  Cloud storage path library  | 
|   `cloudpickle`   |  Pickle for cloud computing  | 
|   `distro`   |  Linux distribution information  | 
|   `filelock`   |  Platform independent file locking  | 
|   `fsspec`   |  Filesystem specification  | 
|   `future`   |  Python 2/3 compatibility  | 
|   `httpx-sse`   |  Server-sent events for HTTPX  | 
|   `importlib_metadata`   |  Library metadata access  | 
|   `importlib_resources`   |  Resource access for packages  | 
|   `jsonschema-specifications`   |  JSON Schema specifications  | 
|   `packaging`   |  Core utilities for Python packages  | 
|   `pexpect`   |  Expect-like subprocess control  | 
|   `platformdirs`   |  Platform-specific directories  | 
|   `ptyprocess`   |  Pseudoterminal utilities  | 
|   `referencing`   |  JSON reference resolution  | 
|   `rpds-py`   |  Persistent data structures  | 
|   `six`   |  Python 2/3 compatibility utilities  | 
|   `smart-open`   |  Utils for streaming large files  | 
|   `zipp`   |  Backport of pathlib-compatible object wrapper  | 

### Text and Markup Processing
<a name="code-interpreter-text-processing-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `markdown-it-py`   |  Markdown parser  | 
|   `markdown2`   |  Markdown processor  | 
|   `markdownify`   |  HTML to Markdown converter  | 
|   `lxml`   |  XML and HTML processing  | 
|   `cssselect2`   |  CSS selector implementation  | 
|   `tinycss2`   |  CSS parser  | 
|   `webencodings`   |  Character encoding for web  | 
|   `soupsieve`   |  CSS selector library  | 
|   `regex`   |  Alternative regular expression module  | 
|   `chardet`   |  Character encoding detection  | 
|   `charset-normalizer`   |  Character encoding detection  | 

### Geospatial and Mapping
<a name="code-interpreter-geospatial-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `shapely`   |  Geometric objects manipulation  | 
|   `pyshp`   |  Shapefile library  | 
|   `branca`   |  HTML/JS template library for maps  | 

### Document Processing Support
<a name="code-interpreter-document-processing-libraries"></a>


| Library | Description | 
| --- | --- | 
|   `python-pptx`   |  Create and update PowerPoint (.pptx) files  | 
|   `defusedxml`   |  XML bomb protection for Python stdlib modules  | 
|   `markitdown`   |  Convert various file formats to Markdown  | 
|   `xlwt`   |  Write data and formatting information to Excel files  | 
|   `odfpy`   |  API for OpenDocument Format documents  | 
|   `docx-mailmerge`   |  Mail merge for Word documents  | 
|   `docxcompose`   |  Compose Word documents by concatenating/appending  | 
|   `html5lib`   |  Standards-compliant library for parsing and serializing HTML  | 
|   `xmltodict`   |  Convert XML to Python dictionaries  | 
|   `tabula-py`   |  Extract tables from PDF files  | 
|   `pypandoc`   |  Python wrapper for Pandoc document converter  | 
|   `pypdf`   |  Pure Python PDF library for splitting, merging, cropping  | 

For a complete list of all pre-installed Python libraries with their specific versions, you can run the following code in your Code Interpreter session:

```
import pkg_resources
installed_packages = [d for d in pkg_resources.working_set]
for package in sorted(installed_packages, key=lambda x: x.project_name.lower()):
    print(f"{package.project_name}=={package.version}")
```

## Node.js packages/libraries
<a name="code-interpreter-nodejs-libraries"></a>

The following Node.js packages/libraries are pre-installed in the AgentCore Code Interpreter environment.


| Package/Library | Description | 
| --- | --- | 
|   `axios`   |  Promise-based HTTP client  | 
|   `lodash`   |  Utility library for common programming tasks  | 
|   `uuid`   |  UUID generation  | 
|   `zod`   |  TypeScript-first schema validation  | 
|   `cheerio`   |  HTML parsing and manipulation  | 

# 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.

# Run code in Code Interpreter from Agents
<a name="code-interpreter-building-agents"></a>

You can build agents that use the Code Interpreter tool to execute code and analyze data. This section demonstrates how to build agents using different frameworks.

**Example**  

1. You can build an agent that uses the Code Interpreter tool using the Strands framework:

    **Install dependencies** 

   Run the following commands to install the required packages:

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

    **Write an agent with Code Interpreter tool** 

   The following Python code shows how to write an agent using Strands with the Code Interpreter tool:

   ```
   # strands_ci_agent.py
   
   import json
   from strands import Agent, tool
   from bedrock_agentcore.tools.code_interpreter_client import code_session
   import asyncio
   
   #Define the detailed system prompt for the assistant
   SYSTEM_PROMPT = """You are a helpful AI assistant that validates all answers through code execution.
   
   VALIDATION PRINCIPLES:
   1. When making claims about code, algorithms, or calculations - write code to verify them
   2. Use execute_python to test mathematical calculations, algorithms, and logic
   3. Create test scripts to validate your understanding before giving answers
   4. Always show your work with actual code execution
   5. If uncertain, explicitly state limitations and validate what you can
   
   APPROACH:
   - If asked about a programming concept, implement it in code to demonstrate
   - If asked for calculations, compute them programmatically AND show the code
   - If implementing algorithms, include test cases to prove correctness
   - Document your validation process for transparency
   - The state is maintained between executions, so you can refer to previous results
   
   TOOL AVAILABLE:
   - execute_python: Run Python code and see output
   
   RESPONSE FORMAT: The execute_python tool returns a JSON response with:
   - sessionId: The code interpreter session ID
   - id: Request ID
   - isError: Boolean indicating if there was an error
   - content: Array of content objects with type and text/data
   - structuredContent: For code execution, includes stdout, stderr, exitCode, executionTime
   
   For successful code execution, the output will be in content[0].text and also in structuredContent.stdout.
   Check isError field to see if there was an error.
   
   Be thorough, accurate, and always validate your answers when possible."""
   
   #Define and configure the code interpreter tool
   @tool
   def execute_python(code: str, description: str = "") -> str:
       """Execute Python code"""
   
       if description:
           code = f"# {description}\n{code}"
   
       #Print code to be executed
       print(f"\n Code: {code}")
   
   
       # Call the Invoke method and execute the generated code, within the initialized code interpreter session
       with code_session("<Region>") as code_client:
           response = code_client.invoke("executeCode", {
           "code": code,
           "language": "python",
           "clearContext": False
       })
   
       for event in response["stream"]:
           return json.dumps(event["result"])
   
   #configure the strands agent including the tool(s)
   agent=Agent(
           tools=[execute_python],
           system_prompt=SYSTEM_PROMPT,
           callback_handler=None)
   
   query="Can all the planets in the solar system fit between the earth and moon?"
   
   # Invoke the agent asynchcronously and stream the response
   async def main():
       response_text = ""
       async for event in agent.stream_async(query):
           if "data" in event:
               # Stream text response
               chunk = event["data"]
               response_text += chunk
               print(chunk, end="")
   
   asyncio.run(main())
   ```

1. You can build an agent that uses the Code Interpreter tool using the LangChain framework:

    **Install dependencies** 

   Run the following commands to install the required packages:

   ```
   pip install langchain
   pip install langchain_aws
   pip install bedrock-agentcore
   ```

    **Write an agent with Code Interpreter tool** 

   The following Python code shows how to write an agent using LangChain with the Code Interpreter tool:

   ```
   # langchain_ci_agent.py
   
   #Please ensure that the latest Bedrock-AgentCore and Boto SDKs are installed
   #Import Bedrock-AgentCore and other libraries
   
   import json
   from bedrock_agentcore.tools.code_interpreter_client import code_session
   from langchain.agents import AgentExecutor, create_tool_calling_agent, initialize_agent, tool
   from langchain_aws import ChatBedrockConverse
   from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
   
   #Define and configure the code interpreter tool
   @tool
   def execute_python(code: str, description: str = "") -> str:
       """Execute Python code"""
   
       if description:
           code = f"# {description}\n{code}"
   
       #Print the code to be executed
       print(f"\nGenerated Code: \n{code}")
   
   
   # Call the Invoke method and execute the generated code, within the initialized code interpreter session
       with code_session("<Region>") as code_client:
           response = code_client.invoke("executeCode", {
           "code": code,
           "language": "python",
           "clearContext": False
       })
       for event in response["stream"]:
           return json.dumps(event["result"])
   
   # Initialize the language model
   # Please ensure access to anthropic.claude-3-5-sonnet model in Amazon Bedrock
   llm = ChatBedrockConverse(
               model_id="anthropic.claude-3-5-sonnet-20240620-v1:0",
               region_name="<Region>"
           )
   
   #Define the detailed system prompt for the assistant
   SYSTEM_PROMPT = """You are a helpful AI assistant that validates all answers through code execution.
   
   VALIDATION PRINCIPLES:
   1. When making claims about code, algorithms, or calculations - write code to verify them
   2. Use execute_python to test mathematical calculations, algorithms, and logic
   3. Create test scripts to validate your understanding before giving answers
   4. Always show your work with actual code execution
   5. If uncertain, explicitly state limitations and validate what you can
   
   APPROACH:
   - If asked about a programming concept, implement it in code to demonstrate
   - If asked for calculations, compute them programmatically AND show the code
   - If implementing algorithms, include test cases to prove correctness
   - Document your validation process for transparency
   - The code interpreter maintains state between executions, so you can refer to previous results
   
   TOOL AVAILABLE:
   - execute_python: Run Python code and see output
   
   RESPONSE FORMAT: The execute_python tool returns a JSON response with:
   - sessionId: The code interpreter session ID
   - id: Request ID
   - isError: Boolean indicating if there was an error
   - content: Array of content objects with type and text/data
   - structuredContent: For code execution, includes stdout, stderr, exitCode, executionTime
   
   For successful code execution, the output will be in content[0].text and also in structuredContent.stdout.
   Check isError field to see if there was an error.
   
   Be thorough, accurate, and always validate your answers when possible."""
   
   # Create a list of our custom tools
   tools = [execute_python]
   
   # Define the prompt template
   prompt = ChatPromptTemplate.from_messages([
       ("system", SYSTEM_PROMPT),
       ("user", "{input}"),
       MessagesPlaceholder(variable_name="agent_scratchpad"),
   ])
   
   # Create the agent
   agent = create_tool_calling_agent(llm, tools, prompt)
   # Create the agent executor
   agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
   
   query="Can all the planets in the solar system fit between the earth and moon?"
   resp=agent_executor.invoke({"input": query})
   
   #print the result
   print(resp['output'][0]['text'])
   ```

# Write files to a session
<a name="code-interpreter-file-operations"></a>

You can use the Code Interpreter to read and write files in the sandbox environment. This allows you to upload data files, process them with code, and retrieve the results.

 **Install dependencies** 

Run the following command to install the required package:

```
pip install bedrock-agentcore
```

 **Upload Code and Data using the file tool** 

The following Python code shows how to upload files to the Code Interpreter session and execute code that processes those files. The files that are required are `data.csv` and `stats.py` that are available [in this package](samples/read_write_files.zip).

```
# file_mgmt_ci_agent.py

from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
import json
from typing import Dict, Any, List

#Configure and Start the code interpreter session
code_client = CodeInterpreter('<Region>')
code_client.start()

#read the content of the sample data file
data_file = "data.csv"

try:
    with open(data_file, 'r', encoding='utf-8') as data_file_content:
        data_file_content = data_file_content.read()
    #print(data_file_content)
except FileNotFoundError:
    print(f"Error: The file '{data_file}' was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

#read the content of the python script to analyze the sample file
code_file = "stats.py"
try:
    with open(code_file, 'r', encoding='utf-8') as code_file_content:
        code_file_content = code_file_content.read()
    #print(code_file_content)
except FileNotFoundError:
    print(f"Error: The file '{code_file}' was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

files_to_create = [
                {
                    "path": "data.csv",
                    "text": data_file_content
                },
                {
                    "path": "stats.py",
                    "text": code_file_content
                }]

#define the method to call the invoke API
def call_tool(tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:

    response = code_client.invoke(tool_name, arguments)
    for event in response["stream"]:
        return json.dumps(event["result"], indent=2)

#write the sample data and analysis script into the code interpreter session
writing_files = call_tool("writeFiles", {"content": files_to_create})
print(f"writing files: {writing_files}")

#List and validate that the files were written successfully
listing_files = call_tool("listFiles", {"path": ""})
print(f"listing files: {listing_files}")

#Run the python script to analyze the sample data file
execute_code = call_tool("executeCode", {
                "code": files_to_create[1]['text'],
                "language": "python",
                "clearContext": True})
print(f"code execution result: {execute_code}")

#Clean up and stop the code interpreter session
code_client.stop()
```

# Using Terminal Commands with an execution role
<a name="code-interpreter-s3-integration"></a>

You can create a custom Code Interpreter tool with an execution role to upload/download files from Amazon S3. This allows your code to interact with S3 buckets for storing and retrieving data.

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

Before creating a custom Code Interpreter with S3 access, you need to:

1. Create an S3 bucket (e.g., `DOC-EXAMPLE-BUCKET` )

1. Create a folder within the bucket (e.g., `output_artifacts` )

1. Create an IAM role with the following trust policy:

   ```
   {
   "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "bedrock-agentcore.amazonaws.com"
         },
         "Action": "sts:AssumeRole",
         "Condition": {
           "StringEquals": {
             "aws:SourceAccount": "111122223333"
           }
         }
       }
     ]
   }
   ```

1. Add the following permissions to the role:

   ```
   {
   "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "VisualEditor0",
         "Effect": "Allow",
         "Action": [
           "s3:PutObject",
           "s3:GetObject"
         ],
         "Resource": "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*",
         "Condition": {
             "StringEquals": {
                 "s3:ResourceAccount": "${aws:PrincipalAccount}"
             }
         }
       }
     ]
   }
   ```

## Sample Python code
<a name="code-interpreter-s3-code"></a>

You can implement S3 integration using boto3 (AWS SDK for Python). The following example uses boto3 to create a custom Code Interpreter with an execution role that can upload files to or download files from Amazon S3.

**Note**  
Before running this code, make sure to replace `REGION` and `<awsaccountid>` with your AWS Region and AWS account number.

```
import boto3
import json
import time

REGION = "<Region>"
CP_ENDPOINT_URL = f"https://bedrock-agentcore-control.{REGION}.amazonaws.com"
DP_ENDPOINT_URL = f"https://bedrock-agentcore.{REGION}.amazonaws.com"

# Update the accountId to reflect the correct S3 path.
S3_BUCKET_NAME = "DOC-EXAMPLE-BUCKET"

bedrock_agentcore_control_client = boto3.client(
    'bedrock-agentcore-control',
    region_name=REGION,
    endpoint_url=CP_ENDPOINT_URL
)
bedrock_agentcore_client = boto3.client(
    'bedrock-agentcore',
    region_name=REGION,
    endpoint_url=DP_ENDPOINT_URL
)

unique_name = f"s3InteractionEnv_{int(time.time())}"
create_response = bedrock_agentcore_control_client.create_code_interpreter(
    name=unique_name,
    description="Combined test code sandbox",
    executionRoleArn="arn:aws:iam::123456789012:role/S3InteractionRole",
    networkConfiguration={
        "networkMode": "SANDBOX"
    }
)
code_interpreter_id = create_response['codeInterpreterId']
print(f"Created custom interpreter ID: {code_interpreter_id}")

session_response = bedrock_agentcore_client.start_code_interpreter_session(
    codeInterpreterIdentifier=code_interpreter_id,
    name="combined-test-session",
    sessionTimeoutSeconds=1800
)
session_id = session_response['sessionId']
print(f"Created session ID: {session_id}")

print(f"Downloading CSV generation script from S3")
command_to_execute = f"aws s3 cp s3://{S3_BUCKET_NAME}/generate_csv.py ."
response = bedrock_agentcore_client.invoke_code_interpreter(
    codeInterpreterIdentifier=code_interpreter_id,
    sessionId=session_id,
    name="executeCommand",
    arguments={
        "command": command_to_execute
    }
)

for event in response["stream"]:
    print(json.dumps(event["result"], default=str, indent=2))

print(f"Executing the CSV generation script")
response = bedrock_agentcore_client.invoke_code_interpreter(
    codeInterpreterIdentifier=code_interpreter_id,
    sessionId=session_id,
    name="executeCommand",
    arguments={
        "command": "python generate_csv.py 5 10"
    }
)

for event in response["stream"]:
    print(json.dumps(event["result"], default=str, indent=2))

print(f"Uploading generated artifact to S3")
command_to_execute = f"aws s3 cp generated_data.csv s3://{S3_BUCKET_NAME}/output_artifacts/"
response = bedrock_agentcore_client.invoke_code_interpreter(
    codeInterpreterIdentifier=code_interpreter_id,
    sessionId=session_id,
    name="executeCommand",
    arguments={
        "command": command_to_execute
    }
)

for event in response["stream"]:
    print(json.dumps(event["result"], default=str, indent=2))

print(f"Stopping the code interpreter session")
stop_response = bedrock_agentcore_client.stop_code_interpreter_session(
    codeInterpreterIdentifier=code_interpreter_id,
    sessionId=session_id
)

print(f"Deleting the code interpreter")
delete_response = bedrock_agentcore_control_client.delete_code_interpreter(
    codeInterpreterId=code_interpreter_id
)
print(f"Code interpreter status from response: {delete_response['status']}")
print(f"Clean up completed, script run successful")
```

This example shows you how to:
+ Create a custom Code Interpreter with an execution role
+ Configure network access - Choose PUBLIC mode if your Code Interpreter needs to connect to the public internet. If your Code Interpreter supports connection to Amazon S3, and needs limited access to the public internet, choose SANDBOX mode.
+ Upload and download files between the Code Interpreter environment and S3
+ Execute commands and scripts within the Code Interpreter environment
+ Clean up resources when finished

# 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>
   ```

# Code Interpreter API Reference Examples
<a name="code-interpreter-api-reference-examples"></a>

This section provides reference examples for common Code Interpreter operations using different approaches. Each example shows how to perform the same operation using AWS CLI, Boto3 SDK, and direct API calls.

## Code Execution
<a name="code-interpreter-api-code-execution"></a>

These examples demonstrate how to execute code in a Code Interpreter session.

**Example**  

1. 

   ```
   params = {
         "language": "python",
         "code": "print(\"Hello, world!\")"
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "executeCode",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "executeCode",
       "arguments": {
         "language": "python",
         "code": "print(\"Hello, world!\")"
       }
     }'
   ```

## Terminal Commands
<a name="code-interpreter-api-terminal-commands"></a>

These examples demonstrate how to execute terminal commands in a Code Interpreter session.

### Execute Command
<a name="code-interpreter-api-execute-command"></a>

**Example**  

1. 

   ```
   params = {
         "command": "ls -l"
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "executeCommand",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "executeCommand",
       "arguments": {
         "command": "ls -l"
       }
     }'
   ```

### Start Command Execution
<a name="code-interpreter-api-start-command"></a>

**Example**  

1. 

   ```
   params = {
         "command": "sleep 15 && echo Task completed successfully"
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "startCommandExecution",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "startCommandExecution",
       "arguments": {
         "command": "sleep 15 && echo Task completed successfully"
       }
     }'
   ```

### Get Task
<a name="code-interpreter-api-get-task"></a>

**Example**  

1. 

   ```
   params = {
         "taskId": "<your-task-id>"
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "getTask",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "getTask",
       "arguments": {
         "taskId": "<your-task-id>"
       }
     }'
   ```

### Stop Command Execution Task
<a name="code-interpreter-api-stop-task"></a>

**Example**  

1. 

   ```
   params = {
         "taskId": "<your-task-id>"
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "stopTask",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "stopTask",
       "arguments": {
         "taskId": "<your-task-id>"
       }
     }'
   ```

## File Management
<a name="code-interpreter-api-file-management"></a>

These examples demonstrate how to manage files in a Code Interpreter session.

### Write Files
<a name="code-interpreter-api-write-files"></a>

**Example**  

1. 

   ```
   params = {
           "content": [{"path": "dir1/samename.txt", "text": "File in dir1"}]
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "writeFiles",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "writeFiles",
       "arguments": {
         "content": [{"path": "dir1/samename.txt", "text": "File in dir1"}]
       }
     }'
   ```

### Read Files
<a name="code-interpreter-api-read-files"></a>

**Example**  

1. 

   ```
   params = {
         "paths": ["tmp.txt"]
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "readFiles",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "readFiles",
       "arguments": {
         "paths": ["tmp.txt"]
       }
     }'
   ```

### Remove Files
<a name="code-interpreter-api-remove-files"></a>

**Example**  

1. 

   ```
   params = {
         "paths": ["tmp.txt"]
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "removeFiles",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "removeFiles",
       "arguments": {
         "paths": ["tmp.txt"]
       }
     }'
   ```

### List Files
<a name="code-interpreter-api-list-files"></a>

**Example**  

1. 

   ```
   params = {
         "directoryPath": ""
       }
   
   client.invoke_code_interpreter(
       **{
           "codeInterpreterIdentifier": "aws.codeinterpreter.v1",
           "sessionId": "<your-session-id>",
           "name": "listFiles",
           "arguments": params
       })
   ```

1. 

   ```
   # 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 '{
       "name": "listFiles",
       "arguments": {
         "directoryPath": ""
       }
     }'
   ```

# Observability
<a name="code-interpreter-observability"></a>

The AgentCore Code Interpreter provides the following observability features:

Execution logs  
Code interpreter execution console logs are not available in CloudWatch, but stdout/stderr details are directly available in each invocation.

Metrics  
You can view the following metrics in Amazon CloudWatch:  
+ Session counts: The number of sessions that Code Interpreter session has been requested
+ Duration: The duration of sessions that Code Interpreter is running
+ Invocations: The total number of times for each tool has been invoked
+ Request latency: The latency of each request
+ Throttles: The number of times requests to the tool have been throttled due to exceeding limits, with percentage change compared to the previous week
+ User errors/system errors: The number of times requests failed due to either user error or system error

These metrics can be used to monitor the usage and performance of your code interpreter sessions, set up alarms for abnormal behavior, and optimize your resource allocation.

For more information, see [AgentCore generated built-in tools observability data](observability-tool-metrics.md).

# Configure Root Certificate Authority for Amazon Bedrock AgentCore Code Interpreter
<a name="code-interpreter-root-ca-certificates"></a>

By default, Amazon Bedrock AgentCore Code Interpreter sessions trust only publicly recognized certificate authorities. If your agents need to access internal services or resources behind a TLS-intercepting proxy that use certificates signed by a private CA, you must provide your custom root CA certificates when starting a session.

Amazon Bedrock AgentCore retrieves the PEM-encoded certificate content from AWS Secrets Manager using your caller credentials, validates the X.509 format and expiry, and installs the certificates into the session’s OS trust store. This enables the code interpreter to establish trusted HTTPS connections to your internal resources.

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

Root Certificate Authority for Amazon Bedrock AgentCore Code Interpreter works as follows:

1. You provide a list of certificate locations, each pointing to a secret in AWS Secrets Manager that contains a PEM-encoded root CA certificate.

1. Amazon Bedrock AgentCore uses your caller credentials to retrieve each certificate from AWS Secrets Manager.

1. Each certificate is validated for correct X.509 PEM format and checked to ensure it has not expired and is not used before its validity start date.

1. Valid certificates are deployed to the session’s OS trust store, making them available to code execution runtimes and any network clients within the sandbox.

Certificates configured at the tool level (through `CreateCodeInterpreter` ) are combined with any certificates provided at session start time. This allows you to set organization-wide certificates on the tool and add session-specific certificates as needed.

**Note**  
Certificate configuration is a one-time operation per session. Once certificates are installed, they cannot be modified for the duration of that session.

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

Before configuring root CA certificates, ensure you have the following:
+ Completed the general [Prerequisites](code-interpreter-getting-started.md#code-interpreter-prerequisites).
+ Your root CA certificates stored as secrets in AWS Secrets Manager. Each secret must contain valid PEM-encoded X.509 certificate
+ IAM permissions to read the certificate secrets from AWS Secrets Manager. Add the following permissions to your IAM policy:

  ```
  {
  "Version": "2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "SecretsManagerCertificateAccess",
              "Effect": "Allow",
              "Action": [
                  "secretsmanager:GetSecretValue"
              ],
              "Resource": "arn:aws:secretsmanager:<Region>:<account-id>:secret:<secret-name>"
          }
      ]
  }
  ```

## Store your certificate in AWS Secrets Manager
<a name="code-interpreter-root-ca-store-certificate"></a>

Before you can use a root CA certificate with Amazon Bedrock AgentCore Code Interpreter, you must store it as a secret in AWS Secrets Manager. The secret value must be the PEM-encoded certificate content.

**Example**  

1. 

   ```
   aws secretsmanager create-secret \
     --name "my-corporate-root-ca" \
     --description "Corporate root CA certificate for AgentCore sessions" \
     --secret-string file://my-root-ca.pem \
     --region <region>
   ```

1. 

   ```
   import boto3
   
   client = boto3.client('secretsmanager', region_name='<region>')
   
   # Read the PEM certificate file
   with open('my-root-ca.pem', 'r') as f:
       cert_content = f.read()
   
   response = client.create_secret(
       Name='my-corporate-root-ca',
       Description='Corporate root CA certificate for AgentCore sessions',
       SecretString=cert_content
   )
   
   print(f"Secret ARN: {response['ARN']}")
   ```

Note the secret ARN from the output. You will use this ARN when starting sessions with certificate configuration.

**Important**  
The secret must contain a valid PEM-encoded X.509 certificate. The certificate must not be expired and must be within its validity period. Amazon Bedrock AgentCore validates the certificate format and expiry before installing it.

## Start a code interpreter session with custom certificates
<a name="code-interpreter-root-ca-session"></a>

To start a code interpreter session that trusts your custom root CA certificates, include the `certificates` parameter in your `StartCodeInterpreterSession` request.

**Example**  

1. 

   ```
   aws bedrock-agentcore start-code-interpreter-session \
     --code-interpreter-identifier "aws.codeinterpreter.v1" \
     --name "ci-session-with-custom-ca" \
     --certificates '[
       {
         "location": {
           "secretsManager": {
             "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:<secret-name>"
           }
         }
       }
     ]'
   ```

1. 

   ```
   import boto3
   
   client = boto3.client('bedrock-agentcore', region_name='<region>')
   
   response = client.start_code_interpreter_session(
       codeInterpreterIdentifier="aws.codeinterpreter.v1",
       name="ci-session-with-custom-ca",
       certificates=[
           {
               "location": {
                   "secretsManager": {
                       "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:<secret-name>"
                   }
               }
           }
       ]
   )
   
   print(f"Session ID: {response['sessionId']}")
   print(f"Status: {response['status']}")
   ```

1. 

   ```
   {
     "name": "ci-session-with-custom-ca",
     "certificates": [
       {
         "location": {
           "secretsManager": {
             "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:<secret-name>"
           }
         }
       }
     ]
   }
   ```

## Using multiple certificates
<a name="code-interpreter-root-ca-multiple-certificates"></a>

You can provide multiple root CA certificates in a single code interpreter session. This is useful when your environment requires trust for multiple internal certificate authorities, such as separate CAs for different internal services or environments.

**Example**  

1. 

   ```
   aws bedrock-agentcore start-code-interpreter-session \
     --code-interpreter-identifier "aws.codeinterpreter.v1" \
     --name "ci-session-with-multiple-cas" \
     --certificates '[
       {
         "location": {
           "secretsManager": {
             "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:corporate-root-ca"
           }
         }
       },
       {
         "location": {
           "secretsManager": {
             "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:proxy-ca"
           }
         }
       }
     ]'
   ```

1. 

   ```
   response = client.start_code_interpreter_session(
       codeInterpreterIdentifier="aws.codeinterpreter.v1",
       name="ci-session-with-multiple-cas",
       certificates=[
           {
               "location": {
                   "secretsManager": {
                       "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:corporate-root-ca"
                   }
               }
           },
           {
               "location": {
                   "secretsManager": {
                       "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:proxy-ca"
                   }
               }
           }
       ]
   )
   ```

## Configure certificates at the tool level
<a name="code-interpreter-root-ca-tool-level"></a>

You can configure certificates at the tool level when creating a custom code interpreter. Certificates configured at the tool level are automatically applied to every session started with that tool, in addition to any certificates provided at session start time.

This is useful for organization-wide certificates that should be trusted by all code interpreter sessions.

**Example**  

1. 

   ```
   response = client.create_code_interpreter(
       name="corporate-code-interpreter",
       description="Code interpreter with corporate CA trust",
       certificates=[
           {
               "location": {
                   "secretsManager": {
                       "secretArn": "arn:aws:secretsmanager:<region>:<account-id>:secret:corporate-root-ca"
                   }
               }
           }
       ]
   )
   
   ci_id = response['codeInterpreterIdentifier']
   print(f"Code Interpreter ID: {ci_id}")
   ```

When you start a session with a code interpreter that has certificates configured, the tool-level certificates are combined with any session-level certificates. Tool-level certificates are applied first, followed by session-level certificates.

## Certificate requirements and limits
<a name="code-interpreter-root-ca-certificate-requirements"></a>

Certificates must meet the following requirements:


| Requirement | Details | 
| --- | --- | 
|  Format  |  PEM-encoded X.509 certificate  | 
|  Storage  |   AWS Secrets Manager secret (as a string value, not binary)  | 
|  Validity  |  Certificate must not be expired and must be within its validity period (between `notBefore` and `notAfter` dates)  | 
|  Maximum certificates per session  |  10 per session and 10 per tool. A session can have up to 20 certificates in total.  | 
|  Secret ARN format  |   `arn:aws:secretsmanager:region:account-id:secret:secret-name`   | 
|  Location type  |  Only AWS Secrets Manager is supported as a certificate location  | 

## Troubleshooting
<a name="code-interpreter-root-ca-troubleshooting"></a>

The following table describes common errors and their resolutions when configuring root CA certificates for Amazon Bedrock AgentCore Code Interpreter.


| Error | Cause | Resolution | 
| --- | --- | --- | 
|  Certificate secret not found in Secrets Manager  |  The secret ARN does not exist or the secret has been deleted.  |  Verify the secret ARN is correct and the secret exists in the specified Region.  | 
|  Access denied to certificate secret in Secrets Manager  |  The caller does not have `secretsmanager:GetSecretValue` permission on the secret.  |  Add the `secretsmanager:GetSecretValue` permission to your IAM policy for the specified secret ARN.  | 
|  Certificate content is not valid PEM/X.509 format  |  The secret value is not a valid PEM-encoded X.509 certificate.  |  Ensure the secret contains a properly formatted PEM certificate starting with `-----BEGIN CERTIFICATE-----` and ending with `-----END CERTIFICATE-----`.  | 
|  Certificate has expired  |  The certificate’s `notAfter` date is in the past.  |  Replace the expired certificate with a valid one in AWS Secrets Manager and retry.  | 
|  Certificate is not yet valid  |  The certificate’s `notBefore` date is in the future.  |  Wait until the certificate’s validity period begins, or use a certificate that is currently valid.  | 
|  Number of certificates exceeds the maximum allowed  |  More than 10 certificates were provided at the session level or tool level.  |  Reduce the number of certificates to 10 or fewer per session and 10 or fewer per tool.  | 
|  Certificate location is required  |  A certificate entry was provided without a location.  |  Ensure each certificate in the array includes a `location` with a `secretsManager` entry containing a valid `secretArn`.  | 
|  Certificates configuration is not enabled  |  The certificates feature is not enabled for your account.  |  Contact AWS Support to enable the certificates feature for your account.  | 

# Troubleshoot AgentCore Code Interpreter
<a name="code-interpreter-troubleshooting"></a>

This section provides solutions to common issues you might encounter when using the Amazon Bedrock AgentCore Code Interpreter.

Common issues with AgentCore Code Interpreter typically relate to:
+ Code execution timeouts
+ Memory limitations during data processing
+ Package installation restrictions

For detailed information about AgentCore Code Interpreter capabilities and usage, see [Execute code and analyze data using Amazon Bedrock AgentCore Code Interpreter](code-interpreter-tool.md).