> ## Documentation Index
> Fetch the complete documentation index at: https://weights.fyi/run/llms.txt

# Python SDK

`weights.sdk` declares a ComputePlan in Python, with its tenancy, schedule, stages and their data, and admits the whole plan in one call to [POST /v1/compute/plans](/run/docs/reference/compute-plans-create.md). Nothing has to be registered first: dataset mounts and shard lists travel inside the plan.

> **Status.** Added to the `weights` Python package on 2026-10-31; it needs Python 3.12 or later and nothing beyond the standard library.

## A plan in one call

Two compressed JSONL files already in your tenant's storage, classified as one stream. `Schedule.scavenger_stream` makes the plan standing: accepted at once, it runs only alongside work already running, so it can wait, unbilled, until its window closes (`Schedule.standard` starts a model itself). The example checks the plan before submitting it:

```python
import os
from weights.sdk import Dataset, DatasetShard, Plan, Schedule, Tenancy, WeightsClient

plan = Plan("pages-2026-10-31",
            tenancy=Tenancy.platform_shared("tenant_12", org_slug="acme", max_budget_usd_micros=5_000_000),
            schedule=Schedule.scavenger_stream(deadline_seconds=86_400))
root = "r2://tenants/tenant_12/pages"
pages = Dataset.r2(root, name="pages", shards=[
    DatasetShard(pack_id="pages-0", source_uri=f"{root}/part-0.jsonl.zst", sha256=PART_0_SHA256,
                 item_count=50_000, compressed_bytes=4_194_304),
    DatasetShard(pack_id="pages-1", source_uri=f"{root}/part-1.jsonl.zst", sha256=PART_1_SHA256,
                 item_count=48_200, compressed_bytes=4_063_232),
])
plan.classifier_drain("classify", model="laya-page-role", dataset=pages,
                      output_uri="r2://tenants/tenant_12/results/pages")

client = WeightsClient("https://weights.fyi/run", os.environ["WEIGHTS_API_KEY"])
body = plan.to_dict()
verdict = client.dry_run(body)   # nothing is admitted or charged
if not verdict["ok"]:
    raise SystemExit([f'{finding["code"]}: {finding["message"]}' for finding in verdict["findings"]])
submission = client.submit(body, verify_source=True)
print(submission.plan_id, submission.state, submission.source_probe["verified"])
```

`PART_0_SHA256` and `PART_1_SHA256` stand for each file's SHA-256. The key needs `submit` to admit the plan and `read` to follow it, and the workspace must hold a grant on the tenant and organisation named.

