Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Simplify connection config handling in Python SDK (#849)

Jakub Novákda7c60d2ddbb
diff --git a/.changeset/strange-hornets-judge.md b/.changeset/strange-hornets-judge.md
new file mode 100644
index 000000000..cb559f6ab
--- /dev/null
+++ b/.changeset/strange-hornets-judge.md
@@ -0,0 +1,5 @@
+---
+'@e2b/python-sdk': minor
+---
+
+Refactor connection config and parameters for all calls to API
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index 459bc0811..6d3250251 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -1,7 +1,8 @@
import os
-from typing import Literal, Optional, Dict
+from typing import Literal, Optional, Dict, TypedDict
from httpx._types import ProxyTypes
+from typing_extensions import Unpack
from e2b.api.metadata import package_version
@@ -11,6 +12,32 @@ KEEPALIVE_PING_INTERVAL_SEC = 50 # 50 seconds
KEEPALIVE_PING_HEADER = "Keepalive-Ping-Interval"
+class ApiParams(TypedDict, total=False):
+ """
+ Parameters for a request.
+
+ In the case of a sandbox, it applies to all **requests made to the returned sandbox**.
+ """
+
+ request_timeout: Optional[float]
+ """Timeout for the request in **seconds**, defaults to 60 seconds."""
+
+ headers: Optional[Dict[str, str]]
+ """Additional headers to send with the request."""
+
+ api_key: Optional[str]
+ """E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable."""
+
+ domain: Optional[str]
+ """E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable."""
+
+ debug: Optional[bool]
+ """Whether to use debug mode, defaults to `E2B_DEBUG` environment variable."""
+
+ proxy: Optional[ProxyTypes]
+ """Proxy to use for the request. In case of a sandbox it applies to all **requests made to the returned sandbox**."""
+
+
class ConnectionConfig:
"""
Configuration for the connection to the API.
@@ -40,6 +67,7 @@ class ConnectionConfig:
access_token: Optional[str] = None,
request_timeout: Optional[float] = None,
headers: Optional[Dict[str, str]] = None,
+ extra_sandbox_headers: Optional[Dict[str, str]] = None,
proxy: Optional[ProxyTypes] = None,
):
self.domain = domain or ConnectionConfig._domain()
@@ -48,6 +76,7 @@ class ConnectionConfig:
self.access_token = access_token or ConnectionConfig._access_token()
self.headers = headers or {}
self.headers["User-Agent"] = f"e2b-python-sdk/{package_version}"
+ self.__extra_sandbox_headers = extra_sandbox_headers or {}
self.proxy = proxy
@@ -82,6 +111,53 @@ class ConnectionConfig:
def get_request_timeout(self, request_timeout: Optional[float] = None):
return self._get_request_timeout(self.request_timeout, request_timeout)
+ def get_api_params(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> dict:
+ """
+ Get the parameters for the API call.
+
+ This is used to avoid passing the following attributes to the API call:
+ - access_token
+ - api_url
+
+ It also returns a copy, so the original object is not modified.
+
+ :return: Dictionary of parameters for the API call
+ """
+ headers = opts.get("headers")
+ request_timeout = opts.get("request_timeout")
+ api_key = opts.get("api_key")
+ domain = opts.get("domain")
+ debug = opts.get("debug")
+ proxy = opts.get("proxy")
+
+ req_headers = self.headers.copy()
+ if headers is not None:
+ req_headers.update(headers)
+
+ return dict(
+ ApiParams(
+ api_key=api_key if api_key is not None else self.api_key,
+ domain=domain if domain is not None else self.domain,
+ debug=debug if debug is not None else self.debug,
+ request_timeout=self.get_request_timeout(request_timeout),
+ headers=req_headers,
+ proxy=proxy if proxy is not None else self.proxy,
+ )
+ )
+
+ @property
+ def sandbox_headers(self):
+ """
+ # We need this separate as we use the same header for E2B access token to API and envd access token to sandbox.
+ """
+ return {
+ **self.headers,
+ **self.__extra_sandbox_headers,
+ }
+
Username = Literal["root", "user"]
"""
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index d2c39e620..4bb86d46b 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -1,6 +1,5 @@
import urllib.parse
-from abc import ABC, abstractmethod
from typing import Optional
from e2b.sandbox.signature import get_signature
@@ -9,7 +8,7 @@ from e2b.envd.api import ENVD_API_FILES_ROUTE
from httpx import Limits
-class SandboxSetup(ABC):
+class SandboxBase:
_limits = Limits(
max_keepalive_connections=40,
max_connections=40,
@@ -21,30 +20,48 @@ class SandboxSetup(ABC):
default_sandbox_timeout = 300
default_template = "base"
+ def __init__(
+ self,
+ sandbox_id: str,
+ envd_version: Optional[str],
+ envd_access_token: Optional[str],
+ sandbox_domain: Optional[str],
+ connection_config: ConnectionConfig,
+ ):
+ self.__connection_config = connection_config
+ self.__sandbox_id = sandbox_id
+ self.__sandbox_domain = sandbox_domain or self.connection_config.domain
+ self.__envd_version = envd_version
+ self.__envd_access_token = envd_access_token
+ self.__envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
+
+ @property
+ def _envd_access_token(self) -> Optional[str]:
+ """Private property to access the envd token"""
+ return self.__envd_access_token
+
@property
- @abstractmethod
def connection_config(self) -> ConnectionConfig:
- ...
+ return self.__connection_config
@property
- @abstractmethod
- def _envd_access_token(self) -> Optional[str]:
- ...
+ def _envd_version(self) -> Optional[str]:
+ return self.__envd_version
@property
- @abstractmethod
- def envd_api_url(self) -> str:
- ...
+ def sandbox_domain(self) -> Optional[str]:
+ return self.__sandbox_domain
@property
- @abstractmethod
- def sandbox_id(self) -> str:
- ...
+ def envd_api_url(self) -> str:
+ return self.__envd_api_url
@property
- @abstractmethod
- def sandbox_domain(self) -> str:
- ...
+ def sandbox_id(self) -> str:
+ """
+ Unique identifier of the sandbox.
+ """
+ return self.__sandbox_id
def _file_url(
self,
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index 49ec991f3..edd2347f4 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -1,10 +1,7 @@
-from abc import ABC
from dataclasses import dataclass
from typing import Optional, Dict
from datetime import datetime
-from httpx import Limits
-
from e2b.api.client.models import SandboxState
@@ -81,11 +78,3 @@ class SandboxMetrics:
"""Memory used in bytes."""
timestamp: datetime
"""Timestamp of the metric entry."""
-
-
-class SandboxApiBase(ABC):
- _limits = Limits(
- max_keepalive_connections=10,
- max_connections=20,
- keepalive_expiry=20,
- )
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/command.py b/packages/python-sdk/e2b/sandbox_async/commands/command.py
index 824ce99a9..1b815aeed 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/command.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/command.py
@@ -35,7 +35,7 @@ class Commands:
# compressor=e2b_connect.GzipCompressor,
async_pool=pool,
json=True,
- headers=connection_config.headers,
+ headers=connection_config.sandbox_headers,
)
async def list(
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/pty.py b/packages/python-sdk/e2b/sandbox_async/commands/pty.py
index 0833f1fee..7dca71a3b 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/pty.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/pty.py
@@ -39,6 +39,7 @@ class Pty:
# compressor=e2b_connect.GzipCompressor,
async_pool=pool,
json=True,
+ headers=connection_config.sandbox_headers,
)
async def kill(
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index 78e87acca..43f7bb182 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -51,7 +51,7 @@ class Filesystem:
# compressor=e2b_connect.GzipCompressor,
async_pool=pool,
json=True,
- headers=connection_config.headers,
+ headers=connection_config.sandbox_headers,
)
@overload
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index e2a4d8f71..08d05b26d 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -8,10 +8,9 @@ from packaging.version import Version
from typing_extensions import Unpack
from e2b.api.client.types import Unset
-from e2b.connection_config import ConnectionConfig, ProxyTypes
+from e2b.connection_config import ConnectionConfig, ApiParams
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, ahandle_envd_api_exception
from e2b.exceptions import format_request_timeout_error, SandboxException
-from e2b.sandbox.main import SandboxSetup
from e2b.sandbox.sandbox_api import SandboxMetrics
from e2b.sandbox.utils import class_method_variant
from e2b.sandbox_async.filesystem.filesystem import Filesystem
@@ -33,6 +32,10 @@ class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):
return response
+ @property
+ def pool(self):
+ return self._pool
+
class AsyncSandboxOpts(TypedDict):
sandbox_id: str
@@ -42,7 +45,7 @@ class AsyncSandboxOpts(TypedDict):
connection_config: ConnectionConfig
-class AsyncSandbox(SandboxSetup, SandboxApi):
+class AsyncSandbox(SandboxApi):
"""
E2B cloud sandbox is a secure and isolated cloud environment.
@@ -86,78 +89,36 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
"""
return self._pty
- @property
- def sandbox_id(self) -> str:
- """
- Unique identifier of the sandbox.
- """
- return self._sandbox_id
-
- @property
- def sandbox_domain(self) -> str:
- """
- Unique identifier of the sandbox.
- """
- return self._sandbox_domain
-
- @property
- def envd_api_url(self) -> str:
- return self._envd_api_url
-
- @property
- def _envd_access_token(self) -> str:
- """Private property to access the envd token"""
- return self.__envd_access_token
-
- @_envd_access_token.setter
- def _envd_access_token(self, value: str):
- """Private setter for envd token"""
- self.__envd_access_token = value
-
- @property
- def connection_config(self) -> ConnectionConfig:
- return self._connection_config
-
def __init__(self, **opts: Unpack[AsyncSandboxOpts]):
"""
Use `AsyncSandbox.create()` to create a new sandbox instead.
"""
- super().__init__()
-
- self._connection_config = opts["connection_config"]
-
- self._sandbox_id = opts["sandbox_id"]
- self._sandbox_domain = opts["sandbox_domain"] or self.connection_config.domain
-
- self._envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
- self._envd_version = opts["envd_version"]
- self._envd_access_token = opts["envd_access_token"]
+ super().__init__(**opts)
self._transport = AsyncTransportWithLogger(
- limits=self._limits, proxy=self._connection_config.proxy
+ limits=self._limits, proxy=self.connection_config.proxy
)
self._envd_api = httpx.AsyncClient(
base_url=self.envd_api_url,
transport=self._transport,
- headers=self._connection_config.headers,
+ headers=self.connection_config.sandbox_headers,
)
-
self._filesystem = Filesystem(
self.envd_api_url,
self._envd_version,
self.connection_config,
- self._transport._pool,
+ self._transport.pool,
self._envd_api,
)
self._commands = Commands(
self.envd_api_url,
self.connection_config,
- self._transport._pool,
+ self._transport.pool,
)
self._pty = Pty(
self.envd_api_url,
self.connection_config,
- self._transport._pool,
+ self._transport.pool,
)
async def is_running(self, request_timeout: Optional[float] = None) -> bool:
@@ -203,54 +164,44 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
timeout: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
envs: Optional[Dict[str, str]] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- proxy: Optional[ProxyTypes] = None,
secure: Optional[bool] = None,
allow_internet_access: Optional[bool] = True,
- ):
+ **opts: Unpack[ApiParams],
+ ) -> "AsyncSandbox":
"""
Create a new sandbox.
By default, the sandbox is created from the default `base` sandbox template.
:param template: Sandbox template name or ID
- :param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
+ :param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param metadata: Custom metadata for the sandbox
:param envs: Custom environment variables for the sandbox
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param proxy: Proxy to use for the request and for the **requests made to the returned sandbox**
:param secure: Envd is secured with access token and cannot be used without it
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
- :return: sandbox instance for the new sandbox
+ :return: A Sandbox instance for the new sandbox
Use this method instead of using the constructor to create a new sandbox.
"""
- connection_headers = {}
+ extra_sandbox_headers = {}
+ debug = opts.get("debug")
if debug:
sandbox_id = "debug_sandbox_id"
sandbox_domain = None
envd_version = None
envd_access_token = None
else:
- response = await SandboxApi._create_sandbox(
+ response = await cls._create_sandbox(
template=template or cls.default_template,
- api_key=api_key,
timeout=timeout or cls.default_sandbox_timeout,
metadata=metadata,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
env_vars=envs,
secure=secure,
- proxy=proxy,
allow_internet_access=allow_internet_access,
+ **opts,
)
sandbox_id = response.sandbox_id
@@ -261,15 +212,11 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
if envd_access_token is not None and not isinstance(
envd_access_token, Unset
):
- connection_headers["X-Access-Token"] = envd_access_token
+ extra_sandbox_headers["X-Access-Token"] = envd_access_token
connection_config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=connection_headers,
- proxy=proxy,
+ extra_sandbox_headers=extra_sandbox_headers,
+ **opts,
)
return cls(
@@ -284,20 +231,15 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
async def connect(
cls,
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- proxy: Optional[ProxyTypes] = None,
- ):
+ **opts: Unpack[ApiParams],
+ ) -> "AsyncSandbox":
"""
Connect to an existing sandbox.
- With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
+ With a sandbox ID, you can connect to the same sandbox from different places or environments (serverless functions, etc.).
:param sandbox_id: Sandbox ID
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param proxy: Proxy to use for the request and for the **requests made to the returned sandbox**
- :return: sandbox instance for the existing sandbox
+ :return: A Sandbox instance for the existing sandbox
@example
```python
@@ -307,28 +249,16 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
# Another code block
same_sandbox = await AsyncSandbox.connect(sandbox_id)
"""
+ response = await cls._cls_get_info(sandbox_id, **opts)
- connection_headers = {}
-
- response = await SandboxApi._cls_get_info(
- sandbox_id,
- api_key=api_key,
- domain=domain,
- debug=debug,
- proxy=proxy,
- )
-
- if response._envd_access_token is not None and not isinstance(
- response._envd_access_token, Unset
- ):
- connection_headers["X-Access-Token"] = response._envd_access_token
+ sandbox_headers = {}
+ envd_access_token = response._envd_access_token
+ if envd_access_token is not None and not isinstance(envd_access_token, Unset):
+ sandbox_headers["X-Access-Token"] = envd_access_token
connection_config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- headers=connection_headers,
- proxy=proxy,
+ extra_sandbox_headers=sandbox_headers,
+ **opts,
)
return cls(
@@ -336,7 +266,7 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
sandbox_domain=response.sandbox_domain,
connection_config=connection_config,
envd_version=response.envd_version,
- envd_access_token=response._envd_access_token,
+ envd_access_token=envd_access_token,
)
async def __aenter__(self):
@@ -346,12 +276,13 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
await self.kill()
@overload
- async def kill(self, request_timeout: Optional[float] = None) -> bool:
+ async def kill(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> bool:
"""
Kill the sandbox.
- :param request_timeout: Timeout for the request in **seconds**
-
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
...
@@ -360,19 +291,12 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
@staticmethod
async def kill(
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> bool:
"""
Kill the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param proxy: Proxy to use for the request
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
@@ -381,35 +305,32 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
@class_method_variant("_cls_kill")
async def kill(
self,
- request_timeout: Optional[float] = None,
- ) -> bool: # type: ignore
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
-
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
+ **opts: Unpack[ApiParams],
+ ) -> bool:
+ """
+ Kill the sandbox specified by sandbox ID.
- await SandboxApi._cls_kill(
+ :return: `True` if the sandbox was killed, `False` if the sandbox was not found
+ """
+ return await self._cls_kill(
sandbox_id=self.sandbox_id,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
@overload
async def set_timeout(
self,
timeout: int,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> None:
"""
Set the timeout of the sandbox.
- After the timeout expires the sandbox will be automatically killed.
+ After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
- Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
+ The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param timeout: Timeout for the sandbox in **seconds**
- :param request_timeout: Timeout for the request in **seconds**
"""
...
@@ -418,53 +339,49 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
async def set_timeout(
sandbox_id: str,
timeout: int,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> None:
"""
Set the timeout of the specified sandbox.
- After the timeout expires the sandbox will be automatically killed.
+ After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
- Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
+ The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param sandbox_id: Sandbox ID
:param timeout: Timeout for the sandbox in **seconds**
- :param request_timeout: Timeout for the request in **seconds**
- :param proxy: Proxy to use for the request
"""
...
@class_method_variant("_cls_set_timeout")
- async def set_timeout( # type: ignore
+ async def set_timeout(
self,
timeout: int,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> None:
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
+ """
+ Set the timeout of the specified sandbox.
+ After the timeout expires, the sandbox will be automatically killed.
+ This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
+ The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- await SandboxApi._cls_set_timeout(
+ :param timeout: Timeout for the sandbox in **seconds**
+ """
+ await self._cls_set_timeout(
sandbox_id=self.sandbox_id,
timeout=timeout,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
@overload
async def get_info(
self,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
- :param request_timeout: Timeout for the request in **seconds**
+
:return: Sandbox info
"""
...
@@ -473,62 +390,44 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
@staticmethod
async def get_info(
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
:param sandbox_id: Sandbox ID
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param domain: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable
- :param debug: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param headers: Custom headers to use for the request
- :param proxy: Proxy to use for the request
+
:return: Sandbox info
"""
...
@class_method_variant("_cls_get_info")
- async def get_info( # type: ignore
+ async def get_info(
self,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
- :param request_timeout: Timeout for the request in **seconds**
+
:return: Sandbox info
"""
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
-
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
-
- return await SandboxApi._cls_get_info(
+ return await self._cls_get_info(
sandbox_id=self.sandbox_id,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
@overload
- async def get_metrics( # type: ignore
+ async def get_metrics(
self,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
Get the metrics of the current sandbox.
:param start: Start time for the metrics, defaults to the start of the sandbox
- :param end: End time for the metrics, defaults to current time
- :param request_timeout: Timeout for the request in **seconds**
+ :param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
@@ -540,37 +439,31 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
sandbox_id: str,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
Get the metrics of the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
:param start: Start time for the metrics, defaults to the start of the sandbox
- :param end: End time for the metrics, defaults to current time
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
+ :param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
...
@class_method_variant("_cls_get_metrics")
- async def get_metrics( # type: ignore
+ async def get_metrics(
self,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
Get the metrics of the current sandbox.
:param start: Start time for the metrics, defaults to the start of the sandbox
- :param end: End time for the metrics, defaults to current time
- :param request_timeout: Timeout for the request in **seconds**
+ :param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
@@ -585,15 +478,9 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
"Disk metrics are not supported in this version of the sandbox, please rebuild the template to get disk metrics."
)
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
-
return await self._cls_get_metrics(
sandbox_id=self.sandbox_id,
start=start,
end=end,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index bddc6886c..c6330fec0 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -3,11 +3,11 @@ import urllib.parse
from typing import Optional, Dict, List
from packaging.version import Version
+from typing_extensions import Unpack
-
+from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
SandboxInfo,
- SandboxApiBase,
SandboxQuery,
ListedSandbox,
SandboxMetrics,
@@ -27,43 +27,25 @@ from e2b.api.client.api.sandboxes import (
post_sandboxes,
get_sandboxes_sandbox_id_metrics,
)
-from e2b.connection_config import ConnectionConfig, ProxyTypes
+from e2b.connection_config import ConnectionConfig, ApiParams
from e2b.api import handle_api_exception
-class SandboxApi(SandboxApiBase):
+class SandboxApi(SandboxBase):
@classmethod
async def list(
cls,
- api_key: Optional[str] = None,
query: Optional[SandboxQuery] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> List[ListedSandbox]:
"""
List all running sandboxes.
- :param api_key: API key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param query: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND.
- :param domain: Domain to use for the request, only relevant for self-hosted environments
- :param debug: Enable debug mode, all requested are then sent to localhost
- :param request_timeout: Timeout for the request in **seconds**
- :param headers: Additional headers to send with the request
- :param proxy: Proxy to use for the request
+ :param query: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters, they are combined with AND.
:return: List of running sandboxes
"""
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
# Convert filters to the format expected by the API
metadata = None
@@ -77,7 +59,7 @@ class SandboxApi(SandboxApiBase):
async with AsyncApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = await get_sandboxes.asyncio_detailed(
client=api_client,
@@ -111,37 +93,19 @@ class SandboxApi(SandboxApiBase):
async def _cls_get_info(
cls,
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get the sandbox info.
:param sandbox_id: Sandbox ID
- :param api_key: API key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param domain: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable
- :param debug: Debug mode, defaults to `E2B_DEBUG` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param headers: Additional headers to send with the request
- :param proxy: Proxy to use for the request
:return: Sandbox info
"""
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
async with AsyncApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = await get_sandboxes_sandbox_id.asyncio_detailed(
sandbox_id,
@@ -172,21 +136,9 @@ class SandboxApi(SandboxApiBase):
async def _cls_kill(
cls,
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
if config.debug:
# Skip killing the sandbox in debug mode
@@ -194,7 +146,7 @@ class SandboxApi(SandboxApiBase):
async with AsyncApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = await delete_sandboxes_sandbox_id.asyncio_detailed(
sandbox_id,
@@ -214,21 +166,9 @@ class SandboxApi(SandboxApiBase):
cls,
sandbox_id: str,
timeout: int,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> None:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
if config.debug:
# Skip setting the timeout in debug mode
@@ -236,7 +176,7 @@ class SandboxApi(SandboxApiBase):
async with AsyncApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = await post_sandboxes_sandbox_id_timeout.asyncio_detailed(
sandbox_id,
@@ -255,26 +195,14 @@ class SandboxApi(SandboxApiBase):
metadata: Optional[Dict[str, str]] = None,
env_vars: Optional[Dict[str, str]] = None,
secure: Optional[bool] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
allow_internet_access: Optional[bool] = True,
+ **opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
async with AsyncApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = await post_sandboxes.asyncio_detailed(
body=NewSandbox(
@@ -314,21 +242,18 @@ class SandboxApi(SandboxApiBase):
sandbox_id: str,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- headers=headers,
- request_timeout=request_timeout,
- proxy=proxy,
- )
+ """
+ Get the metrics of the sandbox specified by sandbox ID.
+
+ :param sandbox_id: Sandbox ID
+ :param start: Start time for the metrics, defaults to the start of the sandbox
+ :param end: End time for the metrics, defaults to the current time
+
+ :return: List of sandbox metrics containing CPU, memory and disk usage information
+ """
+ config = ConnectionConfig(**opts)
if config.debug:
# Skip getting the metrics in debug mode
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/command.py b/packages/python-sdk/e2b/sandbox_sync/commands/command.py
index b460a6c05..a2dea108b 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/command.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/command.py
@@ -34,7 +34,7 @@ class Commands:
# compressor=e2b_connect.GzipCompressor,
pool=pool,
json=True,
- headers=connection_config.headers,
+ headers=connection_config.sandbox_headers,
)
def list(
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/pty.py b/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
index 371a28a8f..bc9c7cd63 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
@@ -34,7 +34,7 @@ class Pty:
# compressor=e2b_connect.GzipCompressor,
pool=pool,
json=True,
- headers=connection_config.headers,
+ headers=connection_config.sandbox_headers,
)
def kill(
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index 56ac2421d..1add5b16f 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@ -51,7 +51,7 @@ class Filesystem:
# compressor=e2b_connect.GzipCompressor,
pool=pool,
json=True,
- headers=connection_config.headers,
+ headers=connection_config.sandbox_headers,
)
@overload
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index 412eb2569..1ee7c6f7b 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -5,12 +5,12 @@ import httpx
from typing import Dict, Optional, overload, List
from packaging.version import Version
+from typing_extensions import Unpack
from e2b.api.client.types import Unset
-from e2b.connection_config import ConnectionConfig, ProxyTypes
+from e2b.connection_config import ConnectionConfig, ApiParams
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, handle_envd_api_exception
from e2b.exceptions import SandboxException, format_request_timeout_error
-from e2b.sandbox.main import SandboxSetup
from e2b.sandbox.sandbox_api import SandboxMetrics
from e2b.sandbox.utils import class_method_variant
from e2b.sandbox_sync.filesystem.filesystem import Filesystem
@@ -32,8 +32,12 @@ class TransportWithLogger(httpx.HTTPTransport):
return response
+ @property
+ def pool(self):
+ return self._pool
+
-class Sandbox(SandboxSetup, SandboxApi):
+class Sandbox(SandboxApi):
"""
E2B cloud sandbox is a secure and isolated cloud environment.
@@ -77,38 +81,6 @@ class Sandbox(SandboxSetup, SandboxApi):
"""
return self._pty
- @property
- def sandbox_id(self) -> str:
- """
- Unique identifier of the sandbox.
- """
- return self._sandbox_id
-
- @property
- def sandbox_domain(self) -> str:
- """
- Domain where the sandbox is hosted.
- """
- return self._sandbox_domain
-
- @property
- def envd_api_url(self) -> str:
- return self._envd_api_url
-
- @property
- def _envd_access_token(self) -> str:
- """Private property to access the envd token"""
- return self.__envd_access_token
-
- @_envd_access_token.setter
- def _envd_access_token(self, value: Optional[str]):
- """Private setter for envd token"""
- self.__envd_access_token = value
-
- @property
- def connection_config(self) -> ConnectionConfig:
- return self._connection_config
-
def __init__(
self,
template: Optional[str] = None,
@@ -116,13 +88,9 @@ class Sandbox(SandboxSetup, SandboxApi):
metadata: Optional[Dict[str, str]] = None,
envs: Optional[Dict[str, str]] = None,
secure: Optional[bool] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- sandbox_id: Optional[str] = None,
- request_timeout: Optional[float] = None,
- proxy: Optional[ProxyTypes] = None,
allow_internet_access: Optional[bool] = True,
+ _sandbox_id: Optional[str] = None,
+ **opts: Unpack[ApiParams],
):
"""
Create a new sandbox.
@@ -130,113 +98,106 @@ class Sandbox(SandboxSetup, SandboxApi):
By default, the sandbox is created from the default `base` sandbox template.
:param template: Sandbox template name or ID
- :param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users
+ :param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param metadata: Custom metadata for the sandbox
:param envs: Custom environment variables for the sandbox
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param proxy: Proxy to use for the request and for the **requests made to the returned sandbox**
- :param allow_internet_access: Allow sandbox to access the internet, defaults to `True`
+ :param secure: Envd is secured with access token and cannot be used without it
+ :param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
- :return: sandbox instance for the new sandbox
+ :return: Sandbox instance for the new sandbox
"""
- super().__init__()
-
- if sandbox_id and (metadata is not None or template is not None):
+ if _sandbox_id and (metadata is not None or template is not None):
raise SandboxException(
"Cannot set metadata or timeout when connecting to an existing sandbox. "
"Use Sandbox.connect method instead.",
)
- connection_headers = {}
+ extra_sandbox_headers = {}
+
+ sandbox_domain: Optional[str] = None
+ envd_version: Optional[str] = None
+ envd_access_token: Optional[str] = None
+
+ debug = opts.get("debug")
if debug:
- self._sandbox_id = "debug_sandbox_id"
- self._sandbox_domain = None
- self._envd_version = None
- self._envd_access_token = None
- elif sandbox_id is not None:
- response = SandboxApi._cls_get_info(
- sandbox_id,
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- proxy=proxy,
+ _sandbox_id = "debug_sandbox_id"
+ elif _sandbox_id is not None:
+ response = self._cls_get_info(
+ _sandbox_id,
+ **opts,
)
- self._sandbox_id = sandbox_id
- self._sandbox_domain = response.sandbox_domain
- self._envd_version = response.envd_version
- self._envd_access_token = response._envd_access_token
+ envd_version = response.envd_version
+ sandbox_domain = response.sandbox_domain
+ envd_access_token = response._envd_access_token
- if response._envd_access_token is not None and not isinstance(
- response._envd_access_token, Unset
+ if envd_access_token is not None and not isinstance(
+ envd_access_token, Unset
):
- connection_headers["X-Access-Token"] = response._envd_access_token
+ extra_sandbox_headers["X-Access-Token"] = envd_access_token
else:
template = template or self.default_template
timeout = timeout or self.default_sandbox_timeout
- response = SandboxApi._create_sandbox(
+ response = self._create_sandbox(
template=template,
- api_key=api_key,
timeout=timeout,
metadata=metadata,
env_vars=envs,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
secure=secure or False,
- proxy=proxy,
allow_internet_access=allow_internet_access,
+ **opts,
)
+ _sandbox_id = response.sandbox_id
+ envd_version = response.envd_version
+ sandbox_domain = response.sandbox_domain
+ envd_access_token = response.envd_access_token
- self._sandbox_id = response.sandbox_id
- self._sandbox_domain = response.sandbox_domain
- self._envd_version = response.envd_version
-
- if response.envd_access_token is not None and not isinstance(
- response.envd_access_token, Unset
+ if envd_access_token is not None and not isinstance(
+ envd_access_token, Unset
):
- self._envd_access_token = response.envd_access_token
- connection_headers["X-Access-Token"] = response.envd_access_token
- else:
- self._envd_access_token = None
+ extra_sandbox_headers["X-Access-Token"] = envd_access_token
- self._transport = TransportWithLogger(limits=self._limits, proxy=proxy)
- self._connection_config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=connection_headers,
- proxy=proxy,
+ connection_config = ConnectionConfig(
+ extra_sandbox_headers=extra_sandbox_headers,
+ **opts,
)
- self._sandbox_domain = self._sandbox_domain or self._connection_config.domain
- self._envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
+ super().__init__(
+ sandbox_id=_sandbox_id,
+ envd_version=envd_version,
+ sandbox_domain=sandbox_domain,
+ envd_access_token=envd_access_token,
+ connection_config=connection_config,
+ )
+
+ proxy = opts.get("proxy")
+ self._transport = TransportWithLogger(limits=self._limits, proxy=proxy)
+
self._envd_api = httpx.Client(
base_url=self.envd_api_url,
transport=self._transport,
- headers=self.connection_config.headers,
+ headers=self.connection_config.sandbox_headers,
)
self._filesystem = Filesystem(
self.envd_api_url,
self._envd_version,
self.connection_config,
- self._transport._pool,
+ self._transport.pool,
self._envd_api,
)
+
self._commands = Commands(
self.envd_api_url,
self.connection_config,
- self._transport._pool,
+ self._transport.pool,
)
+
self._pty = Pty(
self.envd_api_url,
self.connection_config,
- self._transport._pool,
+ self._transport.pool,
)
def is_running(self, request_timeout: Optional[float] = None) -> bool:
@@ -279,20 +240,13 @@ class Sandbox(SandboxSetup, SandboxApi):
def connect(
cls,
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
):
"""
- Connects to an existing Sandbox.
- With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
+ Connect to an existing sandbox.
+ With a sandbox ID, you can connect to the same sandbox from different places or environments (serverless functions, etc.).
:param sandbox_id: Sandbox ID
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param proxy: Proxy to use for the request and for the **requests made to the returned sandbox**
-
- :return: sandbox instance for the existing sandbox
@example
```python
@@ -305,11 +259,8 @@ class Sandbox(SandboxSetup, SandboxApi):
"""
return cls(
- sandbox_id=sandbox_id,
- api_key=api_key,
- domain=domain,
- debug=debug,
- proxy=proxy,
+ _sandbox_id=sandbox_id,
+ **opts,
)
def __enter__(self):
@@ -319,12 +270,13 @@ class Sandbox(SandboxSetup, SandboxApi):
self.kill()
@overload
- def kill(self, request_timeout: Optional[float] = None) -> bool:
+ def kill(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> bool:
"""
Kill the sandbox.
- :param request_timeout: Timeout for the request in **seconds**
-
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
...
@@ -333,59 +285,46 @@ class Sandbox(SandboxSetup, SandboxApi):
@staticmethod
def kill(
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> bool:
"""
Kill the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param proxy: Proxy to use for the request
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
...
@class_method_variant("_cls_kill")
- def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
+ def kill(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> bool:
"""
- Kill the sandbox.
+ Kill the sandbox specified by sandbox ID.
- :param request_timeout: Timeout for the request
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
-
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
-
- SandboxApi._cls_kill(
+ return self._cls_kill(
sandbox_id=self.sandbox_id,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
@overload
def set_timeout(
self,
timeout: int,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> None:
"""
Set the timeout of the sandbox.
- After the timeout expires the sandbox will be automatically killed.
+ After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
- Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
+ The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param timeout: Timeout for the sandbox in **seconds**
- :param request_timeout: Timeout for the request in **seconds**
"""
...
@@ -394,54 +333,51 @@ class Sandbox(SandboxSetup, SandboxApi):
def set_timeout(
sandbox_id: str,
timeout: int,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> None:
"""
Set the timeout of the sandbox specified by sandbox ID.
- After the timeout expires the sandbox will be automatically killed.
+ After the timeout expires, the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
- Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
+ The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param sandbox_id: Sandbox ID
:param timeout: Timeout for the sandbox in **seconds**
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param proxy: Proxy to use for the request
"""
...
@class_method_variant("_cls_set_timeout")
- def set_timeout( # type: ignore
+ def set_timeout(
self,
timeout: int,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> None:
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
+ """
+ Set the timeout of the sandbox.
+ After the timeout expires, the sandbox will be automatically killed.
+ This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
+ The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- SandboxApi._cls_set_timeout(
+ :param timeout: Timeout for the sandbox in **seconds**
+
+ """
+
+ self._cls_set_timeout(
sandbox_id=self.sandbox_id,
timeout=timeout,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
@overload
def get_info(
self,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
- :param request_timeout: Timeout for the request in **seconds**
+
:return: Sandbox info
"""
...
@@ -450,61 +386,44 @@ class Sandbox(SandboxSetup, SandboxApi):
@staticmethod
def get_info(
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
+
:param sandbox_id: Sandbox ID
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param domain: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable
- :param debug: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param headers: Custom headers to use for the request
- :param proxy: Proxy to use for the request
+
:return: Sandbox info
"""
...
@class_method_variant("_cls_get_info")
- def get_info( # type: ignore
+ def get_info(
self,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get sandbox information like sandbox ID, template, metadata, started at/end at date.
- :param request_timeout: Timeout for the request in **seconds**
+
:return: Sandbox info
"""
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
-
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
-
- return SandboxApi._cls_get_info(
+ return self._cls_get_info(
sandbox_id=self.sandbox_id,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
@overload
- def get_metrics( # type: ignore
+ def get_metrics(
self,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
Get the metrics of the current sandbox.
:param start: Start time for the metrics, defaults to the start of the sandbox
- :param end: End time for the metrics, defaults to current time
- :param request_timeout: Timeout for the request in **seconds**
+ :param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
@@ -516,37 +435,31 @@ class Sandbox(SandboxSetup, SandboxApi):
sandbox_id: str,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
Get the metrics of the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
:param start: Start time for the metrics, defaults to the start of the sandbox
- :param end: End time for the metrics, defaults to current time
- :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param request_timeout: Timeout for the request in **seconds**
+ :param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
...
@class_method_variant("_cls_get_metrics")
- def get_metrics( # type: ignore
+ def get_metrics(
self,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- request_timeout: Optional[float] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
- Get the metrics of the current sandbox.
+ Get the metrics of the sandbox specified by sandbox ID.
:param start: Start time for the metrics, defaults to the start of the sandbox
- :param end: End time for the metrics, defaults to current time
- :param request_timeout: Timeout for the request in **seconds**
+ :param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
@@ -561,15 +474,9 @@ class Sandbox(SandboxSetup, SandboxApi):
"Disk metrics are not supported in this version of the sandbox, please rebuild the template to get disk metrics."
)
- config_dict = self.connection_config.__dict__
- config_dict.pop("access_token", None)
- config_dict.pop("api_url", None)
- if request_timeout:
- config_dict["request_timeout"] = request_timeout
-
return self._cls_get_metrics(
sandbox_id=self.sandbox_id,
start=start,
end=end,
- **config_dict,
+ **self.connection_config.get_api_params(**opts),
)
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 42dbe33ae..41d8117ad 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -3,14 +3,15 @@ import urllib.parse
from typing import Optional, Dict, List
from packaging.version import Version
+from typing_extensions import Unpack
from e2b.sandbox.sandbox_api import (
SandboxInfo,
- SandboxApiBase,
SandboxQuery,
ListedSandbox,
SandboxMetrics,
)
+from e2b.sandbox.main import SandboxBase
from e2b.exceptions import TemplateException, SandboxException
from e2b.api import ApiClient, SandboxCreateResponse
from e2b.api.client.models import (
@@ -26,43 +27,25 @@ from e2b.api.client.api.sandboxes import (
post_sandboxes,
get_sandboxes_sandbox_id_metrics,
)
-from e2b.connection_config import ConnectionConfig, ProxyTypes
+from e2b.connection_config import ConnectionConfig, ApiParams
from e2b.api import handle_api_exception
-class SandboxApi(SandboxApiBase):
+class SandboxApi(SandboxBase):
@classmethod
def list(
cls,
- api_key: Optional[str] = None,
query: Optional[SandboxQuery] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> List[ListedSandbox]:
"""
List all running sandboxes.
- :param api_key: API key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param query: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND.
- :param domain: Domain to use for the request, only relevant for self-hosted environments
- :param debug: Enable debug mode, all requested are then sent to localhost
- :param request_timeout: Timeout for the request in **seconds**
- :param headers: Additional headers to send with the request
- :param proxy: Proxy to use for the request
+ :param query: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters, they are combined with AND.
:return: List of running sandboxes
"""
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
# Convert filters to the format expected by the API
metadata = None
@@ -76,7 +59,7 @@ class SandboxApi(SandboxApiBase):
with ApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = get_sandboxes.sync_detailed(client=api_client, metadata=metadata)
@@ -107,36 +90,19 @@ class SandboxApi(SandboxApiBase):
def _cls_get_info(
cls,
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get the sandbox info.
:param sandbox_id: Sandbox ID
- :param api_key: API key to use for authentication, defaults to `E2B_API_KEY` environment variable
- :param domain: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable
- :param debug: Debug mode, defaults to `E2B_DEBUG` environment variable
- :param request_timeout: Timeout for the request in **seconds**
- :param headers: Additional headers to send with the request
:return: Sandbox info
"""
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
with ApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = get_sandboxes_sandbox_id.sync_detailed(
sandbox_id,
@@ -167,21 +133,9 @@ class SandboxApi(SandboxApiBase):
def _cls_kill(
cls,
sandbox_id: str,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
if config.debug:
# Skip killing the sandbox in debug mode
@@ -189,7 +143,7 @@ class SandboxApi(SandboxApiBase):
with ApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = delete_sandboxes_sandbox_id.sync_detailed(
sandbox_id,
@@ -209,21 +163,9 @@ class SandboxApi(SandboxApiBase):
cls,
sandbox_id: str,
timeout: int,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> None:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
if config.debug:
# Skip setting timeout in debug mode
@@ -231,7 +173,7 @@ class SandboxApi(SandboxApiBase):
with ApiClient(
config,
- limits=SandboxApiBase._limits,
+ limits=cls._limits,
) as api_client:
res = post_sandboxes_sandbox_id_timeout.sync_detailed(
sandbox_id,
@@ -250,24 +192,12 @@ class SandboxApi(SandboxApiBase):
metadata: Optional[Dict[str, str]] = None,
env_vars: Optional[Dict[str, str]] = None,
secure: Optional[bool] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
allow_internet_access: Optional[bool] = True,
+ **opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
-
- with ApiClient(config, limits=SandboxApiBase._limits) as api_client:
+ config = ConnectionConfig(**opts)
+
+ with ApiClient(config, limits=cls._limits) as api_client:
res = post_sandboxes.sync_detailed(
body=NewSandbox(
template_id=template,
@@ -306,21 +236,9 @@ class SandboxApi(SandboxApiBase):
sandbox_id: str,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
- api_key: Optional[str] = None,
- domain: Optional[str] = None,
- debug: Optional[bool] = None,
- request_timeout: Optional[float] = None,
- headers: Optional[Dict[str, str]] = None,
- proxy: Optional[ProxyTypes] = None,
+ **opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
- config = ConnectionConfig(
- api_key=api_key,
- domain=domain,
- debug=debug,
- request_timeout=request_timeout,
- headers=headers,
- proxy=proxy,
- )
+ config = ConnectionConfig(**opts)
if config.debug:
# Skip getting the metrics in debug mode
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py
index d3d8d2d4b..df5008ee7 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py
@@ -7,7 +7,7 @@ from e2b import Sandbox
@pytest.mark.skip_debug()
-async def test_download_url_with_signing(template):
+def test_download_url_with_signing(template):
sbx = Sandbox(template, timeout=100, secure=True)
file_path = "test_download_url_with_signing.txt"
file_content = "This file will be watched."
@@ -26,7 +26,7 @@ async def test_download_url_with_signing(template):
@pytest.mark.skip_debug()
-async def test_download_url_with_signing_and_expiration(template):
+def test_download_url_with_signing_and_expiration(template):
sbx = Sandbox(template, timeout=100, secure=True)
file_path = "test_download_url_with_signing.txt"
file_content = "This file will be watched."
@@ -45,7 +45,7 @@ async def test_download_url_with_signing_and_expiration(template):
@pytest.mark.skip_debug()
-async def test_download_url_with_expired_signing(template):
+def test_download_url_with_expired_signing(template):
sbx = Sandbox(template, timeout=100, secure=True)
file_path = "test_download_url_with_signing.txt"
file_content = "This file will be watched."