---
name: spheron-gpu-api
description: Rent and manage NVIDIA GPU and CPU-only instances through the Spheron AI REST API. Use when the user wants to find GPU or CPU offers, deploy or terminate instances, manage SSH keys, persistent volumes, teams, or account balance on Spheron (app.spheron.ai). Covers H100, A100, B200, B300, RTX 4090, and other GPUs, plus CPU Node instances and Spheron Con containers (a Docker image on a GPU or CPU), across SPOT and DEDICATED instance types.
license: For use with the Spheron AI GPU platform. Requires a Spheron API key.
---

# Spheron GPU API skill

You help the user rent and manage GPU instances on the Spheron AI platform by calling its REST API. This document is your complete operating manual. Read it before making any call, then follow the decision framework to choose the right endpoint, build correct parameters, and report results clearly.

You are acting on the user's real account. Deploying an instance or creating a volume spends real money. Treat every create, terminate, and delete as a consequential action.

---

## 1. Before you do anything: the API key

Every authenticated call requires a Spheron API key sent as a Bearer token. Without it, you can only list public GPU offers and providers; you cannot deploy, manage, or read account data.

**Get a key one of two ways:**

1. Generate it from the dashboard at `https://app.spheron.ai/settings?tab=api`.
2. If the user does not have dashboard access yet, or needs API access enabled for their account, contact **info@spheron.ai** to request access.

**Store the key locally and always read it from there:**

Persist the key once on the local system and retrieve it from that location on every run, rather than asking the user again or pasting it into prompts. The preferred store is the `SPHERON_API_KEY` environment variable. A local file outside any repository works too, for example `~/.spheron/credentials` with permissions set to `600`.

Follow this retrieval order before every authenticated call:

1. Read the `SPHERON_API_KEY` environment variable.
2. If it is not set, read the local credentials file (for example `~/.spheron/credentials`).
3. Only if both are empty, ask the user for the key, then save it to one of the locations above so future runs read it automatically.

```bash
# Save the key once (one option: an environment variable for the current shell)
export SPHERON_API_KEY="<your-api-key>"

# Persist it for future shells
echo 'export SPHERON_API_KEY="<your-api-key>"' >> ~/.zshrc

# Read it back on every run instead of re-asking
curl -H "Authorization: Bearer $SPHERON_API_KEY" \
  https://app.spheron.ai/api/providers
```

**Rules you must follow:**

- Always look for the key in the local store first (the retrieval order above). Do not ask the user for a key you already have stored locally, and never invent or guess a key.
- Treat the key like a password. Never print it back in full, never write it into logs, code comments, shared files, or version control. Reference it as `$SPHERON_API_KEY` or `<your-api-key>` in any example you show.
- Send it only over HTTPS to `https://app.spheron.ai`. Never send it to any other host.
- If the user pastes a key into the chat, save it to the local store, use the stored value from then on, and remind them once that keys belong in the environment variable or credentials file, not in prompts.

**Auth header on every authenticated request:**

```
Authorization: Bearer <your-api-key>
```

A `401` response means the key is missing (`code: authentication_required`) or malformed, unknown, revoked or expired (`code: invalid_api_key`). Stop and ask the user to check their key or request access from info@spheron.ai.

---

## 2. Base URL

```
https://app.spheron.ai
```

All paths below are relative to this base. All requests and responses are JSON. Send `Content-Type: application/json` on any request that has a body.

---

## 3. Mental model of the platform

Understand these objects and how they relate before you call anything:

- **Provider**: a compute supplier (for example `spheron-ai`, `spheron-es`, `spheron-ms`, `spheron-am`, `spheron-con`, `data-crunch`, `massed-compute`). The set of providers is dynamic. Always read the live list from `GET /api/providers`.
- **Silicon vendor**: most GPUs are NVIDIA and run CUDA. `spheron-am` supplies AMD Instinct MI300X (192 GB HBM3e per GPU) running ROCm, and Gaudi2 on `spheron-ms` is Intel. On an AMD machine `nvidia-smi` does not exist and CUDA-only wheels and Docker images fail, so say so before the user deploys one.
- **GPU offer**: a concrete, deployable configuration from one provider (a specific GPU model, count, region, OS options, price, and `instanceType`). Each offer has a unique `offerId`. You deploy an offer, not a bare GPU type.
- **CPU Node**: a CPU-only instance with no GPU attached, served by the same offers endpoint as a single row with `gpuType: "CPU"` and `gpuCount: 0`. Use it for data prep, build steps, schedulers, and API workers. Prices start around $0.09/hr, so never rent a GPU for work that does not touch one.
- **Container (Spheron Con)**: a public Docker image run on a GPU or CPU instead of a full virtual machine, from provider `spheron-con`. Its offer group's `gpuType` ends in `_CONTAINER` (`CPU_CONTAINER` for CPU), and it deploys with a `container` object instead of an operating system. Usually ready within a few minutes, billed by the hour, on-demand only. Suggest it when the user just wants to run an image (vLLM, Ollama, Jupyter, a training image) for a while, rather than look after a server.
- **Deployment**: a running GPU instance created from an offer. It has a lifecycle (`deploying` to `running` to `terminated`) and accrues hourly cost while running. On some providers it can also be **stopped**, which releases the GPU, preserves the disk, and drops billing to a lower stopped rate. Terminating is permanent and deletes the disk. Read `supportsPause`, `supportsRestart`, and `pauseUnsupportedReason` on the deployment object to know which controls this specific instance has.
- **SSH key**: how the user logs into the instance. A deployment needs either a saved `sshKeyId` or an inline `ssh_public_key`.
- **Volume**: optional persistent storage you can attach to a deployment. Rules differ sharply by provider.
- **Team**: billing and ownership boundary. Balance lives at the team level. Most users have one default personal team.
- **Balance**: prepaid USD credit on a team. A deployment fails or cannot start if the team has no balance.

