API Reference
Sandbox Class
The main class for creating and managing sandboxes.
Class Methods
Sandbox.create()
Creates a new sandbox instance.
@classmethod
def create(
variant: str = "local-eval",
timeout: float | None = None,
environment: str | None = None,
gpu: str | None = None,
cpu: float | None = None,
memory: int | None = None,
env: dict[str, str] | None = None,
tags: dict[str, str] | None = None,
name: str | None = None,
snapshot_name: str | None = None,
config: SandboxConfig | None = None,
) -> Sandbox
Parameters:
| Parameter | Type | Description |
|---|---|---|
variant | str | Sandbox type: "local-eval", "local-docker", "local-jupyter", or "datalayer-runtime" |
timeout | float | Execution timeout in seconds |
environment | str | Runtime environment name |
gpu | str | GPU type (e.g., "T4", "A100", "H100") |
cpu | float | Number of CPU cores |
memory | int | Memory in MB |
env | dict | Environment variables |
tags | dict | Metadata tags |
name | str | Sandbox name |
snapshot_name | str | Snapshot to restore from |
config | SandboxConfig | Full configuration object |
Sandbox.from_id()
Reconnects to an existing sandbox.
@classmethod
def from_id(sandbox_id: str, variant: str = "datalayer-runtime") -> Sandbox
Sandbox.list()
Lists all sandboxes.
@classmethod
def list(variant: str = "datalayer-runtime") -> list[SandboxInfo]
Sandbox.list_environments()
Lists available environments for a sandbox variant.
@classmethod
def list_environments(
variant: str = "datalayer-runtime",
**kwargs,
) -> list[SandboxEnvironment]
Parameters:
| Parameter | Type | Description |
|---|---|---|
variant | str | Sandbox type: "local-eval", "local-docker", "local-jupyter", or "datalayer-runtime" |
**kwargs | dict | Variant-specific arguments (e.g., credentials, run URL) |
Instance Methods
run_code()
Executes Python code in the sandbox.
def run_code(
code: str,
language: str = "python",
context: Context | None = None,
on_stdout: Callable[[OutputMessage], None] | None = None,
on_stderr: Callable[[OutputMessage], None] | None = None,
on_result: Callable[[Result], None] | None = None,
on_error: Callable[[CodeError], None] | None = None,
envs: dict[str, str] | None = None,
timeout: float | None = None,
) -> ExecutionResult
start()
Starts the sandbox.
def start() -> None
stop()
Stops the sandbox gracefully.
def stop() -> None
terminate()
Terminates the sandbox.
def terminate() -> None
kill()
Force kills the sandbox.
def kill() -> None
set_timeout()
Updates the sandbox timeout.
def set_timeout(timeout: float) -> None
Properties
| Property | Type | Description |
|---|---|---|
sandbox_id | str | Unique sandbox identifier |
files | SandboxFilesystem | Filesystem interface |
commands | SandboxCommands | Command execution interface |
tags | dict[str, str] | Metadata tags |
SandboxFilesystem
File operations interface.
Methods
read()
def read(path: str) -> str
Reads file contents as a string.
read_bytes()
def read_bytes(path: str) -> bytes
Reads file contents as bytes.
write()
def write(path: str, content: str | bytes) -> None
Writes content to a file.
list()
def list(path: str) -> list[FileInfo]
Lists directory contents.
mkdir()
def mkdir(path: str, parents: bool = True) -> None
Creates a directory.
rm()
def rm(path: str, recursive: bool = False) -> None
Removes a file or directory.
upload()
def upload(local_path: str, remote_path: str) -> None
Uploads a local file to the sandbox.
download()
def download(remote_path: str, local_path: str) -> None
Downloads a file from the sandbox.
SandboxCommands
Command execution interface.
Methods
run()
def run(
command: str,
timeout: float | None = None,
cwd: str | None = None,
env: dict[str, str] | None = None,
) -> CommandResult
Runs a command and waits for completion.
exec()
def exec(*args: str, **kwargs) -> ProcessHandle
Executes a command with streaming output.
spawn()
def spawn(command: str, **kwargs) -> ProcessHandle
Starts a background process.
Data Models (Pydantic)
ExecutionResult
Complete result of a code execution with detailed status information.
class ExecutionResult(BaseModel):
# Results and logs
results: list[Result]
logs: Logs
# Execution-level (infrastructure) status
execution_ok: bool = True # Did sandbox infrastructure work?
execution_error: str | None = None # Infrastructure failure details
# Code-level (user code) status
code_error: CodeError | None = None # Python exception info
# Process exit status (sys.exit)
exit_code: int | None = None # Exit code if code calls sys.exit()
# Metadata
execution_count: int = 0
context_id: str | None = None
started_at: float | None = None
completed_at: float | None = None
interrupted: bool = False
# Properties
@property
def success(self) -> bool:
"""True if execution_ok and no code_error and not interrupted and exit_code is 0 or None"""
@property
def duration(self) -> float | None:
"""Execution duration in seconds"""
@property
def text(self) -> str | None:
"""Main text result"""
@property
def stdout(self) -> str:
"""All stdout as single string"""
@property
def stderr(self) -> str:
"""All stderr as single string"""
Usage:
result = sandbox.run_code("x = 1 + 1; print(x)")
# Check infrastructure success
if not result.execution_ok:
print(f"Sandbox failed: {result.execution_error}")
# Check explicit process exit
elif result.exit_code not in (None, 0):
print(f"Process exited with code: {result.exit_code}")
# Check code-level error
elif result.code_error:
print(f"Python error: {result.code_error.name}: {result.code_error.value}")
# Success!
else:
print(f"Result: {result.text}")
print(f"Duration: {result.duration:.2f}s")
# Or use convenience property
if result.success:
print("Everything worked!")
CodeError
Error information when Python code raises an exception.
class CodeError(BaseModel):
name: str # Error class name (e.g., "ValueError")
value: str # Error message
traceback: str # Full traceback
SandboxEnvironment
class SandboxEnvironment(BaseModel):
name: str
title: str
language: str = "python"
owner: str = "local"
visibility: str = "local"
burning_rate: float = 0.0
metadata: dict[str, Any] | None = None
Result
A single execution result with multiple representations.
class Result(BaseModel):
data: dict[str, Any] # MIME type to content mapping
is_main_result: bool = False
extra: dict[str, Any] # Additional metadata
# Convenience properties
@property
def text(self) -> str | None: ... # text/plain
@property
def html(self) -> str | None: ... # text/html
@property
def json(self) -> Any: ... # application/json
@property
def png(self) -> str | None: ... # image/png (base64)
OutputMessage
class OutputMessage(BaseModel):
line: str
timestamp: float = 0.0
error: bool = False # True for stderr
Logs
class Logs(BaseModel):
stdout: list[OutputMessage]
stderr: list[OutputMessage]
@property
def stdout_text(self) -> str: ... # All stdout as string
@property
def stderr_text(self) -> str: ... # All stderr as string
Context
class Context(BaseModel):
id: str
language: str = "python"
cwd: str | None = None
env: dict[str, str]
SandboxConfig
class SandboxConfig(BaseModel):
timeout: float = 30.0
memory_limit: int | None = None
cpu_limit: float | None = None
environment: str = "python-cpu-env"
working_dir: str | None = None
env_vars: dict[str, str]
gpu: str | None = None
name: str | None = None
network_policy: str = "inherit" # "inherit", "none", "allowlist", "all"
allowed_hosts: list[str]
idle_timeout: float | None = None
max_lifetime: float = 86400.0 # 24 hours
SandboxInfo
class SandboxInfo(BaseModel):
id: str
variant: str
status: SandboxStatus = SandboxStatus.RUNNING
created_at: float = 0.0
end_at: float | None = None
config: SandboxConfig | None = None
name: str | None = None
metadata: dict[str, Any]
resources: ResourceConfig | None = None
@property
def remaining_time(self) -> float | None: ... # Seconds until termination
ResourceConfig
class ResourceConfig(BaseModel):
cpu: float | None = None # CPU cores
memory: int | None = None # Memory in MB
gpu: str | None = None # GPU type ("T4", "A100", etc.)
gpu_count: int = 1 # Number of GPUs
disk: int | None = None # Disk in GB
Exceptions
| Exception | Description |
|---|---|
SandboxError | Base exception for all sandbox errors |
SandboxNotFoundError | Sandbox not found |
SandboxTimeoutError | Execution timed out |
SandboxExecutionError | Code execution failed |
SandboxConnectionError | Connection to sandbox failed |
SandboxNotRunningError | Sandbox is not running |
SandboxFilesystemError | Filesystem operation failed |
SandboxCommandError | Command execution failed |
SandboxSnapshotError | Snapshot operation failed |
SandboxResourceError | Resource limit exceeded |
SandboxAuthenticationError | Authentication failed |
SandboxQuotaExceededError | Usage quota exceeded |