Skip to main content

title: "GMI Sandbox SDK Usage" description: "Install, configure, and use the GMI Sandbox Python SDK."

GMI Sandbox SDK Usage

Install

python -m pip install gmi-sandbox-sdk

Configure

Use environment variables or pass values directly.

To get an API key, log in to https://console.gmicloud.ai/, click API keys, select compute, and click Create API key.

export GMI_SANDBOX_API_KEY="your-api-key"

Set GMI_SANDBOX_IDC_NAME (or pass idc_name) to choose the IDC for creating sandboxes and templates and for listing product specifications. You can leave it unset only if your organization has a default IDC configured; otherwise those requests return 400 idc_name is required:

export GMI_SANDBOX_IDC_NAME="gmi-sandbox-us"

Create a client

from sandbox_sdk import SandboxClient

client = SandboxClient()

You can also pass credentials explicitly:

client = SandboxClient(
    api_key="your-api-key",
)

Async client

AsyncSandboxClient provides the same resources and operations with native async HTTP I/O. Use it as an async context manager so pooled connections are closed automatically:

from sandbox_sdk import AsyncSandboxClient

async with AsyncSandboxClient() as client:
    sandbox = await client.sandboxes.create(template_id="template-id")
    await sandbox.connect()
    result = await sandbox.commands.run("echo hello", wait=True)
    print(result.stdout)
    await sandbox.files.write("/tmp/hello.txt", "hello")
    await sandbox.delete()

When not using an async context manager, call await client.aclose() after the client is no longer needed. aclose() closes only the HTTP client the SDK created for you; a transport you pass in stays open and remains yours to close. Requests issued after aclose() raise TransportError, so create a new client instead of reusing a closed one.

Both clients only send requests to http and https URLs, and they validate every redirect hop against that rule. This is a scheme check: it does not restrict which hosts a base_url you configure can reach.

Create and use a sandbox

sandbox = client.sandboxes.create(
    template_id="template-id",
)

sandbox.connect()
result = sandbox.commands.run("echo hello", wait=True)
print(result.stdout)

sandbox.files.write("/tmp/hello.txt", "hello")
print(sandbox.files.read("/tmp/hello.txt").decode())

sandbox.delete()

If you already have a sandbox ID:

sandbox = client.sandboxes.get("sandbox-id")
sandbox.connect()

Files

sandbox.files.read("/tmp/a.txt")
sandbox.files.write("/tmp/a.txt", "hello")
sandbox.files.write("/tmp/a.bin", b"binary-data")
sandbox.files.upload("./local.txt", "/workspace/local.txt")
sandbox.files.download("/workspace/output.txt", "./output.txt")

read() and download() buffer the complete response in memory. download() returns bytes and can also write to a destination path; use its byte_range argument to retrieve large files in chunks.

Commands

execution = sandbox.commands.run(
    "python --version",
    cwd="/workspace",
    envs={"PYTHONUNBUFFERED": "1"},
    wait=True,
    wait_timeout_seconds=25,
)

print(execution.status)
print(execution.exit_code)
print(execution.stdout)
print(execution.stderr)

stdout and stderr are each capped at 1 MiB. Check execution.stdout_truncated (and stderr_truncated); for large output, write to a file and download it.

You can refresh or cancel a running execution:

execution.refresh()
execution.cancel()

Snapshots

Prepare a sandbox once, save it as a snapshot, and launch new sandboxes from it:

base = client.sandboxes.create(template_id="template-id", timeout=900)
base.wait_until_running()
base.connect()
base.commands.run(
    "npm i -g @anthropic-ai/claude-code", execution_timeout_seconds=600
).wait(timeout=600)

snapshot = base.create_snapshot(name="agent-base")
snapshot.wait_until_ready()

worker = client.sandboxes.create(snapshot_id=snapshot.snapshot_id, timeout=900)
worker.wait_until_running()
worker.connect()

Sizing is inherited from the snapshot. Environment variables passed with env_vars are not part of a snapshot; pass them again on each create. Clean up caches and credentials before taking a snapshot.