The core dependency chain for a deployment:

```
providers  →  gpu-offers  →  (pick one offer)  →  ssh key  →  POST deployment  →  poll status  →  connect  →  terminate
                                   │
                                   └── balance must be sufficient on the chosen team
```

---

## 4. Decision framework: choose what to call

Identify the user's intent, then follow the matching path. Do not call endpoints you do not need.

### Intent: "Deploy a GPU instance"

1. If you do not yet have an API key, get one (Section 1).
2. Call `GET /api/teams` to find the team and its balance, or `GET /api/balance` for live balance. Confirm balance is positive. If zero, tell the user to add credit before deploying.
3. Call `GET /api/gpu-offers?computeType=gpu` with a `search` term matching the GPU the user wants (for example `search=h100`). Authenticate so discounted prices appear. Without `computeType` the list holds virtual machines only.
4. From the response, pick a specific offer inside `data[].offers[]`. Record its `provider`, `offerId`, `gpuType`, a valid `region` (from the offer's `clusters`/`region`), a valid OS (from `os_options`), and `instanceType`.
5. Ensure an SSH key exists: call `GET /api/ssh-keys`. If none, either add one with `POST /api/ssh-keys`, or pass an inline `ssh_public_key` at deploy time.
6. Show the user a short summary (GPU, region, instance type, hourly rate, estimated cost) and confirm before deploying.
7. Call `POST /api/deployments`. The parameters `provider`, `offerId`, `gpuType`, `region`, `operatingSystem`, and `instanceType` must all match the chosen offer.
8. Poll `GET /api/deployments/{deploymentId}` every 15 to 30 seconds until `status` is `running`, then return the `sshCommand` and `ipAddress`.

### Intent: "Deploy a CPU instance / I don't need a GPU"

Same flow as above, with three differences:

1. Call `GET /api/gpu-offers?computeType=cpu`. The response is a single row, `gpuType: "CPU"`, `displayName: "CPU NODE"`.
2. Pick an entry from `offers[]` by `vcpus` and `memory` rather than by GPU model. Record its `provider`, `offerId`, `region` (from `clusters`), OS (from `os_options`), and `instanceType`.
3. `POST /api/deployments` with `"gpuType": "CPU"` and `"gpuCount": 0`. Sending a GPU model name against a CPU `offerId` returns `400`.

Providers offering CPU nodes: `data-crunch` (spot and dedicated, Finland), `spheron-ai` (dedicated, Norway, Canada, Noida, and Chennai), `massed-compute` (dedicated, US). Sizes run 2 vCPU / 8 GB up to 52 vCPU / 160 GB. Spheron AI CPU nodes in Noida and Chennai take no volume and no `cloudInit`; sending either returns `400`.

Proactively suggest a CPU node when the user describes work that never touches a GPU: preprocessing, ETL, builds, schedulers, queue workers, or an API front end.

### Intent: "Run a Docker image / a container"

1. Call `GET /api/gpu-offers?computeType=gpu-container` (or `cpu-container`) with a `search` term. Pick an entry from `offers[]`: `provider` is `spheron-con` and `os_options` is `["Container"]`.
2. Check the image with `GET /api/containers/image?image=<ref>`. `status: "not_found"` covers private images, which are refused. `ssh: true` means SSH can be set up; `ssh: false` means the image runs as a non-root user (named in `user`) and has no SSH, so the user reaches it through its ports; `ssh: null` means it could not be told, so do not promise SSH.
3. `POST /api/deployments` with the offer's `provider`, `offerId`, `gpuType` (ending in `_CONTAINER`), `gpuCount` (`0` for a CPU container), `region`, `instanceType: "DEDICATED"`, and a `container` object: `image` (required), `command` (replaces the image's start command), `ports` (up to 9, each gets a public port; 22 is added when an SSH key is sent) and `env` (up to 50; values are never stored or returned). No `operatingSystem` and no `cloudInit`. An SSH key is optional for a container.
4. It is billed from the moment its machine starts, while its image downloads too. `status` turns `running` at once; while `containerState` is present (`phase: "downloading"` or `"starting"`) it cannot be reached yet, so keep polling. Once it is gone, open `http://<ipAddress>:<external_port>` from `portForwards`, or use `sshCommand`.
5. `containerState.issue: "crash_loop"` means it keeps exiting: its image or command is at fault. A container that never comes up is failed within about two minutes with a `failureReason`.

