Skip to main content

guplet-sdk — the Python SDK of guplet

Thin client of the gup API (ARCHITECTURE.md D-23, REQUIREMENTS.md PR-12). Python ≥ 3.9. One install gives the sync guplet.Client and the asyncio guplet.AsyncClient (below, D-89); its one dependency is httpx.

Install

pip install guplet-sdk          # from PyPI (https://pypi.org/project/guplet-sdk/); the API URL is built in

From a checkout of this repository: scripts/build-sdk.sh (stamps the API URL and installs into the active venv).

Get a team API key from the console (API keys page; shown once) or, as the operator, scripts/supabase-seed.sh --api-key <team>. The public API cannot mint keys.

Use

import guplet

client = guplet.Client()                           # key: api_key= > GUPLET_TOKEN > GUPLET_API_KEY_FILE; URL: api= > GUPLET_API > built in

# A gup is created from an image (`os`: one of client.catalog().os, or a team template) at a size.
# There is no type to give: the image name decides what the gup is.
with client.create(os="toolbox", size="s", ttl=600) as gup:   # deleted at the end of the block
    gup.wait()                                                # phase Running (polls every 2 s)
    r = gup.run("python3 -c 'print(6*7)'", cwd="/tmp", env={"A": "1"}, timeout=60)
    print(r.stdout, r.exit_code)                              # "42\n" 0
    print(gup.port_url(8080))                                 # https://8080-<id>.<domain>

vm = client.create(os="ubuntu-24.04", size="s", ttl=900, wait=True)   # the API holds the
# response until the gup is Running (a warm slot answers in under a second); without wait=True, vm.wait() polls
for stream, text in vm.run_stream("for i in 1 2 3; do echo $i; sleep 1; done"):
    print(stream, text, end="")
vm.pause(wait=True); vm.resume(wait=True)
snap = vm.snapshot()
vm.kill()

vm.pause() acknowledges an asynchronous pause. Refresh to read vm.pause_status: frozenAt confirms execution and compute billing have stopped; stage, mode, attempts, error and timings describe background persistence. Paused means durable completion. pause(wait=True) waits up to the API's time cap; check vm.phase and use vm.wait("Paused") if still Pausing. Resume raises Conflict until persistence and billing settlement complete. Snapshot failures remain frozen and unbilled while retrying; they never automatically resume the guest.

Snapshots are kept until you delete them or, unused, for 14 days: snapshot.delete_at is when an unused one goes, and restoring it into a gup (client.create(os=..., restore_from=snap.name)) restarts the 14 days. client.limits() shows your plan's caps and what counts against them: max_active_gups / active_gups, max_disk_gib (the largest disk of one gup), max_snapshots / snapshots, snapshot_retention_seconds, max_warm_slots / warm_slots (0 = no cap). Over a storage cap, a create, resize or snapshot raises StorageLimit.

Keep one Client for many calls: it reuses its connections, so a call does not pay a new TLS handshake. From a distant client that saves 100–150 ms per call. It is safe to share between threads; client.close() closes the idle connections. Behind a proxy (HTTPS_PROXY), each call opens its own connection.

Files

gup.files reads and writes the gup's filesystem through the in-guest agent (REQUIREMENTS.md PR-3, ARCHITECTURE.md D-24). Paths are absolute or relative to the gup user's working directory; mode is an octal string as in chmod.

files = gup.files
files.write("notes.txt", "hello\n")                     # str is UTF-8; bytes pass through; parents created -> bytes written
files.read_text("notes.txt")                            # "hello\n"   (files.read() -> bytes)
files.upload("local.tar.gz", "/tmp/in.tar.gz", mode="0600")   # streamed, no buffering
files.download("/tmp/out.log", "out.log")
for e in files.list("."):                               # FileEntry: name, path, size, mode, mtime, is_dir, is_symlink
    print(e.name, e.size, e.mode, e.is_dir)
