Skip to content

Code Sandbox

GLLM Tools Code Interpreter Sandbox module.

BaseSandbox(**kwargs)

Bases: ABC

Base class for sandbox environments.

Defines the generic sandbox lifecycle contract (creation-retry classification, termination, file transfer) shared by all backends. Code-execution concerns (execute_code, language, result formatting) live in CodeInterpreterSandbox.

Initialize the sandbox.

Parameters:

Name Type Description Default
**kwargs Any

Additional initialization parameters, ignored by the base.

{}

download_file(file_path, *, timeout=DEFAULT_DOWNLOAD_TIMEOUT) abstractmethod async

Download file content from the sandbox.

Parameters:

Name Type Description Default
file_path str

Path to the file in the sandbox.

required
timeout float

Client-side cap in seconds on the transfer. A positive value enforces that many seconds; <= 0 runs unbounded. Optional; the concrete default is provider-specific.

DEFAULT_DOWNLOAD_TIMEOUT

Returns:

Type Description
bytes | None

bytes | None: File content as bytes, or None if download fails -- a timeout included.

Raises:

Type Description
NotImplementedError

If the method is not implemented in the subclass.

terminate(*, timeout=DEFAULT_SANDBOX_KILL_TIMEOUT_SECONDS) abstractmethod async

Terminate the sandbox environment and clean up resources.

Parameters:

Name Type Description Default
timeout float

Client-side cap in seconds on the whole teardown, retries included. Must be positive. Optional; the concrete default is provider-specific.

DEFAULT_SANDBOX_KILL_TIMEOUT_SECONDS

Raises:

Type Description
NotImplementedError

If the method is not implemented in the subclass.

ValueError

If timeout is not positive.

SandboxTerminateError

If the sandbox could not be torn down. Backends that raise this keep their handle, so the caller can retry rather than leak a live sandbox.

CodeInterpreterError(message, *, stage, classifier=None)

Bases: RuntimeError

Base class for every stage-attributed code_interpreter failure.

Subclasses RuntimeError deliberately: every failure this taxonomy replaces was raised as a bare RuntimeError before, so existing except RuntimeError callers keep working while new callers can except CodeInterpreterError and branch on stage / transient.

Attributes:

Name Type Description
stage Stage

The SDLC stage at which the failure occurred.

Initialize the error with a stage and an optional transience classifier.

Parameters:

Name Type Description Default
message str

Human-readable, user-facing message.

required
stage Stage

The stage at which the failure occurred.

required
classifier TransientClassifier | None