A GPU container comes with a 100 GB container disk and a 500 GB volume at `/workspace`. `extras.container.stoppedHourlyUsd` is what it bills per hour while stopped, and `extras.container.volumeHourlyUsd` is what the built-in volume adds to the running price; passing a Spheron Con volume in `volumeIds` takes that amount off. Files to keep go in `/workspace`. Only GPU containers can be stopped; a stop or restart resets everything outside `/workspace` and an attached volume, and a stopped GPU container can only start on its own machine (`resume` returns `503` while that GPU is taken). For Jupyter and Open WebUI images, `GET /api/deployments/{deploymentId}/access-token` returns the token or password the container was started with.

### Intent: "Show me available GPUs / prices"

- `GET /api/gpu-offers` with optional `search`, `instanceType`, `sortBy`, paging. Authenticate to show the user their real discounted price, not list price.
- Omitting `computeType` returns virtual machines only (GPU, CPU and bare metal). Add `computeType=all` for virtual machines and containers together, `computeType=gpu` for GPU virtual machines (bare metal included), `cpu` for the CPU Node row, `vm` for every virtual machine, or `container`, `gpu-container`, `cpu-container` for containers.

### Intent: "What do I have running?"

- `GET /api/deployments?status=active`. To inspect one, `GET /api/deployments/{deploymentId}`.

### Intent: "Stop / pause / hibernate an instance"

Stopping keeps the instance and its disk while releasing the GPU, and billing drops to a lower stopped rate. It is not available everywhere, so check before you promise it.

1. Read the deployment object. `supportsPause` tells you whether this specific instance can be stopped, narrowed by its provider, machine type, and region. When it is `false`, `pauseUnsupportedReason` explains why; relay that text rather than writing your own.
2. Call `GET /api/deployments/{deploymentId}/pause-quote`. Report `currentHourlyRate`, `hourlyRate` (the stopped rate), and the `breakdown` so the user sees what they will still pay.
3. Confirm with the user, then call `POST /api/deployments/{deploymentId}/pause`.
4. Start it again later with `POST /api/deployments/{deploymentId}/resume`. It returns on the same disk, the same contents, and the same public IP. On Spheron AI in Noida and Chennai, a started instance can come back under a new `instanceId`, so read the deployment again afterwards.

Tell the user these three things before they commit:

- A stopped instance still costs its disk rate, and a team that runs out of credit has every instance destroyed, stopped ones included.
- A start can be refused when the provider released the hardware and the machine type is out of stock. Nothing is lost; retry later.
- Stopping is unavailable on some providers, machine types, and regions. Where it is unavailable, the instance bills at the full rate until it is terminated.

If a `pause` request times out, do not retry it. Hibernation routinely outlives the request. Poll the deployment instead.

### Intent: "Restart / reboot an instance"

Restarting reboots the machine in place. Billing does not change and the status stays `running`.

1. Check `supportsRestart` on the deployment object. Restarting is available on Spheron AI (except Noida and Chennai), Spheron MS, Spheron AM, Spheron Con, and Massed Compute, and not on Spheron ES or Verda.
2. Warn the user that this is a hard reboot, so anything held in memory is lost.
3. Call `POST /api/deployments/{deploymentId}/restart`.
4. Poll `GET /api/deployments/{deploymentId}/reboot-status` until `restarting` is `false`.

Never emulate a restart with a pause followed by a resume. That releases the GPU and carries the risk of a refused start, which a reboot does not.

### Intent: "Terminate an instance"

Terminating is permanent and deletes the disk. When the user says "stop" or "shut down", ask whether they mean stopping (reversible, keeps the disk) or terminating (permanent), and offer stopping first where `supportsPause` is `true`.

- Terminating deletes the instance and everything on its disk (the OS, installed packages, models, and any data not on a persistent volume).
- A terminated instance cannot be recovered or resumed. To use the GPU again, deploy a fresh instance and set it up from scratch.
- To preserve work across instances, the user should keep data on a persistent volume (Section 7) or back it up off the instance before terminating. A volume detaches and survives termination; the instance's local disk does not.

If the user wants to terminate:

1. Call `GET /api/deployments/{deploymentId}/can-terminate` first. If `canTerminate` is `false`, tell the user how many minutes remain (`timeRemaining`) before the minimum runtime is met. Read `minimumRuntime` from the response rather than assuming 20 minutes: it is the larger of the account's own minimum and the machine type's provider minimum, and a provider minimum is charged in full even on an early terminate. Minimum runtime counts time spent running, so stopping an instance does not serve it out.
2. Confirm with the user that termination is permanent and deletes the disk.
3. Call `DELETE /api/deployments/{deploymentId}`.

### Intent: "Rename an instance"

- `PATCH /api/deployments/{deploymentId}` with `{ "name": "..." }`. Only `name` is mutable. Everything else (provider, region, GPU, instance type, SSH key, volumes) is immutable. To change anything else, terminate and redeploy.

### Intent: "Persistent storage"

- See Section 7. Always read `GET /api/volumes/regions?provider=<id>` before creating a volume, and respect the provider-specific rules.