files.stat("src").is_dir                                # True
files.mkdir("build/cache", mode="0755", parents=True)   # mkdir -p
files.remove("build", recursive=True)
files.rename("notes.txt", "docs/notes.txt")             # rename or move inside the gup

Big files (ARCHITECTURE.md D-66): upload sends a file larger than guplet.UPLOAD_PART_THRESHOLD (16 MiB) in parts of the server's part size. A part whose connection drops resumes from what the gup received, and the upload completes with the file's sha256. chunked=True forces this path for any size. download resumes a dropped body with a Range request. Both give up after max_retries failures in a row.

A missing path raises NotFound; a path outside the gup or a permission error raises GupletError with status 403; a gup that is not running raises Conflict; a gup without the in-guest agent raises NotEnabled.

Background processes

gup.processes starts a command that outlives the call (ARCHITECTURE.md D-62). The in-guest agent keeps the process and its output on the gup's disk.

p = gup.processes.start("npm run dev", cwd="/app", stdin=True)   # or gup.run(cmd, background=True)
for name, text in p.output():                           # ("stdout"|"stderr", text) until it ends; follow=False stops when caught up
    print(name, text, end="")
p.send_stdin("y\n"); p.send_stdin(b"\x00raw")           # bytes are sent base64; p.close_stdin() sends EOF
p.kill("TERM")                                          # KILL by default; returns the record (state, exit_code)
done = gup.processes.start("make test").wait(timeout=600)   # the final record, with .stdout / .stderr
gup.processes.list(); gup.processes.get(p.id); p.refresh()

output() reconnects by byte offset after a dropped connection, a 5xx or an error frame, up to max_retries failures in a row. start carries an Idempotency-Key, so retrying it is safe. send_stdin is not retried after a network error. A gup created before D-62 raises NotEnabled with code agent_too_old.

