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; |
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 |
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 |
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
- _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 |
PYTHON
|
additional_packages
|
list[str] | None
|
Packages to install into the sandbox once it is
ready, with pip. Installed once through |
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 |
None
|
on_stdout
|
Callable[[str], None] | None
|
Called with each stdout line (a |
None
|
on_stderr
|
Callable[[str], None] | None
|
Called with each stderr line (a |
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
|
Returns:
| Name | Type | Description |
|---|---|---|
ExecutionResult |
ExecutionResult
|
Result of the command execution. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the method is not implemented in the subclass. |
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. |
ExecutionResult
Bases: BaseModel
Structured result of code execution.
failure = None
class-attribute
instance-attribute
Set only when a caught exception adds something status does not already say.
create(status, code, stdout='', stderr='', error='', duration_ms=None, failure=None)
classmethod
Create ExecutionResult with common parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status
|
ExecutionStatus
|
Execution status. |
required |
code
|
str
|
Original code that was executed. |
required |
stdout
|
str
|
Standard output from execution. Defaults to "". |
''
|
stderr
|
str
|
Standard error from execution. Defaults to "". |
''
|
error
|
str
|
Error message if execution failed. Defaults to "". |
''
|
duration_ms
|
int | None
|
Execution duration in milliseconds. Defaults to None. |
None
|
failure
|
FailureDetail | None
|
Extra structured failure detail, when a caught
exception adds something |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ExecutionResult |
ExecutionResult
|
Configured execution result. |
ExecutionStatus
Bases: Enum
Status of code execution.
UNKNOWN is distinct from ERROR: ERROR means the outcome is known — either the
code ran and failed, or it provably never ran at all — while UNKNOWN means the transport
broke after the request was delivered, so whether the code ran cannot be determined. Callers
must not retry an UNKNOWN execution — the code may already have run, with side effects.
Where an ERROR is known to have run nothing, failure.retry_safe says so.
TIMEOUT carries the same warning. It covers an execution that overran its budget, a
request that never came back, and a sandbox killed mid-request — in every case the code may
already have run, so a TIMEOUT must not be retried automatically either. No
FailureDetail is attached because the status alone carries that meaning.
Every backend classifies its own transport failures, because only it knows which of its
SDK's exceptions prove the request was never written. What they share is the direction they
fail in: an unrecognised failure reports UNKNOWN, never ERROR, so a gap in
classification leaves a caller cautious rather than confidently wrong.
FailureDetail
Bases: BaseModel
Extra structured detail about a failed execution, when there is any to add.
Exists so consumers can branch on values rather than parsing error text. None whenever
nothing can be added beyond status — a success, a failure the sandbox reported normally
(a program error, a nonzero exit) with no exception to classify, a timeout, or a failure
raised before anything was submitted.
Presence is not yet uniform across backends for one case: a request the sandbox answered and
refused. BedrockAgentCoreSandbox attaches retry_safe=True there, because a throttle or
a transient rejection is worth retrying; OpenSandbox still returns None for its
equivalent arm. A consumer should therefore treat a missing detail as "no claim either way",
never as "not retry-safe" — the guard is if result.failure and result.failure.retry_safe,
which already fails closed.
Whether the response body arrived complete is deliberately not reported: neither httpx nor
pyqwest exposes HTTP framing state to Python, and E2B's execution stream carries no terminal
event, so it cannot be determined at this layer. That is a limit of what the transport
surfaces rather than a property of the problem — the framing state exists in the Rust stack
below, it simply does not reach Python — so this could change if pyqwest ever exposed it.
A retry_safe=False outcome therefore always means "the sandbox may or may not have run
this".
exception_type
instance-attribute
Qualified exception name, e.g. httpx.ReadError.
retry_safe
instance-attribute
True only when the request was provably never written, so a retry cannot duplicate work.
SandboxExecutionError(message, *, stage, classifier=None)
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 |
{}
|
SandboxStartError(message, *, stage, classifier=None)
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.