### Intent: "How much credit do I have?"

- `GET /api/balance` (live, all teams) or `GET /api/balance?teamId=<id>` for one team.

---

## 5. Endpoint reference

Authenticated unless marked public. All paths are under `https://app.spheron.ai`.

### Providers and offers

| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| GET | `/api/providers` | Public | List configured provider names. Returns a JSON array of strings. |
| GET | `/api/gpu-offers` | Optional | List GPU offers. Authenticate to receive team discount fields. |

`GET /api/gpu-offers` query params: `page` (default 1), `limit` (default 10), `search` (GPU model text), `sortBy` (default popularity), `sortOrder` (`asc`/`desc`), `instanceType` (`SPOT`/`DEDICATED`/`CLUSTER`, case-insensitive), `computeType` (`vm` for every virtual machine, `gpu` for GPU virtual machines and bare metal, `cpu` for the CPU Node row, `gpu-container` / `cpu-container` / `container` for containers, `all` for virtual machines and containers; omit for virtual machines only). Response is `{ data, total, page, limit, totalPages }`. Each `data[]` group has a GPU model with an `offers[]` array; each entry there has the `offerId` you deploy.

Discount fields appear in each offer only when authenticated: `originalPrice`, `discountedPrice`, `discountPercentage`, `hasDiscount`. Unauthenticated responses include only `price` (list price).

### Deployments

| Method | Path | Purpose |
|--------|------|---------|
| POST | `/api/deployments` | Create a GPU instance. |
| GET | `/api/deployments` | List your deployments. Filter with `status`, `teamId`, `userId`. |
| GET | `/api/deployments/{deploymentId}` | Get one deployment. |
| PATCH | `/api/deployments/{deploymentId}` | Rename only (`name` field). |
| DELETE | `/api/deployments/{deploymentId}` | Terminate the instance. |
| GET | `/api/deployments/{deploymentId}/can-terminate` | Check minimum runtime before terminating. |
| GET | `/api/deployments/{deploymentId}/pause-quote` | Quote the stopped rate. Changes nothing. |
| POST | `/api/deployments/{deploymentId}/pause` | Stop the instance, keeping its disk. |
| POST | `/api/deployments/{deploymentId}/resume` | Start a stopped instance. |
| POST | `/api/deployments/{deploymentId}/restart` | Reboot in place. Billing unchanged. |
| GET | `/api/deployments/{deploymentId}/reboot-status` | Whether a reboot is still in flight. |
| PUT | `/api/deployments/{deploymentId}/max-price` | Set or clear (`null`) the max price of a live-priced Spheron ES spot instance. Body: `{ "maxHourlyRate": number \| null }`. |

`GET /api/deployments` `status` filter accepts `active` (running, deploying, or stopped), `inactive` (terminated or failed), or an exact status: `running`, `deploying`, `stopped`, `terminated`, `failed`.

Lifecycle errors: `400` (`action_not_allowed`, `action_not_supported`) means the provider, machine type, region, or current status forbids the action, so do not retry. `400` `instance_not_ready` means the instance has no machine yet: wait until it is running, then retry. `402` (`insufficient_credits`) on a resume means the balance cannot cover 30 minutes at the running rate. `409` means another change is still in flight (`instance_busy`, `instance_already_starting`), or, on a resume, that a spot instance's `hourlyRate` is still above its `maxHourlyRate` (`above_max_price`). `503` (`provider_start_failed`) on a resume usually means the machine type is out of stock; retry later. `504` (`provider_timeout`) means the request went through and is slow, so poll rather than retry.

### SSH keys

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/ssh-keys` | List your keys. |
| POST | `/api/ssh-keys` | Add a key. Body: `{ name, publicKey, teamId? }`. |
| GET | `/api/ssh-keys/{id}` | Get one key. |
| DELETE | `/api/ssh-keys/{id}` | Delete a key. |

### Volumes

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/volumes/regions` | List valid regions per provider. Call this before creating. |
| GET | `/api/volumes/pricing` | Storage rate per GB per hour for a provider/region. |
| GET | `/api/volumes` | List volumes. Filter with `teamId`, `status`, paging. |
| POST | `/api/volumes` | Create a volume. |
| GET | `/api/volumes/{volumeId}` | Get one volume with fresh usage. |
| PATCH | `/api/volumes/{volumeId}` | Rename or expand (provider-dependent). |
| DELETE | `/api/volumes/{volumeId}` | Delete a detached volume. |
| POST | `/api/volumes/{volumeId}/attach` | Attach to a running deployment. |
| POST | `/api/volumes/{volumeId}/detach` | Detach from a deployment. |

