2024-06-21 18:05:51 -07:00
|
|
|
import json
|
2024-06-28 11:10:10 -07:00
|
|
|
import logging
|
2025-11-15 23:35:09 +01:00
|
|
|
import os
|
2025-01-22 20:50:48 -08:00
|
|
|
from dataclasses import dataclass
|
2025-11-15 23:35:09 +01:00
|
|
|
from types import TracebackType
|
2026-03-26 01:37:46 +01:00
|
|
|
from typing import Optional, Protocol, Union
|
2025-11-15 23:35:09 +01:00
|
|
|
|
|
|
|
|
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
|
2025-11-15 23:35:09 +01:00
|
|
|
from e2b.api.client.types import Response
|
2023-11-06 15:07:09 +01:00
|
|
|
from e2b.api.metadata import default_headers
|
2025-11-15 23:35:09 +01:00
|
|
|
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,
|
2025-11-15 23:35:09 +01:00
|
|
|
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
|
|
|
|
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")),
|
|
|
|
|
)
|
|
|
|
|
|
2023-09-29 16:27:26 +02:00
|
|
|
|
2025-01-22 20:50:48 -08:00
|
|
|
@dataclass
|
|
|
|
|
class SandboxCreateResponse:
|
|
|
|
|
sandbox_id: str
|
2025-07-18 13:15:12 +02:00
|
|
|
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]
|
2025-11-15 23:35:09 +01:00
|
|
|
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(
|
2026-03-26 01:37:46 +01:00
|
|
|
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."
|
2025-08-21 17:45:25 +02:00
|
|
|
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)
|
2025-08-21 17:45:25 +02: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
|
|
|
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']}"
|
2025-08-21 17:45:25 +02:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2026-03-26 01:37:46 +01: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.
|
|
|
|
|
"""
|
|
|
|
|
|
2023-11-06 15:07:09 +01:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
2024-06-01 21:07:13 +02:00
|
|
|
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,
|
2025-11-14 16:48:29 -08:00
|
|
|
transport: Optional[Union[BaseTransport, AsyncBaseTransport]] = None,
|
2023-11-06 15:07:09 +01:00
|
|
|
*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(
|
2024-11-04 10:53:10 -08:00
|
|
|
"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(
|
2024-11-04 10:53:10 -08:00
|
|
|
"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
|
|
|
|
|
|
2024-08-19 15:42:25 +02:00
|
|
|
auth_header_name = "X-API-KEY" if require_api_key else "Authorization"
|
|
|
|
|
prefix = "" if require_api_key else "Bearer"
|
2024-07-05 18:12:28 -07:00
|
|
|
|
2025-04-04 00:08:12 +01:00
|
|
|
headers = {
|
|
|
|
|
**default_headers,
|
|
|
|
|
**(config.headers or {}),
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-19 09:37:07 +02:00
|
|
|
# Prevent passing these parameters twice
|
2025-11-14 16:48:29 -08:00
|
|
|
more_headers: Optional[dict] = kwargs.pop("headers", None)
|
|
|
|
|
if more_headers:
|
|
|
|
|
headers.update(more_headers)
|
2025-08-19 09:37:07 +02:00
|
|
|
kwargs.pop("token", None)
|
|
|
|
|
kwargs.pop("auth_header_name", None)
|
|
|
|
|
kwargs.pop("prefix", None)
|
|
|
|
|
|
2024-07-11 16:55:45 +02:00
|
|
|
super().__init__(
|
2024-07-05 18:12:28 -07:00
|
|
|
base_url=config.api_url,
|
|
|
|
|
httpx_args={
|
|
|
|
|
"event_hooks": {
|
|
|
|
|
"request": [self._log_request],
|
|
|
|
|
"response": [self._log_response],
|
2024-07-08 18:33:18 -07:00
|
|
|
},
|
2025-04-19 00:12:25 +02:00
|
|
|
"proxy": config.proxy,
|
2025-11-14 16:48:29 -08:00
|
|
|
"transport": transport,
|
2024-07-05 18:12:28 -07:00
|
|
|
},
|
2025-04-04 00:08:12 +01:00
|
|
|
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,
|
2024-07-05 18:12:28 -07:00
|
|
|
*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:
|
2024-07-05 18:12:28 -07:00
|
|
|
logger.info(f"Response {response.status_code}")
|
2024-07-08 18:33:18 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# 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}")
|