A reference to the transient predicate to apply across the __cause__ chain. Defaults to None, which resolves to BaseSandbox._is_transient_create_error (#5418). This is a reference to the single source of truth, never a second classifier or a stored boolean.

None

transient property

Whether this failure is transient and worth retrying.

Walks this error and its __cause__ chain, applying #5418's classifier. No parallel classification and no stored flag — the verdict is derived on read.

Returns:

Name Type Description
bool bool

True if any exception in the chain is classified transient.

CodeInterpreterSandbox(language=Language.PYTHON, additional_packages=None, **kwargs)

Bases: BaseSandbox

Extended sandbox interface for backends that support shell commands and lifecycle control.

Extends BaseSandbox with: - execute_command: shell command execution - set_timeout: session lease renewal - sandbox_id: instance identification - reset_transport: provider-held SDK transport cleanup (no-op by default) - _setup_python_channels: install additional_packages, or skip for a non-Python sandbox - _install_additional_packages: language-aware package install over the kernel channel

Attributes:

Name Type Description
language str

Programming language for the sandbox.

additional_packages list[str]

Packages to install into the running sandbox.

Initialize the sandbox with its language and the packages to install into it.

Parameters:

Name Type Description Default
language str

Programming language for the sandbox. Also selects the package manager used for additional_packages. Defaults to Language.PYTHON.

PYTHON
additional_packages list[str] | None

Packages to install into the sandbox once it is ready, with pip. Installed once through execute_code, into the kernel interpreter; execute_command reaches the same packages on any image whose two channels share a site-packages. Automatic installs cover Python only; a non-Python sandbox skips the install with a warning and is still created, so its packages must be installed manually via execute_command(...). A failed install aborts creation and tears the sandbox down. Defaults to None.

None
**kwargs Any

Additional initialization parameters.

{}

sandbox_id abstractmethod property

Return the unique sandbox session/instance identifier.

Returns:

Type Description
str | None

str | None: Identifier string, or None if not yet started.

Raises:

Type Description
NotImplementedError

If the property is not implemented in the subclass.

execute_code(code, timeout=None, files=None, upload_dir=None, on_stdout=None, on_stderr=None, **kwargs) abstractmethod async

Execute code in the sandbox environment, optionally streaming its output.

Parameters:

Name Type Description Default
code str

The code to execute.

required
timeout int | None

Maximum execution time in seconds. Defaults to None.

None
files list[Attachment] | None

Files to upload before execution. Defaults to None.

None
upload_dir str | None

Directory to upload files into. Defaults to None.

None
on_stdout Callable[[str], None] | None

Called with each stdout line (a str) as it streams from the running code. Best-effort: backends that cannot stream (e.g. Bedrock) accept the callback but never invoke it. Defaults to None.

None
on_stderr Callable[[str], None] | None

Called with each stderr line (a str) as it streams. Same best-effort semantics as on_stdout. Defaults to None.

None
**kwargs Any

Additional execution parameters.

{}

Returns:

Name Type Description
ExecutionResult ExecutionResult

Structured result of the execution.

Raises:

Type Description
NotImplementedError

If the method is not implemented in the subclass.

execute_command(cmd, *, env=None, timeout=None) abstractmethod async

Execute a shell command in the sandbox.

Parameters:

Name Type Description Default
cmd str

Shell command to run.

required
env dict[str, str] | None

Optional environment variables. Defaults to None.

None
timeout float | None

Command timeout in seconds. None (the default) uses the backend default of 30s; <= 0 disables the timeout; a positive value enforces it. Defaults to None.

None

Returns:

Name Type Description
ExecutionResult ExecutionResult

Result of the command execution.

Raises:

Type Description
NotImplementedError

If the method is not implemented in the subclass.

reset_transport()

Reset provider-held SDK transport state between sandbox lifecycles.

Default is a no-op. Override in providers whose SDK caches transport state across sandbox instances (e.g. E2B's process-global async transport, which binds to the event loop alive when it was created). Implementations must never raise.

set_timeout(seconds) abstractmethod async

Renew or adjust the sandbox session timeout.

Backends that do not support dynamic timeout should implement this as a no-op (do not raise).

Parameters:

Name Type Description Default
seconds int

New timeout in seconds.

required

Raises:

Type Description
NotImplementedError

If the method is not implemented in the subclass.

SandboxExecutionError(message, *, stage, classifier=None)

Bases: CodeInterpreterError

Code/command execution or package installation failed after start.

SandboxNotInitializedError(message='Sandbox is not initialized', **kwargs)

Bases: CodeInterpreterError

An operation was attempted before the sandbox was initialized/started.

Initialize with the shared not-initialized message and NOT_INITIALIZED stage.

Parameters:

Name Type Description Default
message str

Human-readable message. Defaults to "Sandbox is not initialized".

'Sandbox is not initialized'
**kwargs Any

Forwarded to CodeInterpreterError (e.g. classifier).

{}

SandboxStartError(message, *, stage, classifier=None)

Bases: CodeInterpreterError

A sandbox failed to start, attributed to the specific start stage.

SandboxTerminateError(message, *, stage, classifier=None)

Bases: CodeInterpreterError

Teardown failed after every retry (stage is TERMINATE).

Replaces the provider SDK's raw exception, which is preserved as __cause__. The sandbox may still be alive on the server, so providers keep their handle for the caller to retry.

Stage

Bases: StrEnum

The stage of the code_interpreter SDLC at which a failure occurred.

The string value doubles as the error.code field in JSON logs (via extra={"error_code": stage}), so keep the values stable and queryable.

TemplateBuildError(message, *, stage, classifier=None)

Bases: CodeInterpreterError

A template build/ensure failed (stage is typically TEMPLATE_BUILD).