### Teams and balance

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/balance` | Live balance. `teamId` for one team, `all=false` for current team only. |
| GET | `/api/teams` | List teams you belong to (creates a default personal team on first call). |
| GET | `/api/teams/details/{teamId}` | One team. Balance here is stored, not recomputed; use `/api/balance` for live. |

---

## 6. How the deployment parameters work

`POST /api/deployments` is the most important and most error-prone call. Get these right.

**Required fields, and where each value comes from:**

| Field | Type | Must match | Source |
|-------|------|-----------|--------|
| `provider` | string | The chosen offer's provider | `offers[].provider` from gpu-offers, validated against `GET /api/providers` |
| `offerId` | string | Exact offer identifier | `offers[].offerId` |
| `gpuType` | string | The offer's GPU type | `offers[]` group `gpuType` (for example `rtx-4090`, `h100`). Send `CPU` for a CPU Node offer, and the group's `_CONTAINER` type for a container. |
| `gpuCount` | number | Count for that offer | `offers[].gpuCount`. This is `0` for a CPU Node offer, and `0` is a real value, not a missing one. |
| `region` | string | A region the offer lists | `offers[].region` or one of `offers[].clusters` |
| `operatingSystem` | string | One of the offer's OS options | `offers[].os_options` (for example `ubuntu-22.04`). Not needed for a container, which sends `container` instead. |
| `instanceType` | string | The offer's type | `SPOT` or `DEDICATED` (case-insensitive) |

If any of these do not correspond to the same offer, the deploy is rejected or behaves unexpectedly. Do not mix a `gpuType` from one offer with an `offerId` from another. Always copy them from the same `offers[]` entry.

**SSH access (exactly one is required):**

- `sshKeyId`: ID of a key from `GET /api/ssh-keys`. Preferred when the user already has a saved key.
- `ssh_public_key`: inline OpenSSH public key string. Spheron creates a temporary key for the deployment. Use when the user has no saved key and does not want to save one.

Send one of them. A request with neither, or whose saved key has missing or invalid public key data, returns `400` before any deployment is created. Ask which the user wants.

**Optional fields:**

- `teamId`: deploy under a specific team. Defaults to the current team. Get IDs from `GET /api/teams`.
- `name`: a friendly label. Stored verbatim, editable later via PATCH.
- `cloudInit`: first-boot automation. Object with `runcmd` (string array), `packages` (string array), and `writeFiles` (array of `{ path, content, owner?, permissions? }`). Only send it when the offer reports `supportsCloudInit: true`. Spheron AI offers in Noida and Chennai report `false`, and a request carrying `cloudInit` for them returns `400`. On Spheron ES the whole startup configuration, SSH keys included, must fit in 32,768 characters; a larger one returns `400`. Download large files from a `runcmd` step instead of embedding them.
- `maxHourlyRate`: max price in USD per hour for the whole instance, `0.01` to `1000`, and at least the starting price. Only for offers with `extras.live_spot_price: true`; ignored otherwise. Above it, the instance is stopped (not deleted).
- `volumeIds`: array of volume IDs to attach at launch. Either the volume's `id` or its `volumeId` works. Each volume must match the deployment's provider and region. Provider rules below.

**volumeIds per-provider rules:**

- **Spheron AI**: depends on the region. In Canada 1, Montreal 1, Norway 1, Oslo 1, and the US: up to 10 volumes per instance, each attached to one instance at a time, with hot-detach and re-attach after launch. In Noida and Chennai: single-item array of a shared volume in the same region; several deployments can use the same volume. Sending `volumeIds` for a machine that takes none (Noida and Chennai CPU nodes) returns `400`.
- **Verda**: up to 10 volumes per instance. A volume can be shared across multiple instances.
- **Spheron ES**: multiple volumes per instance. A volume can be shared across multiple instances, read-write or read-only. Attaching here at deploy time avoids the VM restart that a post-launch hot-attach causes.
- **Spheron Con**: single-item array of a Spheron Con volume in the same region, mounted at `/workspace`. It cannot be added after launch, and several containers can share it.

**Live spot prices (Spheron ES):** a spot offer with `extras.live_spot_price: true` has a price that can change as often as every 15 minutes, capped at the dedicated price for the same machine. The deployment then reports `liveSpotPrice: true`, and its `hourlyRate` can change while it runs. Tell the user the quoted spot price is the current price, not a fixed rate.

**Max price (Spheron ES spot):** offer the user a max price for a live-priced spot instance, at deploy (`maxHourlyRate`) or later with `PUT /api/deployments/{deploymentId}/max-price`. It covers the whole instance, not one GPU. When the live price rises above it, the instance is stopped: status `stopped`, `pauseInitiator: "price-cap"`, billed at `stoppedHourlyRate`. While stopped, `hourlyRate` keeps tracking the live price, and `resume` returns `409` until `hourlyRate` is at or below `maxHourlyRate`. A stopped instance is still destroyed if the team balance runs out. A max price does not prevent a spot reclaim.

**Spot on Spheron MS:** some Spheron MS offers also come as `SPOT`, listed separately from the on-demand offer and priced no higher than it.

**Cost estimate before deploying:** the offer's hourly rate is `discountedPrice` if the user has a discount, otherwise `price`. The offer price is the total hourly rate for that whole configuration (an 8x H100 offer priced at 21.52 means 21.52 USD per hour total, not per GPU). Add volume cost (`sizeInGb` times the region's `hourlyRatePerGb`). Present the estimate to the user before you create anything.

---

## 7. Volumes: read regions first, then respect provider rules

Providers that take new volumes: `data-crunch`, `spheron-ai`, `spheron-es`, `spheron-ms`, `spheron-con` (and `verda` for attach semantics). `massed-compute` and `spheron-am` have no volumes at all; a deployment on `spheron-am` carrying `volumeIds` is rejected rather than created without them.

**Always call `GET /api/volumes/regions?provider=<id>` first.** It returns each region's `id`, `minSizeGb`, `maxSizeGb`, `hourlyRatePerGb`, and `hasGpuOffers`.

**Create (`POST /api/volumes`) parameters:**

| Field | Required | Notes |
|-------|----------|-------|
| `name` | Yes | Lowercase alphanumeric with hyphens/underscores, max 60 chars. |
| `sizeInGb` | Yes | A whole number of GB within the region's `minSizeGb`/`maxSizeGb`. Fractions such as `100.5` return `400`. |
| `provider` | Yes | One of the supported providers. |
| `region` | Conditional | Required for `data-crunch`, `spheron-ai`, `spheron-es`, `spheron-ms`, `spheron-con`. Spheron MS and Spheron Con have no default. |
| `teamId` | No | Defaults to current team. |
| `deploymentId` | No | Attach during creation. Supported for `data-crunch`, `spheron-ai`, `spheron-es`. Not for `spheron-ms` or `spheron-con`, or for `spheron-ai` volumes in Noida and Chennai. Attaching to a running Spheron ES instance restarts the VM. |

**Size limits by provider:** data-crunch 1 to 10000 GB, spheron-con 10 to 4096 GB, spheron-ms 1 to 16000 GB, spheron-ai up to 51200 GB (varies by region; read the region's `maxSizeGb`; Noida and Chennai are 50 to 2048 GB), spheron-es up to 262144 GB (256 TiB).

**Attach/detach and mutability rules:**

- **Verda**: up to 10 volumes per instance; a volume can be shared across instances. Volume and instance must be in the same region (`FIN-01`, `FIN-02`, `FIN-03`). Cross-region attach fails silently (looks attached, data inaccessible). Always co-locate.
- **Spheron AI**: the region decides the volume kind. Block volumes (Canada 1, Montreal 1, Norway 1, Oslo 1, US): up to 10 per instance, one instance per volume at a time, hot-detach and re-attach supported. Not renamable or resizable; to grow, create a new larger volume and migrate data. Shared volumes (`noida-india`, `chennai-india`): shared filesystems, 50 to 2048 GB, one per instance, selected only at deploy time via `volumeIds`, shareable by several instances, mounted automatically at `/home/jl_fs`. No attach to a running instance, no resize, no rename: `PATCH` rejects `sizeInGb` and `name`. GPU machines only.
- **Spheron ES**: multiple volumes per instance; a volume can be mounted on multiple instances at once, read-write or read-only, within the same region (`EU North 1`, `EU West 1`, `ME West 1`, `US Central 1`). Supports in-place expansion (no shrinking). Hot-attach and hot-detach restart the VM, data preserved; attach via `volumeIds` at deploy time to avoid it. Mounted with `mount -t virtiofs` using the volume's mount tag.
- **Spheron MS**: 1 volume per instance, bound at instance creation via a single-item `volumeIds`. Immutable: size and name are fixed at creation, so `PATCH` and the attach endpoint both return an error. The volume's `region` must equal the offer's `region` or the deployment is rejected before anything is created. Terminating the instance releases the volume for the next deployment.
- **Spheron Con**: for containers only, 10 to 4096 GB, `region` required (there is no default; use one from `GET /api/volumes/regions?provider=spheron-con`, the same as the container's), selected at deploy via a single-item `volumeIds` and mounted at `/workspace`. Several containers in the same region can share it. Renamable and expandable (no shrinking). The attach endpoint returns `400`, and detach returns `400` while its container is live; terminating the container releases it.

**Volume IDs**: new volumes get a Spheron `volumeId` of the form `vol_` plus 24 hex characters. Older volumes still resolve by their previous ID on every `/api/volumes/{volumeId}` call and in `volumeIds`.

**Attach** requires the volume and deployment to be the same provider and region. **Delete** requires the volume to be detached (terminate the instance first, then delete).

---

## 8. Status values and polling

Deployment statuses:

- `deploying`: provisioning, usually 30 to 60 seconds.
- `running`: active and reachable. `sshCommand` and `ipAddress` are populated. A container is `running` from the moment it is billed, which can be before it is reachable: while `containerState` is present, keep polling.
- `stopped`: parked. The GPU is released, the disk and its contents are preserved, and billing runs at `stoppedHourlyRate`. The public IP is retained. Part of the live set, so `?status=active` includes it. Resume it to get back to `running`.
- `failed`: deployment error. Inspect the deployment object for details. A deployment that ends before it ever reaches `running` (terminated by the user, removed by the provider, or stopped for lack of credit) is recorded as `failed`, not `terminated`, and is never charged.
- `terminated`: ended by the user.
- `terminated-provider`: reclaimed by the provider. For SPOT instances this means the spot capacity was interrupted. No user action needed, but the instance is gone.

Lifecycle:

```
deploying → running ⇄ stopped → terminated
    ↓            ↓
  failed   terminated-provider
