langchain-agentcore-codeinterpreter 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """Amazon Bedrock AgentCore Code Interpreter sandbox integration for Deep Agents."""
2
+
3
+ from langchain_agentcore_codeinterpreter.sandbox import AgentCoreSandbox
4
+
5
+ __all__ = ["AgentCoreSandbox"]
@@ -0,0 +1,273 @@
1
+ """Amazon Bedrock AgentCore Code Interpreter sandbox backend implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import logging
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from deepagents.backends.protocol import (
10
+ ExecuteResponse,
11
+ FileDownloadResponse,
12
+ FileUploadResponse,
13
+ )
14
+ from deepagents.backends.sandbox import BaseSandbox
15
+
16
+ if TYPE_CHECKING:
17
+ from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def _extract_text_from_stream(response: dict[str, Any]) -> tuple[str, int | None]:
23
+ """Extract text output and exit code from a code interpreter response stream.
24
+
25
+ Iterates through the streamed response events and collects text content,
26
+ error messages, and the exit code.
27
+
28
+ Args:
29
+ response: Response dict from a code interpreter invocation.
30
+
31
+ Returns:
32
+ Tuple of (output_text, exit_code). The exit code is ``None`` when
33
+ the response stream does not include one.
34
+ """
35
+ output_parts: list[str] = []
36
+ exit_code: int | None = None
37
+
38
+ for event in response.get("stream", []):
39
+ if "result" not in event:
40
+ continue
41
+
42
+ result = event["result"]
43
+
44
+ if "exitCode" in result:
45
+ exit_code = result["exitCode"]
46
+
47
+ for content_item in result.get("content", []):
48
+ content_type = content_item.get("type")
49
+
50
+ if content_type == "text":
51
+ text = content_item.get("text", "")
52
+ output_parts.append(text)
53
+ elif content_type == "error":
54
+ error_msg = content_item.get("text", "Unknown error")
55
+ output_parts.append(f"Error: {error_msg}")
56
+ if exit_code is None:
57
+ exit_code = 1
58
+
59
+ return "\n".join(output_parts), exit_code
60
+
61
+
62
+ def _extract_files_from_stream(
63
+ response: dict[str, Any],
64
+ requested_paths: list[str],
65
+ ) -> dict[str, bytes]:
66
+ """Extract file contents from a code interpreter ``readFiles`` response.
67
+
68
+ Matches ``file://`` URIs in the response back to the original requested
69
+ paths by stripping leading slashes for comparison.
70
+
71
+ Args:
72
+ response: Response dict from a code interpreter ``readFiles``
73
+ invocation.
74
+ requested_paths: The original paths that were requested, used to
75
+ map URIs back to caller-provided names.
76
+
77
+ Returns:
78
+ Dict mapping original requested paths to their contents as bytes.
79
+ """
80
+ path_lookup: dict[str, str] = {}
81
+ for path in requested_paths:
82
+ stripped = path.lstrip("/")
83
+ path_lookup[stripped] = path
84
+
85
+ files: dict[str, bytes] = {}
86
+
87
+ for event in response.get("stream", []):
88
+ if "result" not in event:
89
+ continue
90
+ for item in event["result"].get("content", []):
91
+ if item.get("type") != "resource":
92
+ continue
93
+ resource = item.get("resource", {})
94
+ uri = resource.get("uri", "")
95
+ file_path = uri.replace("file://", "").lstrip("/")
96
+
97
+ content: bytes | None = None
98
+ if "text" in resource:
99
+ content = resource["text"].encode("utf-8")
100
+ elif "blob" in resource:
101
+ content = base64.b64decode(resource["blob"])
102
+
103
+ if content is not None:
104
+ original_path = path_lookup.get(file_path, file_path)
105
+ files[original_path] = content
106
+
107
+ return files
108
+
109
+
110
+ class AgentCoreSandbox(BaseSandbox):
111
+ """AgentCore Code Interpreter sandbox conforming to SandboxBackendProtocol.
112
+
113
+ Wraps an active :class:`CodeInterpreter` session to execute shell commands
114
+ and manage files in a secure, isolated MicroVM environment.
115
+
116
+ This implementation inherits all file operation methods from
117
+ :class:`BaseSandbox` and implements the required ``execute()``,
118
+ ``download_files()``, and ``upload_files()`` methods using AgentCore's
119
+ streaming API.
120
+
121
+ The caller is responsible for managing the interpreter lifecycle
122
+ (``start()`` / ``stop()``).
123
+
124
+ Example:
125
+ .. code-block:: python
126
+
127
+ from bedrock_agentcore.tools.code_interpreter_client import (
128
+ CodeInterpreter,
129
+ )
130
+ from langchain_agentcore_codeinterpreter import AgentCoreSandbox
131
+
132
+ interpreter = CodeInterpreter(region="us-west-2")
133
+ interpreter.start()
134
+
135
+ backend = AgentCoreSandbox(interpreter=interpreter)
136
+ result = backend.execute("echo hello")
137
+ print(result.output)
138
+
139
+ interpreter.stop()
140
+ """
141
+
142
+ def __init__(self, *, interpreter: CodeInterpreter) -> None:
143
+ """Create a backend wrapping an active CodeInterpreter session.
144
+
145
+ Args:
146
+ interpreter: A started :class:`CodeInterpreter` instance.
147
+ """
148
+ self._interpreter = interpreter
149
+
150
+ @staticmethod
151
+ def _to_relative_path(path: str) -> str:
152
+ """Strip leading slashes so paths are relative for AgentCore APIs.
153
+
154
+ Args:
155
+ path: File path (absolute or relative).
156
+
157
+ Returns:
158
+ Relative path string.
159
+ """
160
+ return path.lstrip("/")
161
+
162
+ @property
163
+ def id(self) -> str:
164
+ """Return the AgentCore session ID."""
165
+ return self._interpreter.session_id or ""
166
+
167
+ def execute(
168
+ self,
169
+ command: str,
170
+ *,
171
+ timeout: int | None = None, # noqa: ARG002
172
+ ) -> ExecuteResponse:
173
+ """Execute a shell command inside the sandbox.
174
+
175
+ Args:
176
+ command: Shell command string to execute.
177
+ timeout: Unused. AgentCore does not support per-command timeouts.
178
+ Accepted for interface compatibility with
179
+ :class:`SandboxBackendProtocol`.
180
+
181
+ Returns:
182
+ Response containing the command output, exit code, and truncation
183
+ flag.
184
+ """
185
+ try:
186
+ response = self._interpreter.invoke(
187
+ method="executeCommand", params={"command": command}
188
+ )
189
+ output, exit_code = _extract_text_from_stream(response)
190
+ return ExecuteResponse(
191
+ output=output,
192
+ exit_code=exit_code if exit_code is not None else 0,
193
+ truncated=False,
194
+ )
195
+ except Exception as exc:
196
+ logger.exception("Error executing command: %s", command[:80])
197
+ msg = f"Error executing command: {exc}"
198
+ return ExecuteResponse(
199
+ output=msg,
200
+ exit_code=1,
201
+ truncated=False,
202
+ )
203
+
204
+ def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
205
+ """Download files from the AgentCore sandbox.
206
+
207
+ Uses AgentCore's ``readFiles`` API. Supports partial success —
208
+ individual file downloads may fail without affecting others.
209
+
210
+ Args:
211
+ paths: List of file paths to download.
212
+
213
+ Returns:
214
+ List of :class:`FileDownloadResponse` objects in the same order
215
+ as the input paths.
216
+ """
217
+ try:
218
+ relative_paths = [self._to_relative_path(p) for p in paths]
219
+ response = self._interpreter.invoke(
220
+ method="readFiles", params={"paths": relative_paths}
221
+ )
222
+ file_contents = _extract_files_from_stream(response, paths)
223
+
224
+ return [
225
+ FileDownloadResponse(
226
+ path=path,
227
+ content=file_contents.get(path),
228
+ error=None if path in file_contents else "file_not_found",
229
+ )
230
+ for path in paths
231
+ ]
232
+ except Exception:
233
+ logger.exception("Error downloading files: %s", paths)
234
+ return [
235
+ FileDownloadResponse(path=path, content=None, error="file_not_found")
236
+ for path in paths
237
+ ]
238
+
239
+ def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
240
+ """Upload files to the AgentCore sandbox.
241
+
242
+ Text files are sent directly; binary files are base64-encoded.
243
+
244
+ Args:
245
+ files: List of ``(path, content)`` tuples to upload.
246
+
247
+ Returns:
248
+ List of :class:`FileUploadResponse` objects in the same order
249
+ as the input files.
250
+ """
251
+ file_list: list[dict[str, str]] = []
252
+
253
+ for path, content in files:
254
+ rel_path = self._to_relative_path(path)
255
+ try:
256
+ text_content = content.decode("utf-8")
257
+ file_list.append({"path": rel_path, "text": text_content})
258
+ except UnicodeDecodeError:
259
+ encoded = base64.b64encode(content).decode("ascii")
260
+ file_list.append({"path": rel_path, "blob": encoded})
261
+
262
+ try:
263
+ if file_list:
264
+ self._interpreter.invoke(
265
+ method="writeFiles", params={"content": file_list}
266
+ )
267
+ return [FileUploadResponse(path=path, error=None) for path, _ in files]
268
+ except Exception:
269
+ logger.exception("Error uploading files: %s", [p for p, _ in files])
270
+ return [
271
+ FileUploadResponse(path=path, error="permission_denied")
272
+ for path, _ in files
273
+ ]
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: langchain-agentcore-codeinterpreter
3
+ Version: 0.0.1
4
+ Summary: Amazon Bedrock AgentCore Code Interpreter sandbox integration for Deep Agents
5
+ Project-URL: Source Code, https://github.com/langchain-ai/langchain-aws/tree/main/libs/agentcore-codeinterpreter
6
+ Project-URL: Repository, https://github.com/langchain-ai/langchain-aws
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: agentcore,aws,bedrock,code-interpreter,deepagents,langchain,sandbox
10
+ Requires-Python: <4.0,>=3.11
11
+ Requires-Dist: bedrock-agentcore>=1.1.4
12
+ Requires-Dist: boto3>=1.42.42
13
+ Requires-Dist: deepagents>=0.1.0
14
+ Description-Content-Type: text/markdown
15
+
16
+ # langchain-agentcore-codeinterpreter
17
+
18
+ [![PyPI - Version](https://img.shields.io/pypi/v/langchain-agentcore-codeinterpreter?label=%20)](https://pypi.org/project/langchain-agentcore-codeinterpreter/#history)
19
+ [![PyPI - License](https://img.shields.io/pypi/l/langchain-agentcore-codeinterpreter)](https://opensource.org/licenses/MIT)
20
+ [![PyPI - Downloads](https://img.shields.io/pepy/dt/langchain-agentcore-codeinterpreter)](https://pypistats.org/packages/langchain-agentcore-codeinterpreter)
21
+
22
+ Amazon Bedrock AgentCore Code Interpreter sandbox integration for [Deep Agents](https://github.com/langchain-ai/deepagents).
23
+
24
+ This package provides `AgentCoreSandbox` — a [`SandboxBackendProtocol`](https://docs.langchain.com/oss/deepagents/sandboxes) implementation that wraps AgentCore's [Code Interpreter](https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-code-interpreter.html), a secure, isolated MicroVM environment for executing code. The caller manages the interpreter lifecycle (`start()` / `stop()`); the sandbox backend handles command execution and file operations.
25
+
26
+ > **Note:** For the LangChain `BaseTool` integration (used with `create_react_agent` and LangGraph agents), see [`langchain-aws[tools]`](https://github.com/langchain-ai/langchain-aws). This package is specifically for the Deep Agents `BaseSandbox` protocol.
27
+
28
+ ## Prerequisites
29
+
30
+ **1. AWS credentials** configured via one of the following methods:
31
+
32
+ ```bash
33
+ # Option 1: Long-lived IAM credentials
34
+ export AWS_ACCESS_KEY_ID="your-access-key"
35
+ export AWS_SECRET_ACCESS_KEY="your-secret-key"
36
+ export AWS_REGION="us-west-2"
37
+
38
+ # Option 2: Temporary credentials (IAM roles, SSO, STS AssumeRole)
39
+ export AWS_ACCESS_KEY_ID="your-access-key"
40
+ export AWS_SECRET_ACCESS_KEY="your-secret-key"
41
+ export AWS_SESSION_TOKEN="your-session-token"
42
+ export AWS_REGION="us-west-2"
43
+
44
+ # Option 3: AWS CLI profile (picks up ~/.aws/credentials + ~/.aws/config)
45
+ aws configure
46
+ # or for SSO:
47
+ aws configure sso
48
+ aws sso login --profile your-profile
49
+ ```
50
+
51
+ Any method supported by the [boto3 credential chain](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) works, including EC2 instance profiles, ECS task roles, and environment variables.
52
+
53
+ **2. IAM permissions** — your credentials must allow `bedrock-agentcore:InvokeCodeInterpreter` (or the equivalent action for your region). See the [AgentCore Code Interpreter docs](https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-code-interpreter.html) for the required IAM policy.
54
+
55
+ **3. Region availability** — Code Interpreter is available in select AWS regions. `us-west-2` is a safe default. Pass the region to `CodeInterpreter(region=...)`.
56
+
57
+ ## Quick Install
58
+
59
+ ```bash
60
+ pip install langchain-agentcore-codeinterpreter
61
+ ```
62
+
63
+ ## Usage
64
+
65
+ ### Standalone
66
+
67
+ ```python
68
+ from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
69
+
70
+ from langchain_agentcore_codeinterpreter import AgentCoreSandbox
71
+
72
+ interpreter = CodeInterpreter(region="us-west-2")
73
+ interpreter.start()
74
+
75
+ backend = AgentCoreSandbox(interpreter=interpreter)
76
+
77
+ result = backend.execute("echo hello")
78
+ print(result.output) # "hello"
79
+
80
+ interpreter.stop()
81
+ ```
82
+
83
+ ### With Deep Agents
84
+
85
+ ```python
86
+ from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
87
+ from deepagents import create_deep_agent
88
+
89
+ from langchain_agentcore_codeinterpreter import AgentCoreSandbox
90
+ from langchain_aws import ChatBedrockConverse
91
+
92
+ interpreter = CodeInterpreter(region="us-west-2")
93
+ interpreter.start()
94
+
95
+ model = ChatBedrockConverse(
96
+ model="us.anthropic.claude-sonnet-4-6",
97
+ region_name="us-west-2",
98
+ )
99
+ backend = AgentCoreSandbox(interpreter=interpreter)
100
+ agent = create_deep_agent(
101
+ model=model,
102
+ backend=backend,
103
+ system_prompt="You are a coding assistant with sandbox access.",
104
+ )
105
+
106
+ try:
107
+ result = agent.invoke(
108
+ {
109
+ "messages": [
110
+ {"role": "user", "content": "Create and run a hello world script"}
111
+ ]
112
+ }
113
+ )
114
+ print(result["messages"][-1].content)
115
+ finally:
116
+ interpreter.stop()
117
+ ```
118
+
119
+ ### File operations
120
+
121
+ ```python
122
+ # Upload files
123
+ backend.upload_files([
124
+ ("data.csv", b"name,value\nalice,42\nbob,17"),
125
+ ("analyze.py", b"import csv\nprint('ready')"),
126
+ ])
127
+
128
+ # Download files
129
+ results = backend.download_files(["data.csv"])
130
+ for r in results:
131
+ if r.content is not None:
132
+ print(f"{r.path}: {r.content.decode()}")
133
+ else:
134
+ print(f"Failed: {r.path}: {r.error}")
135
+ ```
136
+
137
+ ## Session behavior
138
+
139
+ AgentCore sessions cannot be reconnected after `interpreter.stop()` is called. Each `start()` creates a fresh, isolated MicroVM. Sessions auto-expire after a configurable timeout (default 15 minutes, maximum 8 hours).
140
+
141
+ ## Contributing
142
+
143
+ See the [langchain-aws contributing guide](https://github.com/langchain-ai/langchain-aws/blob/main/.github/CONTRIBUTING.md).
144
+
145
+ ```bash
146
+ cd libs/agentcore-codeinterpreter
147
+
148
+ # Run unit tests (no network, no AWS credentials needed)
149
+ make tests
150
+
151
+ # Run linter
152
+ make lint
153
+
154
+ # Run integration tests (requires AWS credentials)
155
+ make integration_tests
156
+ ```
@@ -0,0 +1,6 @@
1
+ langchain_agentcore_codeinterpreter/__init__.py,sha256=5Q8uChJ-rUXR0QVEQcIfS1dbzvAOk7EC7L1twhVVZsU,191
2
+ langchain_agentcore_codeinterpreter/sandbox.py,sha256=D_BjDRnw0704XgyRF9SAzv2savmewi3Fok1zg2kUQLY,9234
3
+ langchain_agentcore_codeinterpreter-0.0.1.dist-info/METADATA,sha256=eHMBUMlXEgqMcMqlVUfLjmoqF5dvxrrW5YFabB0Yzr0,5676
4
+ langchain_agentcore_codeinterpreter-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
5
+ langchain_agentcore_codeinterpreter-0.0.1.dist-info/licenses/LICENSE,sha256=TsZ-TKbmch26hJssqCJhWXyGph7iFLvyFBYAa3stBHg,1067
6
+ langchain_agentcore_codeinterpreter-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) LangChain, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.