`client.dry_run` is the [dry run](/run/docs/reference/compute-plans-dry-run.md), the service's own check of the same body: `ok` is false, with `findings`, when the plan rules, your tenancy grant or a model's pinned release would refuse it; `verify_source=True` reads the sources too. With `verify_source=True`, `submit` reads every source by a short byte range before anything is written: an unreadable one refuses the plan with a `source_*` code ([Errors and limits](/run/docs/errors.md#source-verification)) and leaves nothing behind. `submit` also runs the plan validator locally when the package's native library is present (`validate_locally=True` insists on it, `False` skips it); it checks the plan rules only.

## Tenancy and schedule

| Choose | When |
|---|---|
| `Tenancy.platform_shared(tenant_id, org_slug=..., max_budget_usd_micros=...)` | The service's shared capacity, with any schedule. |
| `Tenancy.workspace_byoc(...)` | Your workspace's own enrolled workers ([Bring your own model](/run/docs/your-model.md)), and no other workspace's. The builder refuses a schedule that could start paid capacity; a model the service already runs may still take a stage. |
| `Tenancy.hybrid(...)` | Your own workers and the shared capacity, whichever asks for work first. |
| `Schedule.standard(deadline_seconds=..., max_hourly_usd_micros=...)` | A campaign, batch or training plan that may start a model within its hourly ceiling. |
| `Schedule.scavenger_stream(deadline_seconds=...)` | Standing: it runs only alongside work that is already running, never starts a model and never keeps one running. |
| `Schedule.piggyback(deadline_seconds=...)` | Standing, riding capacity started for other work. |

Give a schedule exactly one of `deadline_seconds` or `until_ms`; there is no default window. `incomplete="ok"` lets a stream settle at its deadline with packs left over, reported as an `incomplete_*` outcome, and makes the plan standing. A standing plan can be promoted later with `client.promote_plan(plan_id, max_hourly_usd_micros=...)` ([promote](/run/docs/reference/compute-plans-promote.md)).

The plan's `idempotency_key` (its `operation_key`, `plan_id` by default) makes a resubmission of the same plan return it; different content under the same key is refused with `409`. The window opens when the plan is compiled, so pin `window_start_ms` on the schedule when you resubmit a plan later.

## Stages and data

Add stages with the `Plan` methods below, or with the same-named `Stage` constructors and `plan.add(stage)`. `depends_on` and `checkpoint_from` take a stage or its id. A fine-tune's `dataset` takes a `Dataset`, a URI, or a stage object, whose `output_uri` it trains on after that stage completes; a stage id there is read as a URI, with no wait. A stream stage's `dataset` and `datasets` take `Dataset` objects only.

| Method | Work |
|---|---|
| `classifier_drain(stage_id, model=..., output_uri=...)` | Classify every item of a stream; `checkpoint_from` reloads a fine-tune stage's checkpoint and waits for it. |
| `embedding_drain(stage_id, model=..., aspect=..., output_uri=...)` | Embeddings for one or more aspects (`offerings`, `profile`), with `dtype` and `dimensions`; `checkpoint_from` reloads a fine-tune stage's checkpoint. |
| `llm_batch_drain(stage_id, model=..., est_input_tokens=..., est_output_tokens=..., output_uri=...)` | Batch generation over every item with the model as served. With `checkpoint_from=` a LoRA student's finetune stage, every item is answered by that stage's adapter on `model`, the base it was trained on: the worker verifies the adapter against its checkpoint receipt, loads it into the engine before the first request, and refuses an adapter of another base (`lora_base_mismatch`) or an engine without runtime LoRA loading (`lora_serving_unavailable`) rather than answer with the unadapted base model. |
| `scavenge_label(stage_id, seat_model=..., output_uri=...)` | Teacher labels from agent seats (`haiku`, `claude-haiku-5-5`, `luna`, `luna-6`); standing schedules only. |
| `finetune(stage_id, base_model=..., recipe=..., steps=..., dataset=..., output_uri=...)` | Train on a `Dataset`, a URI, or another stage object's output, writing the checkpoint under `output_uri`; `checkpoint_from` starts from an upstream stage's completed checkpoint (`SFT -> DPO`). |
| `rl(stage_id, base_model=..., steps=..., dataset=..., output_uri=...)` | Verifiable RL (GRPO, `laya-student-lora-grpo/v1`) on `laya-rlvr-prompt/jsonl` rows: the student's completions of each prompt are scored by a deterministic verifier. Settings, each the recipe's own when left out: `verifier`, `num_generations` (2 to 16), `temperature` (above 0, to 2), `max_completion_tokens` (1 to 4096), `kl_ref_coef` (0 to 1). `checkpoint_from` chains `SFT -> GRPO`. |
| `distill(stage_id, base_model=..., steps=..., dataset=..., output_uri=...)` | On-policy distillation (OPD, `laya-student-lora-opd/v1`) on the same rows: `teacher_model`, `distill_coef` (above 0, to 10), `reward_weight` (0 to 10), and `rl`'s settings except `kl_ref_coef`. `checkpoint_from` chains `SFT -> OPD`. |
| `live_session_pool(stage_id, model=..., ...)` | Parallel coding-agent sessions held for your own harness. |

### Chaining Fine-Tune -> Bulk Inference Drain (and SFT -> GRPO)

Pass `checkpoint_from=<stage>` (or its `stage_id`) to a downstream `classifier_drain`, `embedding_drain`, `finetune`, `rl` or `distill` stage. The SDK adds the upstream stage to `needs` and sets `workload.reload_checkpoint_from_stage`; when the upstream `finetune` completes, its checkpoint reaches the downstream stage's lease as `lease.reload_checkpoint_uri`:

```python
chained_plan = Plan("leadgen-jev-scavenge-experiments-20261102",
                    tenancy=Tenancy.platform_shared("tenant_12", org_slug="acme", max_budget_usd_micros=25_000_000),
                    schedule=Schedule.piggyback(deadline_seconds=86_400, max_hourly_usd_micros=3_500_000))

# Step 1: Fine-tune Fastino GLiDE 28B on a zero-copy dataset pointer
sft = chained_plan.finetune(
    "sft_fastino_glide_28b",
    base_model="fastino-glide-28b",
    recipe="laya-student-lora-sft/v1",
    steps=1843,
    dataset=Dataset.r2("r2://tenants/tenant_12/datasets/scavenge-teacher/2026-11-02-r1/sft/manifest.json",
                       name="ds_8126a1ce5538c9eb358c6aa9",
                       sha256="57f9bfa243e5158181b1a5996157c5d056421c5bda1f4b19454bf6071c307a63",
                       format="laya-student-sft/v1"),
    output_uri="r2://tenants/tenant_12/checkpoints/sft_fastino_glide_28b",
)

# Step 2: Reinforce the Step 1 adapter with verifiable rewards (GRPO) on laya-rlvr-prompt/jsonl rows:
# eight completions a prompt, every row scored by the one verifier the stage names
chained_plan.rl(
    "grpo_fastino_glide_28b",
    base_model="fastino-glide-28b",
    steps=500,
    checkpoint_from=sft,
    verifier="grounded_json_v1",
    num_generations=8,
    dataset=Dataset.r2("r2://tenants/tenant_12/datasets/scavenge-teacher/2026-11-02-r1/rlvr/manifest.json",
                       name="ds_3c0d9f1e2b7a4c6d8e5f1a2b",
                       sha256="a3f1c2d4e5b60718293a4b5c6d7e8f90112233445566778899aabbccddeeff00",
                       format="laya-student-rlvr/v1"),
    output_uri="r2://tenants/tenant_12/checkpoints/grpo_fastino_glide_28b",
)
chained = client.submit(chained_plan)
```

A stream stage reads one of three inputs: a `Dataset` with shards, made into packs as workers ask for work and sealed once all are packs (`open_stream=True` keeps it open); a `manifest_uri`; or `open_stream=True` alone, to append packs yourself. With no shards to count from, `classifier_drain` and `embedding_drain` need `total_items`, and `llm_batch_drain` needs `total_items_hint` (it takes no `total_items`); `scavenge_label` needs neither.

| Data | Form |
|---|---|
| `Dataset.r2`, `.s3`, `.hf`, `.https`, `.oci` | One object, pinned by `sha256`, mounted with `hydration_mode` `jit` or `prestage` at `mount_path`; or the root of a shard list. `Dataset(name, source_uri=...)` takes any other supported scheme. |
| `Dataset.sharded(name, shards)` | Shards only, for a stream stage. |
| `DatasetShard(pack_id, source_uri, sha256, item_count, ...)` | One pack's input: a whole object with its `compressed_bytes`, or `byte_start` and `byte_end` of one. |

## Follow and steer it

```python
from weights.sdk import WeightsAPIError

stream = submission.stream("classify")
print(stream.status()["state"], stream.backlog()["counts"])
try:
    print(stream.pack_status("pages-0")["state"])
except WeightsAPIError as error:
    if error.code != "compute_pack_not_found":
        raise
    print("pages-0 is not a pack yet")
for event in client.compute_events(after_seq=0):
    print(event["seq"], event["kind"]["event_type"])
```

A shard becomes a pack only when work can start on it, and a standing plan waits for running work, so its packs can be absent at first: until then `pack_status` answers `404 compute_pack_not_found` and the backlog counts none.

| Call | Does |
|---|---|
| `stream.backlog()`, `stream.pack_status(pack_id)`, `stream.status()` | Counts, available room and next lazy packs; one pack's state and receipt; the stage's progress ([backlog](/run/docs/reference/streams-packs-list.md), [pack](/run/docs/reference/streams-packs-get.md)). |
| `stream.append_pack(shard)`, `stream.append_packs(shards)`, `stream.materialize()`, `stream.seal()` | Add one pack or a batch of 1–64 packs (probed concurrently by default), fill the lookahead now, close the stream to new packs. |
| `stream.retry(operation_key=...)`, `stream.accept_loss(operation_key=..., reason=...)` | Send dead-lettered packs back to work, or accept their loss; both replay safely by key. |
| `client.get_plan`, `client.list_plans`, `client.iter_plans`, `client.cancel_plan` | Read one plan, a page of plans, every plan page by page, or cancel one. |
| `client.create_trace_sink`, `list_trace_sinks`, `delete_trace_sink`, `test_trace_sink` | Your [trace destinations](/run/docs/tracing.md#your-own-destinations); a `webhook` one's `id` is a plan's `notify_sink_id`. |
| `client.quote_finetune(recipe=..., train_rows=..., options=...)`, `client.create_finetune(dataset=..., recipe=..., options=...)` | One training job outside a plan: its estimate with the options it would run with ([POST /v1/quote](/run/docs/reference/quote-finetune-post.md)), and the job itself ([POST /v1/jobs](/run/docs/reference/jobs-create-finetune.md)); give `idempotency_key` when the call may be sent twice. |
| `weights compute validate`, `dry-run`, `submit`, `list`, `show`, `promote`, `cancel`, `quote` | The same calls from a shell, each printing the answer as JSON: a plan from `--file PLAN.json`, or a named plan from `--preset NAME --datasets FILE` (`weights.sdk.preset_plan`). `weights compute --help` lists the flags. |

`client.request(method, path, ...)` reaches any other call of the [reference](/run/docs/reference.md) with the same key.

## Standing streams and push events

A standing open stream can take its work in waves, told by its own events when to send the next one. Name a `webhook` [destination](/run/docs/tracing.md#compute-events-on-a-webhook) in `notify_sink_id`, and each event reaches your receiver signed:

```python
from weights.sdk import compute_events, verify_webhook

sink = client.create_trace_sink("waves", RECEIVER_URL, kind="webhook")
secret = sink["signing_secret"]   # answered once: keep it where your receiver reads it
standing = Plan("waves-2026-11-20",
                tenancy=Tenancy.platform_shared("tenant_12", org_slug="acme", max_budget_usd_micros=5_000_000),
                schedule=Schedule.scavenger_stream(deadline_seconds=86_400), notify_sink_id=sink["id"],
                notify_events=["pack_completed", "stage_completed", "plan_completed"])
standing.classifier_drain("pages", model="laya-page-role", open_stream=True, total_items=EXPECTED_ITEMS,
                          output_uri="r2://tenants/tenant_12/results/waves")
pages = client.submit(standing).stream("pages")
pages.upload_pack("wave-0", WAVE_0, item_count=WAVE_0_ITEMS)

def receive(headers, body: bytes) -> None:   # your receiver, once per delivery
    for event in compute_events(verify_webhook(secret, headers, body, max_age_seconds=MAX_AGE_SECONDS)):
        if event["event"] == "pack_completed" and first_time(event["event_id"]):
            wave = next_wave(pages.read_output(event["pack_id"]))
            if wave:
                pages.upload_pack(wave["pack_id"], wave["data"], item_count=wave["items"])
            else:
                pages.seal()   # stage_completed, then plan_completed, follow
```

`RECEIVER_URL` is your receiver's `https` address; the other capitals and the functions stand for your own values and code.

| The standing plan | Does |
|---|---|
| While it waits | Costs nothing: admission starts no model and holds nothing running, so the plan waits, unbilled, until its window closes. |
| When work is already running | Its packs run beside that work, and they never keep a model running. |
| `pack_completed` | Carries the pack's `pack_id`, `ordinal`, `output_uri`, `output_sha256` and `items_completed`: register the next wave from it. |
| `seal()` | Closes the stream; `stage_completed` and `plan_completed` follow, with `outcome` and `coverage`. |
| Delivery | At least once, oldest first: key on `event_id`. `notify_events` narrows what is pushed; `[]` is every event. `client.compute_events` still reads them all. |
| From a shell | `weights sinks create URL --pipe \| <intake>` hands the new webhook's `id`, `url` and one-time `signing_secret` to your receiver's intake as one JSON line (`weights.trace-sink-credential/v1`); then `weights compute submit FILE` with the plan's JSON, or `weights compute submit --preset NAME --datasets FILE --notify-sink-id ID` for a named plan (`--notify-event NAME` narrows what is pushed). Both commands read the deployment from `WEIGHTS_API_URL`, then `WEIGHTS_PUBLIC_URL`. |

## Errors and retries

Every SDK error is a `WeightsError`. `PlanError` is the builder refusing before any call; `PlanValidationError` is the local validator's refusal; `WeightsAPIError` is any answer outside 2xx, with `status`, `code` and the decoded `body`.

Retries are off by default; with `retries` and `backoff_seconds` the client sends a `502`, `503` or `504` again up to `retries` times, after the answer's `Retry-After`, or else after `backoff_seconds` doubled on each attempt:

| Call | Sent again after a lost answer |
|---|---|
| Reads, `dry_run` | Safe. |
| `submit` | Answers the same plan, by the plan's key. |
| `append_pack`, `upload_pack` | Answer the first registration, by identical content. |
| `retry`, `accept_loss` | Replay by their `operation_key`. |
| `seal`, `cancel_plan` | Answer as the first. |
| `promote_plan` | Not safe: a second promotion answers `409`. Leave retries off for it and read the plan after a lost answer. |
| `create_trace_sink` | Not safe: a repeat adds a second destination with its own secret. |
| `client.request` | As safe as the call it reaches. |

By default the client refuses plain `http://` except on loopback (`allow_plain_http=True` permits it inside a private network, where your key then travels unencrypted), and it never follows a redirect, so your key goes nowhere else.