```

A restart does not change the status. The instance stays `running` throughout; poll `reboot-status` to know when the reboot finishes.

After `POST /api/deployments`, poll `GET /api/deployments/{deploymentId}` every 15 to 30 seconds until `running` or `failed`. Do not poll faster than once every 10 seconds. If it reaches `failed`, report the failure rather than retrying blindly.

If the user chose a SPOT instance, warn them it can move to `terminated-provider` at any time. For long, uninterruptible work, recommend DEDICATED.

---

## 9. Errors, retries, and rate limits

Every error is JSON with a stable `code` and an `error` sentence:

```json
{
  "error": "Insufficient credits. You have $0.40 real-time balance but need at least $1.00 for 0.5 hour(s) minimum runtime. Please add credits to continue.",
  "code": "insufficient_credits",
  "details": { "requiredAmount": 1, "balance": 0.4 },
  "requestId": "3f2b8c1e-5d4a-4c1b-9b7e-2a6f0d8e4c11"
}
```

- Branch on `code`, never on the wording of `error`. Codes are lowercase snake_case and never change meaning. The full list is in the [error reference](https://docs.spheron.ai/api-reference#error-codes).
- Show `error` to the user, and read `details` for facts: `requiredAmount` and `balance` (dollars), `field` (the request field at fault), `retryAfter` (seconds).
- A code you do not know: fall back to the HTTP status.
- Quote `requestId` (also the `X-Request-Id` header) when the user needs to contact support.
- Some older codes also send `legacyCode`, their old UPPERCASE spelling. Ignore it; read `code`.

How to react to the common codes:

- `validation_error` (`400`): a parameter is missing or wrong; `details.field` names it when known. Fix that field; do not retry the same body.
- `authentication_required`, `invalid_api_key` (`401`): bad or missing key. Stop and ask the user (Section 1).
- `deployment_access_denied`, `team_access_denied`, `volume_access_denied`, `ssh_key_access_denied` (`403`): the key is valid but cannot act on that resource or team. Confirm the user owns it.
- `insufficient_credits` (`402`): the team balance cannot cover the action (the minimum runtime on a deploy, 30 minutes at the running rate on a start). Tell the user the amounts in `details` and ask them to add credits; do not retry until they have.
- `deployment_not_found`, `volume_not_found`, `ssh_key_not_found` (`404`): the resource does not exist or was already removed.
- `offer_unavailable` (`409`, on `POST /api/deployments`): the offer sold out or its cloud is temporarily unavailable. Refresh offers and pick another.
- `instance_busy`, `deployment_in_progress` (`409`): a change is already in flight. Wait, then retry.
- `rate_limited` (`429`): wait `details.retryAfter` seconds (the time left in the window), then retry.
- `internal_error` (`500`): server side. Retry once after a short delay; if it persists, tell the user and quote `requestId`.

Rate limits:

- `POST /api/deployments` has its own per-user limit over 15 minutes and a per-minute burst limit (enterprise users can raise it by contacting info@spheron.ai).
- Stop, start and restart: 10 calls per 5 minutes for one instance.
- All other endpoints share a general per-IP limit over 15 minutes.

Responses include `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds until the window resets). Watch `RateLimit-Remaining` and slow down before it reaches zero. Never loop deploy attempts.

