Skip to main content
The Sandbox class is the main entry point to OpenSandbox. It supports both manual lifecycle management and async context managers.

Creating a Sandbox

from opensandbox import Sandbox

sandbox = await Sandbox.create(
    template='base',
    timeout=300,
    envs={'NODE_ENV': 'production'},
    metadata={'owner': 'my-agent'},
)

Sandbox.create(**kwargs)

Creates a new sandbox and returns a connected Sandbox instance.
template
str
default:"base"
Container template to use.
timeout
int
default:"300"
Sandbox time-to-live in seconds.
api_key
str | None
default:"None"
API key. Falls back to OPENSANDBOX_API_KEY env var.
api_url
str | None
default:"None"
API base URL. Falls back to OPENSANDBOX_API_URL env var, then https://app.opensandbox.ai.
envs
dict[str, str] | None
default:"None"
Environment variables injected into the sandbox.
metadata
dict[str, str] | None
default:"None"
Arbitrary key-value metadata attached to the sandbox.
Returns: Sandbox

Async Context Manager

The recommended way to use sandboxes in Python — the sandbox is automatically killed when the block exits:
async with Sandbox.create(template='base') as sandbox:
    result = await sandbox.commands.run('echo "hello"')
    print(result.stdout)
# sandbox is automatically killed here

Connecting to an Existing Sandbox

sandbox = await Sandbox.connect(
    'sandbox-abc123',
    api_key='sk-...',
)

Sandbox.connect(sandbox_id, **kwargs)

Connects to a running sandbox by ID.
sandbox_id
str
required
The ID of the sandbox to connect to.
api_key
str | None
default:"None"
API key override.
api_url
str | None
default:"None"
API URL override.
Returns: Sandbox

Properties

PropertyTypeDescription
sandbox_idstrUnique identifier for the sandbox
statusstrCurrent status: "running", "stopped", or "error"
templatestrTemplate used to create the sandbox
filesFilesystemFilesystem operations
commandsCommandsCommand execution
ptyPtyPTY terminal access

Instance Methods

await sandbox.kill()

Stops and destroys the sandbox.
await sandbox.kill()
Returns: None

await sandbox.is_running()

Checks if the sandbox is still alive.
if not await sandbox.is_running():
    print('Sandbox has stopped')
Returns: bool

await sandbox.set_timeout(timeout)

Updates the sandbox timeout. Resets the TTL countdown.
# Extend for another 10 minutes
await sandbox.set_timeout(600)
timeout
int
required
New timeout in seconds.
Returns: None

sandbox.close()

Closes the underlying HTTP client connections without killing the sandbox.
sandbox.close()
Returns: None