e2b-haystack 1.0.0__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,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: e2b-haystack
3
+ Version: 1.0.0
4
+ Summary: Haystack integration for E2B cloud sandboxes
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/e2b#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/e2b
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: E2B,Haystack,code execution,sandbox,tools
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: e2b>=2.0.0
24
+ Requires-Dist: haystack-ai>=2.19.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # e2b-haystack
28
+
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/e2b-haystack.svg)](https://pypi.org/project/e2b-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/e2b-haystack.svg)](https://pypi.org/project/e2b-haystack)
31
+
32
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/e2b/CHANGELOG.md)
33
+
34
+ ---
35
+
36
+ ## Contributing
37
+
38
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
39
+
40
+ To run integration tests locally, set the `E2B_API_KEY` environment variable (get one at <https://e2b.dev/>).
@@ -0,0 +1,12 @@
1
+ haystack_integrations/tools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/tools/e2b/__init__.py,sha256=XL_KIT6iXtKvwfoifJBVoGQZ9eEaWhwCwspgFpnGm3E,693
3
+ haystack_integrations/tools/e2b/bash_tool.py,sha256=03GudyOqjBZHv1g47jYIgMdQjACVbL8PKeZ6LuGHMw4,3600
4
+ haystack_integrations/tools/e2b/e2b_sandbox.py,sha256=J69pRUnMlgfzXSnoCmmqSMo2Px1oJ44NP4IbfAMlyWE,9232
5
+ haystack_integrations/tools/e2b/list_directory_tool.py,sha256=5ZGdKcPUIxm5vfsIQv0cwT_GL1GjA-LB7SwK9Pg00Cc,2856
6
+ haystack_integrations/tools/e2b/read_file_tool.py,sha256=FXG1F6oo3osL04nBHDhScEPvd1FQp4XEGyQVMXovVsw,2551
7
+ haystack_integrations/tools/e2b/sandbox_toolset.py,sha256=iOxYmV7CajeOWYH308uBatmKd5JGMz56fw4tJb0uBVw,3532
8
+ haystack_integrations/tools/e2b/write_file_tool.py,sha256=l-Cftsq9gxXZZgJvuaPx8m_-54Z6peD4lGtuTZc2g-4,2624
9
+ e2b_haystack-1.0.0.dist-info/METADATA,sha256=G6GJUpMOoMoBeVJ7nYtduia3JsBUjD-LLgNPSfUzb_M,1868
10
+ e2b_haystack-1.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ e2b_haystack-1.0.0.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
12
+ e2b_haystack-1.0.0.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,19 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from haystack_integrations.tools.e2b.bash_tool import RunBashCommandTool
6
+ from haystack_integrations.tools.e2b.e2b_sandbox import E2BSandbox
7
+ from haystack_integrations.tools.e2b.list_directory_tool import ListDirectoryTool
8
+ from haystack_integrations.tools.e2b.read_file_tool import ReadFileTool
9
+ from haystack_integrations.tools.e2b.sandbox_toolset import E2BToolset
10
+ from haystack_integrations.tools.e2b.write_file_tool import WriteFileTool
11
+
12
+ __all__ = [
13
+ "E2BSandbox",
14
+ "E2BToolset",
15
+ "ListDirectoryTool",
16
+ "ReadFileTool",
17
+ "RunBashCommandTool",
18
+ "WriteFileTool",
19
+ ]
@@ -0,0 +1,94 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack.core.serialization import generate_qualified_class_name
8
+ from haystack.tools import Tool
9
+
10
+ from haystack_integrations.tools.e2b.e2b_sandbox import E2BSandbox
11
+
12
+
13
+ class RunBashCommandTool(Tool):
14
+ """
15
+ A :class:`~haystack.tools.Tool` that executes bash commands inside an E2B sandbox.
16
+
17
+ Pass the same :class:`E2BSandbox` instance to multiple tool classes so they
18
+ all operate in the same live sandbox environment.
19
+
20
+ ### Usage example
21
+
22
+ ```python
23
+ from haystack_integrations.tools.e2b import E2BSandbox, RunBashCommandTool, ReadFileTool
24
+
25
+ sandbox = E2BSandbox()
26
+ agent = Agent(
27
+ chat_generator=...,
28
+ tools=[
29
+ RunBashCommandTool(sandbox=sandbox),
30
+ ReadFileTool(sandbox=sandbox),
31
+ ],
32
+ )
33
+ ```
34
+ """
35
+
36
+ def __init__(self, sandbox: E2BSandbox) -> None:
37
+ """
38
+ Create a RunBashCommandTool.
39
+
40
+ :param sandbox: The :class:`E2BSandbox` instance that will execute commands.
41
+ """
42
+
43
+ def run_bash_command(command: str, timeout: int = 60) -> str:
44
+ sb = sandbox._require_sandbox()
45
+ try:
46
+ result = sb.commands.run(command, timeout=timeout)
47
+ return f"exit_code: {result.exit_code}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}"
48
+ except Exception as e:
49
+ # e2b raises CommandExitException for non-zero exit codes. That exception
50
+ # carries exit_code/stdout/stderr attributes — treat it as a valid result
51
+ # rather than an error so the LLM can see and react to the exit status.
52
+ if hasattr(e, "exit_code"):
53
+ stdout = getattr(e, "stdout", "")
54
+ stderr = getattr(e, "stderr", "")
55
+ return f"exit_code: {e.exit_code}\nstdout:\n{stdout}\nstderr:\n{stderr}" # type: ignore[union-attr]
56
+ msg = f"Failed to run bash command: {e}"
57
+ raise RuntimeError(msg) from e
58
+
59
+ super().__init__(
60
+ name="run_bash_command",
61
+ description=(
62
+ "Execute a bash command inside the E2B sandbox and return the combined stdout, "
63
+ "stderr, and exit code. Use this to run shell scripts, install packages, compile "
64
+ "code, or perform any system-level operation."
65
+ ),
66
+ parameters={
67
+ "type": "object",
68
+ "properties": {
69
+ "command": {"type": "string", "description": "The bash command to execute."},
70
+ "timeout": {
71
+ "type": "integer",
72
+ "description": (
73
+ "Maximum number of seconds to wait for the command to finish. Defaults to 60 seconds."
74
+ ),
75
+ },
76
+ },
77
+ "required": ["command"],
78
+ },
79
+ function=run_bash_command,
80
+ )
81
+ self._e2b_sandbox = sandbox
82
+
83
+ def to_dict(self) -> dict[str, Any]:
84
+ """Serialize this tool to a dictionary."""
85
+ return {
86
+ "type": generate_qualified_class_name(type(self)),
87
+ "data": {"sandbox": self._e2b_sandbox.to_dict()},
88
+ }
89
+
90
+ @classmethod
91
+ def from_dict(cls, data: dict[str, Any]) -> "RunBashCommandTool":
92
+ """Deserialize a RunBashCommandTool from a dictionary."""
93
+ sandbox = E2BSandbox.from_dict(data["data"]["sandbox"])
94
+ return cls(sandbox=sandbox)
@@ -0,0 +1,238 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import uuid
6
+ import weakref
7
+ from typing import Any, ClassVar
8
+
9
+ from haystack import logging
10
+ from haystack.core.serialization import generate_qualified_class_name
11
+ from haystack.lazy_imports import LazyImport
12
+ from haystack.utils import Secret, deserialize_secrets_inplace
13
+
14
+ with LazyImport(message="Run 'pip install e2b'") as e2b_import:
15
+ from e2b import Sandbox
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class E2BSandbox:
21
+ """
22
+ Manages the lifecycle of an E2B cloud sandbox.
23
+
24
+ Instantiate this class and pass it to one or more E2B tool classes
25
+ (`RunBashCommandTool`, `ReadFileTool`, `WriteFileTool`,
26
+ `ListDirectoryTool`) to share a single sandbox environment across all
27
+ tools. All tools that receive the same `E2BSandbox` instance operate
28
+ inside the same live sandbox process.
29
+
30
+ ### Usage example
31
+
32
+ ```python
33
+ from haystack.components.generators.chat import OpenAIChatGenerator
34
+ from haystack.components.agents import Agent
35
+
36
+ from haystack_integrations.tools.e2b import (
37
+ E2BSandbox,
38
+ RunBashCommandTool,
39
+ ReadFileTool,
40
+ WriteFileTool,
41
+ ListDirectoryTool,
42
+ )
43
+
44
+ sandbox = E2BSandbox()
45
+ agent = Agent(
46
+ chat_generator=OpenAIChatGenerator(model="gpt-4o"),
47
+ tools=[
48
+ RunBashCommandTool(sandbox=sandbox),
49
+ ReadFileTool(sandbox=sandbox),
50
+ WriteFileTool(sandbox=sandbox),
51
+ ListDirectoryTool(sandbox=sandbox),
52
+ ],
53
+ )
54
+ ```
55
+
56
+ Lifecycle is handled automatically by the Agent's pipeline. If you use the
57
+ tools standalone, call :meth:`warm_up` before the first tool invocation:
58
+
59
+ ```python
60
+ sandbox.warm_up()
61
+ # ... use tools ...
62
+ sandbox.close()
63
+ ```
64
+ """
65
+
66
+ # Process-wide cache used during deserialization to keep tools that
67
+ # shared one sandbox before serialization sharing it after `from_dict`
68
+ # as well. Keyed by `instance_id`. Weak refs so an entry disappears
69
+ # once no tool references the sandbox. A cache hit is only honored
70
+ # when the full serialized config matches (see `from_dict`), so a
71
+ # crafted YAML cannot hijack another tenant's live instance.
72
+ _instances: ClassVar["weakref.WeakValueDictionary[str, E2BSandbox]"] = weakref.WeakValueDictionary()
73
+
74
+ def __init__(
75
+ self,
76
+ api_key: Secret = Secret.from_env_var("E2B_API_KEY", strict=True),
77
+ sandbox_template: str = "base",
78
+ timeout: int = 120,
79
+ environment_vars: dict[str, str] | None = None,
80
+ instance_id: str | None = None,
81
+ ) -> None:
82
+ """
83
+ Create an E2BSandbox instance.
84
+
85
+ :param api_key: E2B API key.
86
+ :param sandbox_template: E2B sandbox template name.
87
+ :param timeout: Sandbox inactivity timeout in seconds.
88
+ :param environment_vars: Optional environment variables to inject into the sandbox.
89
+ :param instance_id: Stable identifier preserved across `to_dict`/`from_dict`. When
90
+ omitted, a fresh UUID is generated. Tools that share the same `E2BSandbox`
91
+ instance inherit this id, which is what lets them re-share the instance after
92
+ a serialization round-trip. Distinct from the cloud-side sandbox id assigned
93
+ by E2B at warm-up.
94
+ """
95
+ self.api_key = api_key
96
+ self.sandbox_template = sandbox_template
97
+ self.timeout = timeout
98
+ self.environment_vars = environment_vars or {}
99
+ self.instance_id = instance_id or uuid.uuid4().hex
100
+ self._sandbox: Any = None
101
+
102
+ # ------------------------------------------------------------------
103
+ # Lifecycle
104
+ # ------------------------------------------------------------------
105
+
106
+ def warm_up(self) -> None:
107
+ """
108
+ Establish the connection to the E2B sandbox.
109
+
110
+ Idempotent -- calling it multiple times has no effect if the sandbox is
111
+ already running.
112
+
113
+ :raises RuntimeError: If the E2B sandbox cannot be created.
114
+ """
115
+ if self._sandbox is not None:
116
+ return
117
+
118
+ e2b_import.check()
119
+ resolved_key = self.api_key.resolve_value()
120
+ try:
121
+ logger.info(
122
+ "Starting E2B sandbox (template={template}, timeout={timeout}s)",
123
+ template=self.sandbox_template,
124
+ timeout=self.timeout,
125
+ )
126
+ self._sandbox = Sandbox.create(
127
+ api_key=resolved_key,
128
+ template=self.sandbox_template,
129
+ timeout=self.timeout,
130
+ envs=self.environment_vars if self.environment_vars else None,
131
+ )
132
+ logger.info("E2B sandbox started (id={sandbox_id})", sandbox_id=self._sandbox.sandbox_id)
133
+ except Exception as e:
134
+ msg = f"Failed to start E2B sandbox: {e}"
135
+ raise RuntimeError(msg) from e
136
+
137
+ def close(self) -> None:
138
+ """
139
+ Shut down the E2B sandbox and release all associated resources.
140
+
141
+ Call this when you are done to avoid leaving idle sandboxes running.
142
+ """
143
+ if self._sandbox is None:
144
+ return
145
+ try:
146
+ self._sandbox.kill()
147
+ logger.info("E2B sandbox closed")
148
+ except Exception as e:
149
+ logger.warning("Failed to close E2B sandbox: {error}", error=e)
150
+ finally:
151
+ self._sandbox = None
152
+
153
+ # ------------------------------------------------------------------
154
+ # Serialisation
155
+ # ------------------------------------------------------------------
156
+
157
+ def to_dict(self) -> dict[str, Any]:
158
+ """
159
+ Serialize the sandbox configuration to a dictionary.
160
+
161
+ :returns: Dictionary containing the serialised configuration.
162
+ """
163
+ return {
164
+ "type": generate_qualified_class_name(type(self)),
165
+ "data": {
166
+ "instance_id": self.instance_id,
167
+ "api_key": self.api_key.to_dict(),
168
+ "sandbox_template": self.sandbox_template,
169
+ "timeout": self.timeout,
170
+ "environment_vars": self.environment_vars,
171
+ },
172
+ }
173
+
174
+ @classmethod
175
+ def from_dict(cls, data: dict[str, Any]) -> "E2BSandbox":
176
+ """
177
+ Deserialize an :class:`E2BSandbox` from a dictionary.
178
+
179
+ Multiple tools that shared a single :class:`E2BSandbox` before serialization
180
+ will share the same restored instance: each tool's `from_dict` consults a
181
+ process-wide cache keyed on `instance_id`. A cache hit is only honored when
182
+ the full serialized config (api_key, template, timeout, environment_vars)
183
+ matches the cached entry — a crafted YAML with a guessed id but a different
184
+ config falls through to a fresh instance and never observes the cached one.
185
+
186
+ :param data: Dictionary created by :meth:`to_dict`.
187
+ :returns: An :class:`E2BSandbox` instance ready to be warmed up. May be a
188
+ previously-restored instance if the id and config match.
189
+ """
190
+ inner = data["data"]
191
+ instance_id = inner.get("instance_id")
192
+
193
+ # Snapshot the incoming config in its serialized (Secret-as-dict) form
194
+ # before `deserialize_secrets_inplace` mutates `inner`, so we can compare
195
+ # against `cached.api_key.to_dict()` symmetrically.
196
+ incoming_config = {
197
+ "api_key": inner.get("api_key"),
198
+ "sandbox_template": inner.get("sandbox_template", "base"),
199
+ "timeout": inner.get("timeout", 120),
200
+ "environment_vars": inner.get("environment_vars", {}),
201
+ }
202
+
203
+ if instance_id is not None:
204
+ cached = cls._instances.get(instance_id)
205
+ if cached is not None:
206
+ cached_config = {
207
+ "api_key": cached.api_key.to_dict(),
208
+ "sandbox_template": cached.sandbox_template,
209
+ "timeout": cached.timeout,
210
+ "environment_vars": cached.environment_vars,
211
+ }
212
+ if incoming_config == cached_config:
213
+ return cached
214
+ # Id collision with mismatched config: fall through to building
215
+ # a fresh instance, but DO NOT register it — preserves the
216
+ # legitimate cached entry from being evicted.
217
+
218
+ deserialize_secrets_inplace(inner, keys=["api_key"])
219
+ instance = cls(
220
+ api_key=inner["api_key"],
221
+ sandbox_template=inner.get("sandbox_template", "base"),
222
+ timeout=inner.get("timeout", 120),
223
+ environment_vars=inner.get("environment_vars", {}),
224
+ instance_id=instance_id,
225
+ )
226
+ if instance_id is not None and instance_id not in cls._instances:
227
+ cls._instances[instance_id] = instance
228
+ return instance
229
+
230
+ # ------------------------------------------------------------------
231
+ # Internal helpers (used by the tool classes)
232
+ # ------------------------------------------------------------------
233
+
234
+ def _require_sandbox(self) -> "Sandbox":
235
+ """Return the active sandbox or raise a helpful error."""
236
+ if self._sandbox is None:
237
+ self.warm_up()
238
+ return self._sandbox
@@ -0,0 +1,81 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack.core.serialization import generate_qualified_class_name
8
+ from haystack.tools import Tool
9
+
10
+ from haystack_integrations.tools.e2b.e2b_sandbox import E2BSandbox
11
+
12
+
13
+ class ListDirectoryTool(Tool):
14
+ """
15
+ A :class:`~haystack.tools.Tool` that lists directory contents in an E2B sandbox.
16
+
17
+ Pass the same :class:`E2BSandbox` instance to multiple tool classes so they
18
+ all operate in the same live sandbox environment.
19
+
20
+ ### Usage example
21
+
22
+ ```python
23
+ from haystack_integrations.tools.e2b import E2BSandbox, ListDirectoryTool
24
+
25
+ sandbox = E2BSandbox()
26
+ agent = Agent(chat_generator=..., tools=[ListDirectoryTool(sandbox=sandbox)])
27
+ ```
28
+ """
29
+
30
+ def __init__(self, sandbox: E2BSandbox) -> None:
31
+ """
32
+ Create a ListDirectoryTool.
33
+
34
+ :param sandbox: The :class:`E2BSandbox` instance to list directories from.
35
+ """
36
+
37
+ def list_directory(path: str) -> str:
38
+ sb = sandbox._require_sandbox()
39
+ try:
40
+ entries = sb.files.list(path)
41
+ lines = []
42
+ for entry in entries:
43
+ name = entry.name
44
+ if getattr(entry, "is_dir", False) or getattr(entry, "type", "") == "dir":
45
+ name = name + "/"
46
+ lines.append(name)
47
+ return "\n".join(lines) if lines else "(empty directory)"
48
+ except Exception as e:
49
+ msg = f"Failed to list directory '{path}': {e}"
50
+ raise RuntimeError(msg) from e
51
+
52
+ super().__init__(
53
+ name="list_directory",
54
+ description=(
55
+ "List the files and subdirectories inside a directory in the E2B sandbox "
56
+ "filesystem. Returns a newline-separated list of names with a trailing '/' "
57
+ "appended to subdirectory names."
58
+ ),
59
+ parameters={
60
+ "type": "object",
61
+ "properties": {
62
+ "path": {"type": "string", "description": "Absolute or relative path of the directory to list."}
63
+ },
64
+ "required": ["path"],
65
+ },
66
+ function=list_directory,
67
+ )
68
+ self._e2b_sandbox = sandbox
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ """Serialize this tool to a dictionary."""
72
+ return {
73
+ "type": generate_qualified_class_name(type(self)),
74
+ "data": {"sandbox": self._e2b_sandbox.to_dict()},
75
+ }
76
+
77
+ @classmethod
78
+ def from_dict(cls, data: dict[str, Any]) -> "ListDirectoryTool":
79
+ """Deserialize a ListDirectoryTool from a dictionary."""
80
+ sandbox = E2BSandbox.from_dict(data["data"]["sandbox"])
81
+ return cls(sandbox=sandbox)
@@ -0,0 +1,76 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack.core.serialization import generate_qualified_class_name
8
+ from haystack.tools import Tool
9
+
10
+ from haystack_integrations.tools.e2b.e2b_sandbox import E2BSandbox
11
+
12
+
13
+ class ReadFileTool(Tool):
14
+ """
15
+ A :class:`~haystack.tools.Tool` that reads files from an E2B sandbox filesystem.
16
+
17
+ Pass the same :class:`E2BSandbox` instance to multiple tool classes so they
18
+ all operate in the same live sandbox environment.
19
+
20
+ ### Usage example
21
+
22
+ ```python
23
+ from haystack_integrations.tools.e2b import E2BSandbox, ReadFileTool
24
+
25
+ sandbox = E2BSandbox()
26
+ agent = Agent(chat_generator=..., tools=[ReadFileTool(sandbox=sandbox)])
27
+ ```
28
+ """
29
+
30
+ def __init__(self, sandbox: E2BSandbox) -> None:
31
+ """
32
+ Create a ReadFileTool.
33
+
34
+ :param sandbox: The :class:`E2BSandbox` instance to read files from.
35
+ """
36
+
37
+ def read_file(path: str) -> str:
38
+ sb = sandbox._require_sandbox()
39
+ try:
40
+ content = sb.files.read(path)
41
+ if isinstance(content, bytes):
42
+ return content.decode("utf-8", errors="replace")
43
+ return str(content)
44
+ except Exception as e:
45
+ msg = f"Failed to read file '{path}': {e}"
46
+ raise RuntimeError(msg) from e
47
+
48
+ super().__init__(
49
+ name="read_file",
50
+ description=(
51
+ "Read the text content of a file from the E2B sandbox filesystem and return it "
52
+ "as a string. The file must exist; use list_directory to verify paths first."
53
+ ),
54
+ parameters={
55
+ "type": "object",
56
+ "properties": {
57
+ "path": {"type": "string", "description": "Absolute or relative path of the file to read."}
58
+ },
59
+ "required": ["path"],
60
+ },
61
+ function=read_file,
62
+ )
63
+ self._e2b_sandbox = sandbox
64
+
65
+ def to_dict(self) -> dict[str, Any]:
66
+ """Serialize this tool to a dictionary."""
67
+ return {
68
+ "type": generate_qualified_class_name(type(self)),
69
+ "data": {"sandbox": self._e2b_sandbox.to_dict()},
70
+ }
71
+
72
+ @classmethod
73
+ def from_dict(cls, data: dict[str, Any]) -> "ReadFileTool":
74
+ """Deserialize a ReadFileTool from a dictionary."""
75
+ sandbox = E2BSandbox.from_dict(data["data"]["sandbox"])
76
+ return cls(sandbox=sandbox)
@@ -0,0 +1,97 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack.core.serialization import generate_qualified_class_name
8
+ from haystack.tools import Toolset
9
+ from haystack.utils import Secret, deserialize_secrets_inplace
10
+
11
+ from haystack_integrations.tools.e2b.bash_tool import RunBashCommandTool
12
+ from haystack_integrations.tools.e2b.e2b_sandbox import E2BSandbox
13
+ from haystack_integrations.tools.e2b.list_directory_tool import ListDirectoryTool
14
+ from haystack_integrations.tools.e2b.read_file_tool import ReadFileTool
15
+ from haystack_integrations.tools.e2b.write_file_tool import WriteFileTool
16
+
17
+
18
+ class E2BToolset(Toolset):
19
+ """
20
+ A :class:`~haystack.tools.Toolset` that bundles all E2B sandbox tools.
21
+
22
+ All tools in the set share a single :class:`E2BSandbox` instance so they
23
+ operate inside the same live sandbox process. The toolset owns the sandbox
24
+ lifecycle: calling :meth:`warm_up` starts the sandbox, and serialisation
25
+ round-trips preserve the shared-sandbox relationship.
26
+
27
+ ### Usage example
28
+
29
+ ```python
30
+ from haystack.components.generators.chat import OpenAIChatGenerator
31
+ from haystack.components.agents import Agent
32
+
33
+ from haystack_integrations.tools.e2b import E2BToolset
34
+
35
+ agent = Agent(
36
+ chat_generator=OpenAIChatGenerator(model="gpt-4o"),
37
+ tools=E2BToolset(),
38
+ )
39
+ ```
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ api_key: Secret = Secret.from_env_var("E2B_API_KEY", strict=True),
45
+ sandbox_template: str = "base",
46
+ timeout: int = 120,
47
+ environment_vars: dict[str, str] | None = None,
48
+ ) -> None:
49
+ """
50
+ Create an E2BToolset.
51
+
52
+ :param api_key: E2B API key. Defaults to ``Secret.from_env_var("E2B_API_KEY")``.
53
+ :param sandbox_template: E2B sandbox template name. Defaults to ``"base"``.
54
+ :param timeout: Sandbox inactivity timeout in seconds. Defaults to ``120``.
55
+ :param environment_vars: Optional environment variables to inject into the sandbox.
56
+ """
57
+ self.sandbox = E2BSandbox(
58
+ api_key=api_key,
59
+ sandbox_template=sandbox_template,
60
+ timeout=timeout,
61
+ environment_vars=environment_vars,
62
+ )
63
+ super().__init__(
64
+ tools=[
65
+ RunBashCommandTool(sandbox=self.sandbox),
66
+ ReadFileTool(sandbox=self.sandbox),
67
+ WriteFileTool(sandbox=self.sandbox),
68
+ ListDirectoryTool(sandbox=self.sandbox),
69
+ ]
70
+ )
71
+
72
+ def warm_up(self) -> None:
73
+ """Start the shared E2B sandbox (idempotent)."""
74
+ self.sandbox.warm_up()
75
+
76
+ def close(self) -> None:
77
+ """Shut down the shared E2B sandbox and release cloud resources."""
78
+ self.sandbox.close()
79
+
80
+ def to_dict(self) -> dict[str, Any]:
81
+ """Serialize this toolset to a dictionary."""
82
+ return {
83
+ "type": generate_qualified_class_name(type(self)),
84
+ "data": self.sandbox.to_dict()["data"],
85
+ }
86
+
87
+ @classmethod
88
+ def from_dict(cls, data: dict[str, Any]) -> "E2BToolset":
89
+ """Deserialize an E2BToolset from a dictionary."""
90
+ inner = data["data"]
91
+ deserialize_secrets_inplace(inner, keys=["api_key"])
92
+ return cls(
93
+ api_key=inner["api_key"],
94
+ sandbox_template=inner.get("sandbox_template", "base"),
95
+ timeout=inner.get("timeout", 120),
96
+ environment_vars=inner.get("environment_vars", {}),
97
+ )
@@ -0,0 +1,76 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack.core.serialization import generate_qualified_class_name
8
+ from haystack.tools import Tool
9
+
10
+ from haystack_integrations.tools.e2b.e2b_sandbox import E2BSandbox
11
+
12
+
13
+ class WriteFileTool(Tool):
14
+ """
15
+ A :class:`~haystack.tools.Tool` that writes files to an E2B sandbox filesystem.
16
+
17
+ Pass the same :class:`E2BSandbox` instance to multiple tool classes so they
18
+ all operate in the same live sandbox environment.
19
+
20
+ ### Usage example
21
+
22
+ ```python
23
+ from haystack_integrations.tools.e2b import E2BSandbox, WriteFileTool
24
+
25
+ sandbox = E2BSandbox()
26
+ agent = Agent(chat_generator=..., tools=[WriteFileTool(sandbox=sandbox)])
27
+ ```
28
+ """
29
+
30
+ def __init__(self, sandbox: E2BSandbox) -> None:
31
+ """
32
+ Create a WriteFileTool.
33
+
34
+ :param sandbox: The :class:`E2BSandbox` instance to write files to.
35
+ """
36
+
37
+ def write_file(path: str, content: str) -> str:
38
+ sb = sandbox._require_sandbox()
39
+ try:
40
+ sb.files.write(path, content)
41
+ return f"File written successfully: {path}"
42
+ except Exception as e:
43
+ msg = f"Failed to write file '{path}': {e}"
44
+ raise RuntimeError(msg) from e
45
+
46
+ super().__init__(
47
+ name="write_file",
48
+ description=(
49
+ "Write text content to a file in the E2B sandbox filesystem. "
50
+ "Parent directories are created automatically if they do not exist. "
51
+ "Existing files are overwritten."
52
+ ),
53
+ parameters={
54
+ "type": "object",
55
+ "properties": {
56
+ "path": {"type": "string", "description": "Absolute or relative path of the file to write."},
57
+ "content": {"type": "string", "description": "Text content to write into the file."},
58
+ },
59
+ "required": ["path", "content"],
60
+ },
61
+ function=write_file,
62
+ )
63
+ self._e2b_sandbox = sandbox
64
+
65
+ def to_dict(self) -> dict[str, Any]:
66
+ """Serialize this tool to a dictionary."""
67
+ return {
68
+ "type": generate_qualified_class_name(type(self)),
69
+ "data": {"sandbox": self._e2b_sandbox.to_dict()},
70
+ }
71
+
72
+ @classmethod
73
+ def from_dict(cls, data: dict[str, Any]) -> "WriteFileTool":
74
+ """Deserialize a WriteFileTool from a dictionary."""
75
+ sandbox = E2BSandbox.from_dict(data["data"]["sandbox"])
76
+ return cls(sandbox=sandbox)
File without changes