---

## 10. Worked examples

### List H100 offers (authenticated, with discounts)

```bash
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/gpu-offers?search=h100&limit=5"
```

### Add an SSH key

```bash
curl -X POST "https://app.spheron.ai/api/ssh-keys" \
  -H "Authorization: Bearer <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{"name": "My Key", "publicKey": "ssh-ed25519 AAAAC3... user@host"}'
```

### Deploy a single RTX 4090 (DEDICATED)

```bash
curl -X POST "https://app.spheron.ai/api/deployments" \
  -H "Authorization: Bearer <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "spheron-ai",
    "offerId": "rtx-4090-spheron-ai-1",
    "gpuType": "rtx-4090",
    "gpuCount": 1,
    "region": "us-east-1",
    "operatingSystem": "ubuntu-22.04",
    "instanceType": "DEDICATED",
    "sshKeyId": "your_ssh_key_id"
  }'
```

### List CPU Node offers

```bash
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/gpu-offers?computeType=cpu"
```

Returns one row (`gpuType: "CPU"`, `displayName: "CPU NODE"`) whose `offers[]` entries each report `gpuCount: 0` and describe size with `vcpus` and `memory`.

### Deploy a CPU node (SPOT, Verda)

```bash
curl -X POST "https://app.spheron.ai/api/deployments" \
  -H "Authorization: Bearer <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "data-crunch",
    "offerId": "CPU.4V.16G_FIN-01_200_spot",
    "gpuType": "CPU",
    "gpuCount": 0,
    "region": "Finland 1",
    "operatingSystem": "Ubuntu 22.04",
    "instanceType": "SPOT",
    "sshKeyId": "your_ssh_key_id"
  }'
```

### Poll until running

```bash
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/deployments/<deployment-id>"
```

### Check, then terminate