client.snapshots.list(source_sandbox_id=base.sandbox_id)
snapshot.update(name="agent-base-v2")
snapshot.delete()   # delete sandboxes launched from it first, or this raises ConflictError

Pause and resume

sandbox.pause()      # state becomes paused
sandbox.resume()     # cold start; pass timeout= to reset the lifetime
sandbox.wait_until_running()
sandbox.connect()    # reconnect before data-plane calls

A paused sandbox keeps its disk files except /tmp; memory and running processes are not kept.

Templates

template = client.templates.get("template-id")
template.update(name="new-name")
template.delete()

builds = template.builds()
build = template.build("build-id")
logs = template.build_logs("build-id", offset=0, limit=100)

Creating a template requires an idempotency key:

template = client.templates.create(
    name="demo",
    resources={"type": "preset", "product": "gmi.sandbox.small"},
    build={"source": {"type": "image", "image": "ubuntu:22.04"}},
    idempotency_key="template-1",
)

print(template.template_id)
template.update(name="new-name")

Create from a Dockerfile and local build context:

from pathlib import Path

template = client.templates.create(
    name="dockerfile-demo",
    resources={"type": "preset", "product": "gmi.sandbox.small"},
    dockerfile_content=Path("Dockerfile").read_text(),
    build_context_dir=".",
    idempotency_key="template-dockerfile-1",
)

The live API accepts one uploaded context archive. The SDK translates COPY . <destination> and ADD . <destination> to the API's Template-file reference syntax. Other local source forms are rejected before a request is sent. AsyncSandboxClient.templates.create() accepts the same arguments.

Choose the runtime user of sandboxes launched from a Build with default_user (for example default_user={"username": "root"}). It is applied after all build steps, so it overrides the Dockerfile's final USER; it does not change the working directory, which still comes from the Dockerfile's WORKDIR (/home/user when omitted). templates.create() and templates.builds.create() accept it with either build= or dockerfile_content=.

Rebuild an existing template without replacing it with client.templates.builds.create(template.template_id, dockerfile_content=..., build_context_dir=..., start_cmd=..., idempotency_key=...); the async client exposes the same call and returns the newly created build, while template.wait_until_ready() remains the readiness helper.

Product specifications

client.product_specifications.list(idc_name="gmi-sandbox-us")

Errors

The SDK raises typed exceptions for HTTP failures:

  • BadRequestError
  • AuthenticationError
  • PermissionDeniedError
  • NotFoundError
  • ConflictError
  • RateLimitError
  • ServerError

Example:

from sandbox_sdk import NotFoundError

try:
    client.sandboxes.get("missing")
except NotFoundError:
    print("sandbox not found")

Metadata

Release files for gmi-sandbox-sdk 1.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gmi-sandbox-sdk 1.2.1
File Size Uploaded Provenance Actions
gmi_sandbox_sdk-1.2.1.tar.gz 32.3 kB Without provenance Details for gmi_sandbox_sdk-1.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gmi-sandbox-sdk 1.2.1
File Interpreter ABI Platform Actions
gmi_sandbox_sdk-1.2.1-py3-none-any.whl Python 3 none any Details for gmi_sandbox_sdk-1.2.1-py3-none-any.whl

Total release size: 63.4 kB

Release files / gmi_sandbox_sdk-1.2.1.tar.gz

Download URL gmi_sandbox_sdk-1.2.1.tar.gz
Size 32.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9978d1abe295850959cb1ab4fed1adf9f032db38f99ae044dc85e725a0a8a00c
BLAKE2b-256 checksum
How to use checksums
2f48ad1ef6a02e3a3321fb3dd8866b6f1fd52fb4e20d0cac79ec1a1ab6ab9558
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Release files / gmi_sandbox_sdk-1.2.1-py3-none-any.whl

Download URL gmi_sandbox_sdk-1.2.1-py3-none-any.whl
Size 31.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
28938d98383c18f5d4837c959b1f8f0b0c14ff9e22288d172379849ba27439ef
BLAKE2b-256 checksum
How to use checksums
b1c6c766288e2c3bf40c0de1862c97f4170b819dc02d36cee3798df125a4513a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Security for gmi-sandbox-sdk 1.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page