Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add possibility to change domain in python SDK

Jakub Novak1fd6cd5be861
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 897347e50..bf08da016 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -26,10 +26,7 @@ from .api import (
E2BApiClient,
client,
)
-from .constants import (
- SANDBOX_DOMAIN,
- API_HOST,
-)
+from .constants import DOMAIN
from .sandbox import (
Sandbox,
FilesystemOperation,
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 761713b0c..fe9efa941 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,7 +1,7 @@
from importlib.metadata import version
from typing import Union
-from e2b.constants import API_HOST
+from e2b.constants import DOMAIN, PROTOCOL, DEBUG
from e2b.api.metadata import default_headers
@@ -16,11 +16,6 @@ else:
import e2b.api.v2.client.exceptions as exceptions
-# Defining the host is optional and defaults to https://api.e2b.dev
-# See configuration.py for a list of all supported configuration parameters.
-configuration = client.Configuration(
- host=API_HOST,
-)
class E2BApiClient(client.ApiClient):
@@ -28,9 +23,17 @@ class E2BApiClient(client.ApiClient):
self,
api_key: Union[str, None] = None,
access_token: Union[str, None] = None,
+ domain: str = DOMAIN,
*args,
**kwargs,
):
+ prefix = "" if DEBUG else f"api."
+ api_host = f"{PROTOCOL}://{prefix}{domain}"
+
+ # Defining the host is optional and defaults to https://api.e2b.dev
+ # See configuration.py for a list of all supported configuration parameters.
+ configuration = client.Configuration(host=api_host)
+
configuration.api_key["ApiKeyAuth"] = api_key
configuration.access_token = access_token
@@ -38,4 +41,4 @@ class E2BApiClient(client.ApiClient):
self.default_headers = default_headers
-__all__ = ["E2BApiClient", "configuration", "client", "models"]
+__all__ = ["E2BApiClient", "client", "models"]
diff --git a/packages/python-sdk/e2b/constants.py b/packages/python-sdk/e2b/constants.py
index be18c0ab6..7ae087fac 100644
--- a/packages/python-sdk/e2b/constants.py
+++ b/packages/python-sdk/e2b/constants.py
@@ -4,16 +4,13 @@ SANDBOX_REFRESH_PERIOD = 5 # seconds
TIMEOUT = 60
-DOMAIN = os.getenv("E2B_DOMAIN") or "e2b.dev"
+
SECURE = os.getenv("E2B_SECURE", "TRUE").upper() == "TRUE"
DEBUG = os.getenv("E2B_DEBUG") or False
-
-API_DOMAIN = "localhost:3000" if DEBUG else f"api.{DOMAIN}"
PROTOCOL = "https" if SECURE and not DEBUG else "http"
-API_HOST = f"{PROTOCOL}://{API_DOMAIN}"
-SANDBOX_DOMAIN = DOMAIN
+DOMAIN = os.getenv("E2B_DOMAIN") or "e2b.dev"
ENVD_PORT = 49982
WS_ROUTE = "/ws"
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index ba1432475..fea2bfd9d 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -8,7 +8,7 @@ from typing import Any, Callable, Dict, List, Literal, Optional, IO, TypeVar, Un
from typing_extensions import Self
from e2b.api import models
-from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTE
+from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTE, DOMAIN
from e2b.sandbox.code_snippet import CodeSnippetManager, OpenPort
from e2b.sandbox.env_vars import EnvVars
from e2b.sandbox.filesystem import FilesystemManager
@@ -77,6 +77,7 @@ class Sandbox(SandboxConnection):
on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
metadata: Optional[Dict[str, str]] = None,
timeout: Optional[float] = TIMEOUT,
+ domain: str = DOMAIN,
_sandbox: Optional[models.Sandbox] = None,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
@@ -101,6 +102,7 @@ class Sandbox(SandboxConnection):
:param on_exit: A default callback that is called when the process exits
:param metadata: A dictionary of strings that is stored alongside the running sandbox. You can see this metadata when you list running sandboxes.
:param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds
+ :param domain: The domain to use for the API
"""
template = id or template or "base"
@@ -146,6 +148,7 @@ class Sandbox(SandboxConnection):
_debug_port=_debug_port,
_debug_dev_env=_debug_dev_env,
timeout=timeout,
+ domain=domain,
)
self._actions: Dict[str, Action[Self]] = {}
@@ -254,6 +257,7 @@ class Sandbox(SandboxConnection):
on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
timeout: Optional[float] = TIMEOUT,
api_key: Optional[str] = None,
+ domain: str = DOMAIN,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
_debug_dev_env: Optional[Literal["remote", "local"]] = None,
@@ -270,7 +274,7 @@ class Sandbox(SandboxConnection):
:param on_exit: A default callback that is called when the process exits
:param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds
:param api_key: The API key to use, if not provided, the `E2B_API_KEY` environment variable is used
-
+ :param domain: The domain to use for the API
```py
sandbox = Sandbox()
@@ -295,6 +299,7 @@ class Sandbox(SandboxConnection):
on_exit=on_exit,
timeout=timeout,
api_key=api_key,
+ domain=domain,
_sandbox=models.Sandbox(
sandbox_id=sandbox_id,
client_id=client_id,
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
index 615a42ad8..c070ea5cb 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
@@ -13,7 +13,7 @@ from urllib3.exceptions import ReadTimeoutError, MaxRetryError, ConnectTimeoutEr
from e2b.api import E2BApiClient, exceptions, models, client
from e2b.constants import (
- SANDBOX_DOMAIN,
+ DOMAIN,
SANDBOX_REFRESH_PERIOD,
TIMEOUT,
ENVD_PORT,
@@ -95,6 +95,7 @@ class SandboxConnection:
env_vars: Optional[EnvVars] = None,
metadata: Optional[Dict[str, str]] = None,
timeout: Optional[float] = TIMEOUT,
+ domain: Optional[str] = None,
_sandbox: Optional[models.Sandbox] = None,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
@@ -120,7 +121,9 @@ class SandboxConnection:
self._debug_port = _debug_port
self._debug_dev_env = _debug_dev_env
self._sandbox = _sandbox
+ self.domain = domain or DOMAIN
+ self._api_client = E2BApiClient(api_key=self._api_key, domain=self.domain)
self._is_open = False
self._process_cleanup: List[Callable[[], Any]] = []
self._subscribers = {}
@@ -156,7 +159,7 @@ class SandboxConnection:
if not self._sandbox:
raise SandboxException("Sandbox is not running.")
- hostname = f"{self.id}.{SANDBOX_DOMAIN}"
+ hostname = f"{self.id}.{self.domain}"
if port:
return f"{port}-{hostname}"
@@ -184,23 +187,22 @@ class SandboxConnection:
if not 0 <= duration <= 3600:
raise ValueError("Duration must be between 0 and 3600 seconds")
- with E2BApiClient(api_key=self._api_key) as api_client:
- api = client.SandboxesApi(api_client)
- try:
- api.sandboxes_sandbox_id_refreshes_post(
- self._sandbox.sandbox_id,
- client.SandboxesSandboxIDRefreshesPostRequest(duration=duration),
- )
- logger.debug(
- f"Sandbox will be kept alive without connection for next {duration} seconds."
- )
- except exceptions.ApiException as e:
- if e.status == 404:
- raise SandboxException(
- f"Sandbox {self.id} failed because it cannot be found"
- ) from e
- else:
- raise e
+ api = client.SandboxesApi(self._api_client)
+ try:
+ api.sandboxes_sandbox_id_refreshes_post(
+ self._sandbox.sandbox_id,
+ client.SandboxesSandboxIDRefreshesPostRequest(duration=duration),
+ )
+ logger.debug(
+ f"Sandbox will be kept alive without connection for next {duration} seconds."
+ )
+ except exceptions.ApiException as e:
+ if e.status == 404:
+ raise SandboxException(
+ f"Sandbox {self.id} failed because it cannot be found"
+ ) from e
+ else:
+ raise e
def close(self) -> None:
"""
@@ -240,16 +242,15 @@ class SandboxConnection:
if not self._sandbox and not self._debug_hostname:
try:
- with E2BApiClient(api_key=self._api_key) as api_client:
- api = client.SandboxesApi(api_client)
+ api = client.SandboxesApi(self._api_client)
- self._sandbox = api.sandboxes_post(
- models.NewSandbox(templateID=self._template, metadata=metadata),
- _request_timeout=timeout,
- )
- logger.info(
- f"Sandbox {self._sandbox.template_id} created (id:{self.id})"
- )
+ self._sandbox = api.sandboxes_post(
+ models.NewSandbox(templateID=self._template, metadata=metadata),
+ _request_timeout=timeout,
+ )
+ logger.info(
+ f"Sandbox {self._sandbox.template_id} created (id:{self.id})"
+ )
except ReadTimeoutError as e:
logger.error(f"Failed to acquire sandbox")
self._close()
@@ -419,38 +420,36 @@ class SandboxConnection:
)
current_retry = 0
-
- with E2BApiClient(api_key=self._api_key) as api_client:
- api = client.SandboxesApi(api_client)
- while True:
- if not self._is_open:
- logger.debug(
- f"Cannot refresh sandbox - it was closed. {self.id}"
- )
- return
- sleep(SANDBOX_REFRESH_PERIOD)
- try:
- api.sandboxes_sandbox_id_refreshes_post(
- self._sandbox.sandbox_id,
- client.SandboxesSandboxIDRefreshesPostRequest(duration=0),
- )
- logger.debug(f"Refreshed sandbox {self.id}")
- except exceptions.ApiException as e:
- if e.status == 404:
- raise SandboxException(
- f"Sandbox {self.id} failed because it cannot be found"
- ) from e
+ api = client.SandboxesApi(self._api_client)
+ while True:
+ if not self._is_open:
+ logger.debug(
+ f"Cannot refresh sandbox - it was closed. {self.id}"
+ )
+ return
+ sleep(SANDBOX_REFRESH_PERIOD)
+ try:
+ api.sandboxes_sandbox_id_refreshes_post(
+ self._sandbox.sandbox_id,
+ client.SandboxesSandboxIDRefreshesPostRequest(duration=0),
+ )
+ logger.debug(f"Refreshed sandbox {self.id}")
+ except exceptions.ApiException as e:
+ if e.status == 404:
+ raise SandboxException(
+ f"Sandbox {self.id} failed because it cannot be found"
+ ) from e
+ else:
+ if current_retry < self._refresh_retries:
+ logger.error(
+ f"Refreshing sandbox {self.id} failed. Retrying..."
+ )
+ current_retry += 1
else:
- if current_retry < self._refresh_retries:
- logger.error(
- f"Refreshing sandbox {self.id} failed. Retrying..."
- )
- current_retry += 1
- else:
- logger.error(
- f"Refreshing sandbox {self.id} failed. Max retries exceeded"
- )
- raise e
+ logger.error(
+ f"Refreshing sandbox {self.id} failed. Max retries exceeded"
+ )
+ raise e
finally:
if self._sandbox:
logger.info(f"Stopped refreshing sandbox (id: {self.id})")
@@ -460,16 +459,17 @@ class SandboxConnection:
self._close()
@staticmethod
- def list(api_key: Optional[str] = None) -> List[RunningSandbox]:
+ def list(api_key: Optional[str] = None, domain: str = DOMAIN) -> List[RunningSandbox]:
"""
List all running sandboxes.
:param api_key: API key to use for authentication.
+ :param domain: Domain to use for the API.
If not provided, the `E2B_API_KEY` environment variable will be used.
"""
api_key = get_api_key(api_key)
- with E2BApiClient(api_key=api_key) as api_client:
+ with E2BApiClient(api_key=api_key, domain=domain) as api_client:
return [
RunningSandbox(
sandbox_id=f"{sandbox.sandbox_id}-{sandbox.client_id}",
@@ -479,18 +479,19 @@ class SandboxConnection:
]
@staticmethod
- def kill(sandbox_id: str, api_key: Optional[str] = None) -> None:
+ def kill(sandbox_id: str, api_key: Optional[str] = None, domain: str = DOMAIN) -> None:
"""
Kill the running sandbox specified by the sandbox ID.
:param sandbox_id: ID of the sandbox to kill.
:param api_key: API key to use for authentication.
+ :param domain: Domain to use for the API.
If not provided, the `E2B_API_KEY` environment variable will be used.
"""
api_key = get_api_key(api_key)
short_id = sandbox_id.split("-")[0]
- with E2BApiClient(api_key=api_key) as api_client:
+ with E2BApiClient(api_key=api_key, domain=domain) as api_client:
return client.SandboxesApi(api_client).sandboxes_sandbox_id_delete(
sandbox_id=short_id
)