```bash
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/deployments/<deployment-id>/can-terminate"

curl -X DELETE "https://app.spheron.ai/api/deployments/<deployment-id>" \
  -H "Authorization: Bearer <your-api-key>"
```

### Quote, stop, then start again

```bash
# 1. Confirm this instance can be stopped
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/deployments/<deployment-id>" \
  | jq '{supportsPause, supportsRestart, pauseUnsupportedReason}'

# 2. Quote both rates and show the user before committing
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/deployments/<deployment-id>/pause-quote"

# 3. Stop it
curl -X POST "https://app.spheron.ai/api/deployments/<deployment-id>/pause" \
  -H "Authorization: Bearer <your-api-key>"

# 4. Start it again later, on the same disk and the same public IP
curl -X POST "https://app.spheron.ai/api/deployments/<deployment-id>/resume" \
  -H "Authorization: Bearer <your-api-key>"
```

### Restart and wait for the reboot

```bash
curl -X POST "https://app.spheron.ai/api/deployments/<deployment-id>/restart" \
  -H "Authorization: Bearer <your-api-key>"

# Poll until "restarting" is false
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/deployments/<deployment-id>/reboot-status"
```

### Create and attach a volume (Verda)

```bash
# 1. Discover valid regions
curl -H "Authorization: Bearer <your-api-key>" \
  "https://app.spheron.ai/api/volumes/regions?provider=data-crunch"

# 2. Create the volume
curl -X POST "https://app.spheron.ai/api/volumes" \
  -H "Authorization: Bearer <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{"name": "my-data-volume", "sizeInGb": 100, "provider": "data-crunch", "region": "FIN-01"}'

# 3. Attach it to a running deployment in the same region
curl -X POST "https://app.spheron.ai/api/volumes/<volume-id>/attach" \
  -H "Authorization: Bearer <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{"deploymentId": "<deployment-id>"}'
```

---

## 11. Operating rules for you, the assistant

Follow these whenever you act on the Spheron API:

1. **Never guess required values.** If `offerId`, `region`, `instanceType`, or an SSH key is unknown, fetch it from the API or ask the user. Do not fabricate IDs.
2. **Copy deploy fields from one offer.** `provider`, `offerId`, `gpuType`, `gpuCount`, `region`, `operatingSystem`, and `instanceType` must all come from the same `offers[]` entry.
3. **Confirm spend before creating.** Before `POST /api/deployments` or `POST /api/volumes`, show the hourly rate and estimated cost and get explicit confirmation.
4. **Check balance.** A team with zero balance cannot deploy. Verify with `GET /api/balance` if a deploy fails or before a large deploy.
5. **Confirm before destroying.** Before `DELETE` on a deployment or volume, confirm with the user. For deployments, call `can-terminate` first and report `timeRemaining` if termination is blocked.
6. **Check before you promise a stop.** Stopping keeps the disk and drops billing to a stopped rate, but it is unavailable on some providers, machine types, and regions. Read `supportsPause` and `supportsRestart` on the deployment object first, relay `pauseUnsupportedReason` verbatim when it is set, and offer stopping before terminating whenever it is available. Never emulate a restart with a pause and a resume.
7. **Respect SPOT semantics.** Tell the user SPOT can be interrupted (`terminated-provider`). Recommend DEDICATED for work that must not be interrupted.
8. **Poll politely.** Status polling no faster than every 10 seconds; 15 to 30 seconds is the norm. Honor `429` `retryAfter`. Never loop deployment creation.
9. **Read the key from the local store, protect it.** On every run, retrieve the key from `SPHERON_API_KEY` or the local credentials file before asking the user (Section 1). Never echo the full key; reference it as `$SPHERON_API_KEY` or `<your-api-key>`.
10. **Report clearly.** After each action, state what changed (IDs, status, cost) and the next sensible step. On errors, quote the `code` and `error` message and explain the fix.
11. **Stay on the documented surface.** Use only the endpoints in this skill against `https://app.spheron.ai`. If a capability is not listed (for example resizing a deployment), say so: the path is to terminate and redeploy.
12. **Name the silicon vendor when it is not NVIDIA.** Before deploying a `spheron-am` offer, tell the user it is AMD Instinct MI300X running ROCm: `nvidia-smi` is absent, PyTorch must come from the ROCm wheel index, and CUDA-only packages and Docker images do not work. `torch.cuda.is_available()` returning `True` on ROCm is expected, because HIP reuses the `cuda` namespace; confirm with `torch.version.hip`.
13. **Read the real minimum runtime.** Do not quote 20 minutes from memory. Take `minimumRuntime` from `can-terminate`: it is the larger of the account's minimum and the machine type's provider minimum, and the latter is charged in full even on an early terminate. Quote the figure before the user commits to a short job.
14. **Do not rent a GPU for CPU work.** If the described workload never touches CUDA (data prep, builds, schedulers, queue workers, API servers), offer a CPU Node instead and name the price difference. A CPU node reports no GPU, so `nvidia-smi` and `torch.cuda.is_available()` do not work on it.

If you need access, capability changes, higher rate limits, or run into an account issue you cannot resolve through the API, direct the user to contact **info@spheron.ai**.
