173 lines
5.5 KiB
Python
Raw Permalink Normal View History

2024-06-21 18:05:51 -07:00
import json
2024-06-28 11:10:10 -07:00
import logging
import os
2025-01-22 20:50:48 -08:00
from dataclasses import dataclass
from types import TracebackType
from typing import Optional, Protocol, Union
from httpx import AsyncBaseTransport, BaseTransport, Limits
2024-06-21 18:05:51 -07:00
2024-07-11 23:15:56 +02:00
from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.types import Response
from e2b.api.metadata import default_headers
from e2b.connection_config import ConnectionConfig
2024-10-22 21:41:08 -07:00
from e2b.exceptions import (
AuthenticationException,
2024-10-22 21:57:08 -07:00
RateLimitException,
SandboxException,
2024-10-22 21:41:08 -07:00
)
2024-06-02 23:06:37 +02:00
2024-06-28 11:10:10 -07:00
logger = logging.getLogger(__name__)
2024-06-02 23:06:37 +02:00
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
limits = Limits(
max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),
keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),
)
2025-01-22 20:50:48 -08:00
@dataclass
class SandboxCreateResponse:
sandbox_id: str
sandbox_domain: Optional[str]
2025-01-22 20:50:48 -08:00
envd_version: str
Fix Python SDK type issues with ty type checker (#1122) ## Summary - Resolved 43 type diagnostics reported by ty (Astral's Python type checker) - Fixed Self type issues on class singletons - Added explicit type annotations for shadowed attributes - Replaced None with UNSET for auto-generated API parameters - Fixed method signature alignment for protocol matching - Added targeted type: ignore suppressions for pattern-based limitations All checks pass: ty check, ruff format, ruff check. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly typing/CI changes, but some adjustments affect sandbox connect/pause overload dispatch and API response/parameter handling (`UNSET` vs `None`), which could alter edge-case runtime behavior. > > **Overview** > Fixes Python SDK static typing issues for Astral’s `ty` checker and wires typechecking into CI. > > Adds a new `Typecheck` GitHub Action plus workspace `typecheck` scripts (TS packages via `tsc`, Python SDK via `make typecheck` running `ty`), and publishes a patch changeset for `@e2b/python-sdk`. > > Across the Python SDK, adjusts type annotations and overloads (e.g., `Self`/singleton typing, `connect` overloads, optional `user`/token/domain handling), tightens API model parsing with `cast`/`Optional` checks and `UNSET` usage, and adds a few targeted `ty` ignore comments in tests/protocols to silence checker limitations. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit f66402847c40cee7e44e1aaa7caa97e271ba9978. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-02-12 17:23:39 +01:00
envd_access_token: Optional[str]
traffic_access_token: Optional[str]
2025-01-22 20:50:48 -08:00
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
def handle_api_exception(
e: "SupportsApiErrorResponse",
Render failed layer stack traces on build error (#901) ### Changelog - Added traces for Python and JavaScript SDK. - Added methods for stack trace collection, stack trace context - Updated file upload mechanism for tracing - Changed API handling to support throwing API errors with traces > **Note** > For functions like `aptInstall`, `fromRegistry` which call `.run` and `.fromImage`, the stack trace has to be replaced so it throws correctly from parent. > **Note** > There are no build logs in the trace, we can add this at later point. ### Examples Keep in mind that the way the traces are rendered entirely depends on environment (Bun, Node, Deno, Vitest, Pytest) **Standard Python** ``` Traceback (most recent call last): File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py", line 17, in <module> Template.build( ~~~~~~~~~~~~~~^ template, ^^^^^^^^^ ...<2 lines>... memory_mb=1024, ^^^^^^^^^^^^^^^ ) ^ File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/e2b/template_sync/main.py", line 157, in build wait_for_build_finish( ~~~~~~~~~~~~~~~~~~~~~^ api_client, ^^^^^^^^^^^ ...<4 lines>... stack_traces=template._template._stack_traces, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/e2b/template_sync/build_api.py", line 199, in wait_for_build_finish raise BuildException(error_message).with_traceback(stack_trace) File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py", line 12, in <module> .run_cmd("cat non_existing_file.txt") ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ e2b.template.exceptions.BuildException: failed to run command: exit status 1 ``` **Pytest** ``` [gw0] darwin -- Python 3.13.3 /Users/mish/Library/Caches/pypoetry/virtualenvs/e2b-e6GdLxLZ-py3.13/bin/python @pytest.mark.skip_debug() def test_build(): template = ( Template() .from_image("ubuntu:22.04") .run_cmd("cat non_existing_file.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", wait_for_timeout(10_000)) ) # try: > Template.build( template, alias=str(uuid4()), cpu_count=1, memory_mb=1024, ) tests/sync/template_sync/test_stacktrace.py:18: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ e2b/template_sync/main.py:157: in build wait_for_build_finish( e2b/template_sync/build_api.py:199: in wait_for_build_finish raise BuildException(error_message).with_traceback(stack_trace) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @pytest.mark.skip_debug() def test_build(): template = ( Template() .from_image("ubuntu:22.04") > .run_cmd("cat non_existing_file.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", wait_for_timeout(10_000)) ) E e2b.template.exceptions.BuildException: failed to run command: exit status 1 tests/sync/template_sync/test_stacktrace.py:12: BuildException ========================================================== short test summary info ========================================================== FAILED tests/sync/template_sync/test_stacktrace.py::test_build - e2b.template.exceptions.BuildException: failed to run command: exit status 1 ``` **Node** ``` node:internal/modules/run_main:104 triggerUncaughtException( ^ at file:///Users/mish/Documents/Projects/E2B/E2B/packages/js-sdk/tests/template/trace.test.mts:8:4 at ModuleJob.run (node:internal/modules/esm/module_job:274:25) at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:644:26) at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:98:5) { name: 'BuildError' } Node.js v23.11.0 ``` **Bun** ``` 1 | export class BuildError extends Error { 2 | constructor(message: string, stackTrace?: string) { 3 | super(message) ^ BuildError: failed to run command: exit status 1 at /Users/mish/Documents/Projects/E2B/E2B/packages/js-sdk/src/template/errors.ts:3:5 Bun v1.2.4 (macOS arm64) ``` **Vitest** ``` BuildError: failed to run command: exit status 1 ❯ tests/template/trace.test.ts:8:6 6| const template = Template() 7| .fromImage('ubuntu:22.04') 8| .runCmd('cat folder/test.txt') | ^ 9| .setWorkdir('/app') 10| .setStartCmd('echo "Hello, world!"', waitForTimeout(10_000)) ``` --------- Co-authored-by: Jakub Dobry <jakub.dobry8@gmail.com>
2025-09-19 12:34:08 +02:00
default_exception_class: type[Exception] = SandboxException,
stack_trace: Optional[TracebackType] = None,
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
):
2024-07-12 12:22:57 -07:00
try:
body = json.loads(e.content) if e.content else {}
except json.JSONDecodeError:
body = {}
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
if e.status_code == 401:
message = f"{e.status_code}: Unauthorized, please check your credentials."
if body.get("message"):
message += f" - {body['message']}"
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
return AuthenticationException(message)
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
if e.status_code == 429:
message = f"{e.status_code}: Rate limit exceeded, please try again later."
if body.get("message"):
message += f" - {body['message']}"
return RateLimitException(message)
2024-10-22 21:41:08 -07:00
2024-06-21 18:05:51 -07:00
if "message" in body:
Render failed layer stack traces on build error (#901) ### Changelog - Added traces for Python and JavaScript SDK. - Added methods for stack trace collection, stack trace context - Updated file upload mechanism for tracing - Changed API handling to support throwing API errors with traces > **Note** > For functions like `aptInstall`, `fromRegistry` which call `.run` and `.fromImage`, the stack trace has to be replaced so it throws correctly from parent. > **Note** > There are no build logs in the trace, we can add this at later point. ### Examples Keep in mind that the way the traces are rendered entirely depends on environment (Bun, Node, Deno, Vitest, Pytest) **Standard Python** ``` Traceback (most recent call last): File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py", line 17, in <module> Template.build( ~~~~~~~~~~~~~~^ template, ^^^^^^^^^ ...<2 lines>... memory_mb=1024, ^^^^^^^^^^^^^^^ ) ^ File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/e2b/template_sync/main.py", line 157, in build wait_for_build_finish( ~~~~~~~~~~~~~~~~~~~~~^ api_client, ^^^^^^^^^^^ ...<4 lines>... stack_traces=template._template._stack_traces, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/e2b/template_sync/build_api.py", line 199, in wait_for_build_finish raise BuildException(error_message).with_traceback(stack_trace) File "/Users/mish/Documents/Projects/E2B/E2B/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py", line 12, in <module> .run_cmd("cat non_existing_file.txt") ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ e2b.template.exceptions.BuildException: failed to run command: exit status 1 ``` **Pytest** ``` [gw0] darwin -- Python 3.13.3 /Users/mish/Library/Caches/pypoetry/virtualenvs/e2b-e6GdLxLZ-py3.13/bin/python @pytest.mark.skip_debug() def test_build(): template = ( Template() .from_image("ubuntu:22.04") .run_cmd("cat non_existing_file.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", wait_for_timeout(10_000)) ) # try: > Template.build( template, alias=str(uuid4()), cpu_count=1, memory_mb=1024, ) tests/sync/template_sync/test_stacktrace.py:18: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ e2b/template_sync/main.py:157: in build wait_for_build_finish( e2b/template_sync/build_api.py:199: in wait_for_build_finish raise BuildException(error_message).with_traceback(stack_trace) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @pytest.mark.skip_debug() def test_build(): template = ( Template() .from_image("ubuntu:22.04") > .run_cmd("cat non_existing_file.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", wait_for_timeout(10_000)) ) E e2b.template.exceptions.BuildException: failed to run command: exit status 1 tests/sync/template_sync/test_stacktrace.py:12: BuildException ========================================================== short test summary info ========================================================== FAILED tests/sync/template_sync/test_stacktrace.py::test_build - e2b.template.exceptions.BuildException: failed to run command: exit status 1 ``` **Node** ``` node:internal/modules/run_main:104 triggerUncaughtException( ^ at file:///Users/mish/Documents/Projects/E2B/E2B/packages/js-sdk/tests/template/trace.test.mts:8:4 at ModuleJob.run (node:internal/modules/esm/module_job:274:25) at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:644:26) at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:98:5) { name: 'BuildError' } Node.js v23.11.0 ``` **Bun** ``` 1 | export class BuildError extends Error { 2 | constructor(message: string, stackTrace?: string) { 3 | super(message) ^ BuildError: failed to run command: exit status 1 at /Users/mish/Documents/Projects/E2B/E2B/packages/js-sdk/src/template/errors.ts:3:5 Bun v1.2.4 (macOS arm64) ``` **Vitest** ``` BuildError: failed to run command: exit status 1 ❯ tests/template/trace.test.ts:8:6 6| const template = Template() 7| .fromImage('ubuntu:22.04') 8| .runCmd('cat folder/test.txt') | ^ 9| .setWorkdir('/app') 10| .setStartCmd('echo "Hello, world!"', waitForTimeout(10_000)) ``` --------- Co-authored-by: Jakub Dobry <jakub.dobry8@gmail.com>
2025-09-19 12:34:08 +02:00
return default_exception_class(
f"{e.status_code}: {body['message']}"
).with_traceback(stack_trace)
return default_exception_class(f"{e.status_code}: {e.content}").with_traceback(
stack_trace
)
2024-06-21 18:05:51 -07:00
class SupportsApiErrorResponse(Protocol):
@property
def status_code(self) -> int: ...
@property
def content(self) -> Union[str, bytes]: ...
2024-07-11 23:15:56 +02:00
class ApiClient(AuthenticatedClient):
2024-10-08 13:04:39 +02:00
"""
The client for interacting with the E2B API.
"""
def __init__(
self,
config: ConnectionConfig,
2024-06-21 18:05:51 -07:00
require_api_key: bool = True,
2024-06-02 23:06:37 +02:00
require_access_token: bool = False,
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
transport: Optional[Union[BaseTransport, AsyncBaseTransport]] = None,
*args,
**kwargs,
):
2024-07-11 23:15:56 +02:00
if require_api_key and require_access_token:
2024-06-02 23:06:37 +02:00
raise AuthenticationException(
2024-07-11 23:15:56 +02:00
"Only one of api_key or access_token can be required, not both",
2024-06-02 23:06:37 +02:00
)
2024-07-11 23:15:56 +02:00
if not require_api_key and not require_access_token:
2024-06-02 23:06:37 +02:00
raise AuthenticationException(
2024-07-11 23:15:56 +02:00
"Either api_key or access_token is required",
2024-06-02 23:06:37 +02:00
)
2024-07-11 23:15:56 +02:00
token = None
if require_api_key:
if config.api_key is None:
raise AuthenticationException(
"API key is required, please visit the Team tab at https://e2b.dev/dashboard to get your API key. "
2024-07-11 23:15:56 +02:00
"You can either set the environment variable `E2B_API_KEY` "
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
'or you can pass it directly to the method like api_key="e2b_..."',
2024-07-11 23:15:56 +02:00
)
token = config.api_key
if require_access_token:
if config.access_token is None:
raise AuthenticationException(
"Access token is required, please visit the Personal tab at https://e2b.dev/dashboard to get your access token. "
2024-07-11 23:15:56 +02:00
"You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `access_token` in options.",
)
token = config.access_token
auth_header_name = "X-API-KEY" if require_api_key else "Authorization"
prefix = "" if require_api_key else "Bearer"
headers = {
**default_headers,
**(config.headers or {}),
}
# Prevent passing these parameters twice
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
more_headers: Optional[dict] = kwargs.pop("headers", None)
if more_headers:
headers.update(more_headers)
kwargs.pop("token", None)
kwargs.pop("auth_header_name", None)
kwargs.pop("prefix", None)
2024-07-11 16:55:45 +02:00
super().__init__(
base_url=config.api_url,
httpx_args={
"event_hooks": {
"request": [self._log_request],
"response": [self._log_response],
},
"proxy": config.proxy,
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
"transport": transport,
},
headers=headers,
Fix Python SDK type issues with ty type checker (#1122) ## Summary - Resolved 43 type diagnostics reported by ty (Astral's Python type checker) - Fixed Self type issues on class singletons - Added explicit type annotations for shadowed attributes - Replaced None with UNSET for auto-generated API parameters - Fixed method signature alignment for protocol matching - Added targeted type: ignore suppressions for pattern-based limitations All checks pass: ty check, ruff format, ruff check. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly typing/CI changes, but some adjustments affect sandbox connect/pause overload dispatch and API response/parameter handling (`UNSET` vs `None`), which could alter edge-case runtime behavior. > > **Overview** > Fixes Python SDK static typing issues for Astral’s `ty` checker and wires typechecking into CI. > > Adds a new `Typecheck` GitHub Action plus workspace `typecheck` scripts (TS packages via `tsc`, Python SDK via `make typecheck` running `ty`), and publishes a patch changeset for `@e2b/python-sdk`. > > Across the Python SDK, adjusts type annotations and overloads (e.g., `Self`/singleton typing, `connect` overloads, optional `user`/token/domain handling), tightens API model parsing with `cast`/`Optional` checks and `UNSET` usage, and adds a few targeted `ty` ignore comments in tests/protocols to silence checker limitations. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit f66402847c40cee7e44e1aaa7caa97e271ba9978. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-02-12 17:23:39 +01:00
token=token or "",
2024-07-11 23:15:56 +02:00
auth_header_name=auth_header_name,
prefix=prefix,
*args,
**kwargs,
)
def _log_request(self, request):
logger.info(f"Request {request.method} {request.url}")
def _log_response(self, response: Response):
if response.status_code >= 400:
logger.error(f"Response {response.status_code}")
2024-06-28 11:10:10 -07:00
else:
logger.info(f"Response {response.status_code}")
# We need to override the logging hooks for the async usage
class AsyncApiClient(ApiClient):
async def _log_request(self, request):
logger.info(f"Request {request.method} {request.url}")
async def _log_response(self, response: Response):
if response.status_code >= 400:
logger.error(f"Response {response.status_code}")
else:
logger.info(f"Response {response.status_code}")