Errors: GupletError(status, message, code, retry_after) with subclasses Unauthorized (401), InsufficientCredits (402), Forbidden (403; StorageLimit for code storage_limit: a disk or a snapshot count over your plan's cap), NotFound (404), Conflict (409, e.g. not running), Gone (410), RateLimited (429, raised after the retries; TeamLimit for code team_limit: as many running gups as your plan allows), NotEnabled (501, feature not deployed on this cluster), Unavailable (503, raised after the retries) and ResizeRefused. A command whose session broke or hit the server timeout raises ExecError / ExecTimeout; a non-zero exit is just ExecResult.exit_code.

asyncio (FastAPI)

guplet.AsyncClient (ARCHITECTURE.md D-89) is for code on an event loop, where a blocking call would stall every other request. It comes with pip install guplet-sdk (since 1.5.0; "guplet-sdk[async]" still installs the same thing). Same options, retries, idempotency keys and errors as Client, awaited:

import asyncio, guplet

async def main():
    async with guplet.AsyncClient() as client:          # one per process / event loop; it keeps connections alive
        async with await client.create(os="toolbox", size="s", ttl=600, wait=True) as gup:   # killed at the end
            r1, r2 = await asyncio.gather(gup.run("make test"), gup.run("make lint"))        # at the same time
            async with gup.run_stream("for i in 1 2 3; do echo $i; sleep 1; done") as s:
                async for name, text in s:
                    print(name, text, end="")
            print(s.exit_code)
            await gup.files.write("notes.txt", "hello\n")
            p = await gup.run("npm run dev", background=True)                               # an AsyncProcess
            async with p.output(follow=False) as out:
                async for name, text in out:
                    print(text, end="")
            await gup.pause(wait=True); await gup.resume(wait=True)
            await gup.keepalive(ttl=3600)                                                    # lease: one more hour, in seconds
            print(gup.port_url(8080), (await gup.cost()).cost)

asyncio.run(main())

In FastAPI, make the client in the app's lifespan and close it there with await client.aclose().

To set the connection pool, timeouts, proxies or tracing hooks yourself, pass your own httpx.AsyncClient (since 1.6.0):

import httpx

async def trace_request(request):                   # an httpx event hook: your tracer here
    print(request.method, request.url.path)

http = httpx.AsyncClient(limits=httpx.Limits(max_connections=500), timeout=httpx.Timeout(30, connect=5),
                         event_hooks={"request": [trace_request]})
client = guplet.AsyncClient(http_client=http)   # client.aclose() leaves `http` open: you close it
  • Scope: create, get, list, delete, exec, execs; on AsyncGup refresh, wait, kill, pause, resume, keepalive, run, run_stream, cost, cost_stream, files (all of Files), processes (all of Processes) and port_url. The rest (templates, secrets, warm pools, snapshots, resize, egress, logs, desktop) is sync-only for now: use Client for those.
  • Cancelling: cancelling a run (asyncio.wait_for, an anyio timeout such as anyio.fail_after, a cancelled task) closes its stream, and that stops the command on the gup. async with gup still deletes the gup when its block was cancelled. FastAPI does not cancel a plain endpoint when its client disconnects, so put a timeout on long runs yourself.
  • Streams: run_stream(), cost_stream() and Process.output() start when entered or first iterated. Use async with when you may stop reading before the end.
  • on_cost may be a plain function or a coroutine function.
  • Network errors surface as httpx.TransportError (the sync client raises URLError / OSError).
  • Connections: on the SDK's own httpx client, open connections are not capped, because each running command holds one; up to 20 idle ones are kept for 30 s. HTTPS_PROXY is honoured.
  • Your own http_client: every call goes through it, with the SDK's headers added per request; its pool limits, proxies, TLS and event hooks apply as they are. Without timeout=, a call uses your client's timeout (httpx's default is 5 s, the SDK's own client 60 s), except that a stream waits up to 60 s for a frame and a wait=True call up to its timeout + 10 s (the read only). Each running command or followed stream holds one connection, so your max_connections (httpx's default 100) caps them: the next one fails with PoolTimeout after your pool timeout. Do not add a raise_for_status() response hook (it skips the SDK's retries and error classes) or a hook that reads the body (it waits for the command to end), and do not use a transport that resends a request it already sent (it can run a command twice; httpx's own retries= only retries connecting, which is safe).
  • Local files: upload and download read and write the local file with ordinary blocking calls: 64 KiB at a time, except a chunked upload, which reads and hashes one part (16 MiB) at a time.

Exec output is text (not binary-safe). Tests: scripts/test-sdk.sh (offline, against sdk/fixtures, in a venv per httpx version of tests/async-httpx-versions.txt), scripts/sdk-smoke.sh (live; --async adds the asyncio client).

Metadata

Release files for guplet-sdk 1.7.0

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

Source distribution (sdist)

Source distribution for guplet-sdk 1.7.0
File Size Uploaded Provenance Actions
guplet_sdk-1.7.0.tar.gz 89.5 kB Without provenance Details for guplet_sdk-1.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for guplet-sdk 1.7.0
File Interpreter ABI Platform Actions
guplet_sdk-1.7.0-py3-none-any.whl Python 3 none any Details for guplet_sdk-1.7.0-py3-none-any.whl

Total release size: 148.6 kB

Release files / guplet_sdk-1.7.0.tar.gz

Download URL guplet_sdk-1.7.0.tar.gz
Size 89.5 kB
Tags Source
SHA-256 checksum
How to use checksums
0d1dbaf7ff330fae5e60c8290da295266dd12ce4e23b3187d02d973795fe8b0d
BLAKE2b-256 checksum
How to use checksums
1aa128c5f5a210ceac52a398d01fc42955658efa0e092e559e39c3819dbe0c04
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / guplet_sdk-1.7.0-py3-none-any.whl

Download URL guplet_sdk-1.7.0-py3-none-any.whl
Size 59.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2eaa068c14b79aa98fd128d6c1c7c902fe4eb713538847a4fbac84d3db862aeb
BLAKE2b-256 checksum
How to use checksums
dc9dbb22e8cb8bee102e75f9d826ff31ea5ee56fdbd1333ddb640927e535ad4e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for guplet-sdk 1.7.0

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