> ## Documentation Index
> Fetch the complete documentation index at: https://docs.strandai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Install the Strand AI Python SDK, configure an API key, upload H&E slides, submit marker predictions, and stream results as AnnData for analysis.

The Python SDK wraps the REST API and adds:

* a resumable chunked uploader for large WSIs,
* typed dataclasses for requests and responses,
* SSE streaming for live job status,
* an optional [`AnnData`](https://anndata.readthedocs.io/) round-trip
  for results.

See the [SDK quickstart](https://docs.strandai.com/sdks/quickstart.md) for the end-to-end programmatic workflow.

## Install

```bash theme={"dark"}
pip install strand-sdk
# with bioinformatics extras (AnnData / zarr) for downloading results:
pip install "strand-sdk[anndata]"
```

Requires Python 3.12+.

If your environment can't reach PyPI, install from the GitHub mirror:

```bash theme={"dark"}
pip install "git+https://github.com/Strand-AI/strand-sdk-python.git"
```

## Configuration

| Source | Variable / argument | Default |
| - | - | - |
| Env | `STRAND_API_KEY` | required |
| Env | `STRAND_BASE_URL` | `https://app.strandai.com` |
| Arg | `Client(api_key=..., access_token=..., base_url=..., timeout=..., max_retries=...)` | n/a |

```python theme={"dark"}
from strand import Client

client = Client()                      # picks up STRAND_API_KEY from env
client = Client(api_key="sk-strand-…") # explicit
```

Resource servers acting for a user can pass a short-lived Strand AI OAuth token
instead: `Client(access_token=token)`. An explicit access token takes
precedence over API-key arguments and `STRAND_API_KEY`.

## Full pipeline

`client.predict(...)` is callable: one blocking call runs upload, submit,
wait, and download.

```python theme={"dark"}
result = client.predict(
    "biopsy.ome.tiff",
    markers=["PanCK", "CD4", "CD45"],
    output_dir="./outputs/",
)
print(f"used {result.credits_used} credits; "
      f"wrote {len(result.marker_outputs)} markers")
```

It returns a `PredictResult` with `job_id`, `status`, `credits_used`,
`marker_outputs` (paths under `output_dir`), and `results` (a `JobResults`
handle for selective reads). It raises `JobFailedError` if the job fails,
`JobTimeoutError` if the deadline elapses, and surfaces
`InsufficientCreditsError` when the org balance cannot reserve the run.

Pass `on_progress=lambda stage, frac: ...` to follow the four stages
(`"upload"`, `"submit"`, `"wait"`, `"download"`). `frac` is always a float
in `[0.0, 1.0]`: `0.0` at stage start, `1.0` at stage end, with intermediate
values where available (such as upload byte progress).

## Uploads

```python theme={"dark"}
upload = client.uploads.upload_file(
    "biopsy.svs",
    progress=lambda done, total: print(f"{done}/{total}"),
)
print(upload.id, upload.status)

# List or retrieve uploads from a later process.
page = client.uploads.list(limit=50)
upload = client.uploads.get(upload.id)
```

`upload_file` initiates a resumable session, streams 8 MiB chunks directly to
GCS, then polls the upload resource until the authenticated `OBJECT_FINALIZE`
event starts ingest. There is no finalize request. Dimensions can remain `None`
while ingest preprocessing continues; call `uploads.get(upload.id)` to refresh
them. Tune transfer chunks with `chunk_size`.

`list` pages are newest-first and stable under inserts. Pass the response's
`next_cursor` back as `cursor=` to get the next page.

### Skip re-uploads with content-hash dedup

Agentic and batch workflows often re-run on the same WSI. Set
`if_not_exists=True` on `upload_file` to skip the byte upload when the
platform already has the file:

```python theme={"dark"}
upload = client.uploads.upload_file("slide.svs", if_not_exists=True)
```

The SDK streams a sha256 of the local file and posts it on the upload-init
request. If a non-archived sample in your org already has that hash, the
existing `Upload` is returned and no bytes are transferred. On a miss the
upload proceeds normally and the hash is stored for next time.

On modern hardware, hashing a 600 MB WSI takes one or two seconds.
Leave the default (`False`) when the upload should run unconditionally.

## Samples

`client.samples.list()` uses one cursor-paginated surface for owned and public
samples. The default scope is `"mine"`; use `"public"` for the curated cohort
or `"all"` for owned samples followed by public samples.

```python theme={"dark"}
from strand import MarkerFilter, SampleFieldFilter

definitions = client.samples.fields()
tags_id = next(field.id for field in definitions if field.key == "tags")
page = client.samples.list(
    scope="all",
    limit=48,
    q="block a",
    status=["ready", "preprocessing"],
    workflow="has_results",
    marker=MarkerFilter("CD20", "completed"),
    field=SampleFieldFilter(tags_id, "eq", "trial-042"),
)
for item in page.items:
    print(item.ownership, item.id, item.app_url)
print(page.app_url)  # exact filtered browser view

if page.next_cursor:
    page = client.samples.list(scope="all", cursor=page.next_cursor)
```

Use `client.samples.fields()` to discover every field definition, including
predefined Tags and Public, before constructing `SampleFieldFilter`. Definitions
carry `origin`, `storage`, and `writable`. Public rows support `q` title search
only. Every non-`q` facet suppresses public rows under `scope="all"` and is
rejected under `scope="public"`.

List items are a discriminated union. `MineSampleSummary` carries the owned
filename, status, size, unified `fields`, and creation time.
`PublicSampleSummary` carries the public title and thumbnail. Both expose canonical
`.id` and `.app_url`; discriminate with `.ownership`.

`client.samples.get(id)` follows the same identity contract:

```python theme={"dark"}
sample = client.samples.get(item.id)
if sample.ownership == "mine":
    print(sample.name, sample.job_count)
    for job in sample.jobs:
        print(job.id, job.status, job.results_available)
else:
    print(sample.title, sample.markers)
    sample.download_to("./public-sample.zarr")
```

Owned detail includes the 50 newest prediction jobs plus `job_count`, the total
matching history. Public detail remains a download-capable `PublicSample`
handle. Its bytes use the authenticated public OME-Zarr routes.

Use one patch to rename an owned sample, replace field values, and/or set
isotropic microns per pixel:

```python theme={"dark"}
client.samples.patch(
    upload.id,
    name="Trial 42 baseline",
    fields={"tags": ["trial-042", "baseline"]},
    mpp=0.26,
)

client.samples.patch(upload.id, name=None)  # revert to filename
client.samples.patch(upload.id, fields={"tags": []})  # clear Tags
```

Omitted fields are not changed. `name=None` is distinct from omission. Each
entry in `fields` sets the complete value rather than applying an add/remove
delta. Public is read-only and can only change through the publication flow.
The user-reported `mpp` takes precedence over embedded slide metadata. See
[Set slide pixel size](https://docs.strandai.com/microns-per-pixel.md) for the REST and R equivalents.

### Cell segmentation

Cell segmentation runs per sample, not per prediction job, and costs no
credits. Uploads segment automatically unless the organization or the upload
opts out; `segment` starts segmentation on a sample that has none and retries a
failed one.

```python theme={"dark"}
state = client.samples.segmentation(sample_id)
print(state.status, state.retryable, state.credit_cost)  # credit_cost is always 0

if state.status in {"not_started", "failed"}:
    state = client.samples.segment(sample_id)
```

`segment` is idempotent: completed or in-flight work is returned as-is, and a
failed layer can be retried after the server's 60-second cooldown. Public
samples are read-only and cannot be segmented.

`state.job` is a `SegmentationJob` with `id`, `status`, `error_message`,
`created_at`, `started_at`, and `completed_at`. `state.layer` is a
`SegmentationLayer` with `id`, `entity_type`, `seg_model_version`,
`coordinate_frame`, `instance_count`, `created_at`, and artifact-availability
flags. Both values are `None` before the corresponding resource exists.

When `state.layer` reports a materialized layer, read its artifacts:

```python theme={"dark"}
if state.layer is not None:
    layer_id = state.layer.id
    manifest = client.samples.segmentation_manifest(sample_id, layer_id)
    cells = client.samples.segmentation_file(
        sample_id, layer_id, "features/instances.parquet"
    )
```

The mask is a uint32 label OME-Zarr. `features/instances.parquet` carries
`instance_id`, `local_label`, geometry, and morphology; per-marker Parquet files
carry `mean` and `median` expression joined on `instance_id`. These are the only
per-cell outputs. The `AnnData` returned by `job.download_results()` is a
pixel-grid matrix of marker predictions, not per-cell expression.

| Method | What it does |
| - | - |
| `client.samples.segmentation(sample_id)` | Read lifecycle status, retryability, credit cost, latest job and layer. |
| `client.samples.segment(sample_id)` | Start or retry segmentation. Credit-free and idempotent. |
| `client.samples.segmentation_manifest(sample_id, layer_id)` | Read the mask, morphology, and expression manifest. |
| `client.samples.segmentation_file(sample_id, layer_id, path)` | Read one artifact file's bytes. |

## Predict

```python theme={"dark"}
# Validate and price the exact request without reserving credits.
est = client.predict.submit(
    upload.id,
    markers=["CD4", "PanCK", "Ki67"],
    dry_run=True,
)
print(est.estimated_credits, est.org_balance)

# Submit the same request. Reserves credits atomically and returns a Job.
job = client.predict.submit(upload.id, markers=["CD4", "PanCK", "Ki67"])
```

| Method | What it does |
| - | - |
| `client.markers.list()` | List the markers your account can request (credit-free). |
| `client.predict.submit(..., dry_run=True)` | Validate and price without reserving credits or creating a job. Returns `Estimate`. |
| `client.predict.submit(..., dry_run=False)` | Reserve credits and enqueue. Returns `Job`. |

### Selecting a model

`predict.submit` and `predict(...)` accept an optional `model=`:

* `"v0.7"`: current dispatchable version and default.

Omit `model` to let the platform pick `"v0.7"`. The older `"v0.4"` and
`"v0.5"` labels can appear on historical jobs but are sunset for new
submissions.

```python theme={"dark"}
result = client.predict(
    "slide.svs",
    markers=["CD4", "Ki67", "PanCK"],
    model="v0.7",
)
```

`PredictResult.model` and `JobStatus.model` always carry the canonical `v0.X`
label the platform actually ran. Jobs from before the versioning rollout may
surface as `"v0.1"`, a sunset legacy label: readable on historical jobs, not
dispatchable. The retired 2026 `"v10*"` ids were removed entirely and are
rejected with a 400.

### Submit without waiting

A full pipeline run blocks for 15+ minutes. To submit without waiting for
results, pass `wait=False`. `predict(...)` returns a `Job` handle as soon as
upload and submission complete:

```python theme={"dark"}
job = client.predict("slide.svs", markers=["CD3e", "CD4"], wait=False)
print(f"submitted {job.id}")

# ...do other work, or shut down the process. The job runs server-side.

# Later (same process or a fresh one via `client.jobs.get(job_id)`):
job.wait()
adata = job.download_results()

# Or stream events:
for event in job.stream_events():
    print(event.status, event.progress)
```

Static typing follows the `wait` flag: `wait=True` returns `PredictResult` and
`wait=False` returns `Job`, so IDE completions stay correct without a runtime
check.

## Jobs

```python theme={"dark"}
# Block until terminal. Uses SSE with polling fallback:
status = job.wait(timeout=1800)

# Cancel an in-flight job and refund its reserved credits:
status = job.cancel()

# Or stream events yourself:
for event in job.stream_events():
    print(event.status, event.progress)

# Download results as AnnData (requires the `anndata` extra):
adata = job.download_results()

# Or write the raw OME-Zarr store to disk:
path = job.download_results(path="./results-zarr")

# Select native stored data plus H&E and true cell outputs without conversion:
export = job.request_export("ome-zarr", include_he=True, include_segmentation=True)

# Separately request the potentially multi-GB source stored by Strand.
# This is not processed/registered H&E; after ingest de-identification it is the
# stored de-identified copy. The 15-minute URL is a bearer link; keep it private.
# Refresh/resume may request a new link and is subject to issuance limits.
export = job.request_export("ome-zarr", include_original_upload=True)

# Or render and download a generated single-file format:
path = job.download_export("ome-tiff", "./result.ome.tiff", timeout=1800)
```

| Method | What it does |
| - | - |
| `job.refresh()` | Refetch the latest `JobStatus` snapshot. |
| `job.cancel()` | Cancel an in-flight job and return its refreshed status. |
| `job.wait(timeout=...)` | Block until `completed`, `failed`, or `cancelled`. |
| `job.stream_events()` | Iterate over SSE `JobEvent`s. |
| `job.download_results()` | Returns an `AnnData` (default) or writes to a path. |
| `job.request_export(format, ...)` | Select native OME-Zarr or start/reuse a cached ZIP/TIFF, optionally attaching processed H\&E, segmentation, or the separate stored original upload. |
| `job.get_export(format, ...)` | Poll status and refresh signed artifact URLs. |
| `job.download_export(format, path)` | Wait for and download a generated OME-Zarr ZIP or OME-TIFF file. |

Cancel is atomic: the job's status flips to `cancelled`, the credit
reservation is refunded, and any markers already written stay on the sample.
Cancellation leaves the GPU worker running and ignores its remaining outputs.
Calling `cancel` on a job that is already `completed`, `failed`, or `cancelled`
raises `BadRequestError`. `client.jobs.cancel(job_id)` is a top-level
shortcut for cancelling by id from another process.

## Whole-object signed result reads

The default result transport remains the authenticated proxy. An opt-in signed
transport downloads **whole stored objects**, including complete compressed shards,
not individual inner chunks. It requires the matching signed-result REST endpoint
to be deployed.

```python theme={"dark"}
results = job.results()
paths = ["markers/DAPI/0/zarr.json", "markers/DAPI/0/c/0/0/0"]

# No storage payload is read while this complete preflight runs.
plan = results.get_signed_files(paths, max_download_bytes=64 * 1024**2)
print(plan.total_bytes, plan.manifest_requests)  # URL-free planning values
raw_files = plan.download()

# Equivalent one-call convenience:
raw_files = results.get_files_batch(
    paths, transport="signed", max_download_bytes=64 * 1024**2,
)
```

`plan.files` contains immutable `SignedFileInfo` metadata: relative path, provider,
opaque object identity, version, size, expiry, ETag and available base64 MD5/CRC32C.
The plan retains capability URLs privately in memory, excludes them from its
representation and refuses serialization. Publicly constructed plans use the
same metadata, target, identity and complete-budget validation as API preflight;
all entries are revalidated before a download creates its storage client. Never inspect or persist its private
state. `object_id` identifies the provider/bucket/key/version tuple. Content checksums
are supplied separately.

The SDK resolves every manifest before creating a storage client or reading any
payload. It requests up to 16 paths at a time and only halves a manifest batch on
HTTP 413, with a bounded binary split. A single oversized object fails. The
complete deduplicated payload must fit `max_download_bytes` (64 MiB by default),
not merely each individual manifest. Larger complete downloads need an explicit
larger budget. The budget covers payload bytes only. Process memory and combined
API-plus-storage traffic require separate limits.

Storage reads use a fresh credential-free client with environment credentials/
proxies and redirects disabled, identity content encoding and finite timeouts.
Every read checks expiry, response generation/version, exact length and all
available full-object MD5/CRC32C checksums. GCS metadata ETags can differ from
signed-GET ETags; ETags are never treated as content digests. Expiry, changed
versions, unexpected targets/encodings, truncation and failed checksums abort the
call without a partial map, automatic URL refresh, latest-version resolution or
proxy fallback. Accurate client UTC time is required for expiry checks.

Advanced request/byte guards can supply
`plan.download(storage_client_factory=factory)` or the same keyword to
`get_files_batch`. The zero-argument factory must return a **fresh** `httpx.Client`
with `trust_env=False`, no auth/cookies/credential headers and a no-retry transport;
the SDK owns and closes it. Instrument that client's transport and the SDK's
existing authenticated API client to account for both HTTP planes, including
failed attempts. Do not reuse an old app-host-only guard. Signed manifest bodies
must be byte-counted/hashed without being persisted, and provider URLs must be
redacted before guard/debug logging. Provider error bodies may echo signatures
and must not be captured.

The SDK redacts standard `httpx`/`httpcore` log records only within signed I/O
contexts and emits fixed, URL-free errors with no raw exception chains. Other
threads and ordinary API logging are unchanged. The SDK checks its logging
factory after the storage-client callback, before provider requests and at close.
A detected replacement stops the operation and closes the client. Do not replace
the global logging factory during active I/O. Arbitrary concurrent factory
changes, custom hooks that dump requests, private-state inspection and custom
user logging are outside this protection.

`transport="signed"` with `layout="inner"` is invalid. Proxy layout, framing and
`verify_sha256` behavior remain unchanged. `verify_sha256` controls proxy frame
checks; `max_download_bytes` bounds the complete signed payload. Signed checksum
checks cannot be disabled with `verify_sha256=False`.

## Errors

All errors inherit from `StrandError`. Typed subclasses map HTTP codes 1:1 for
specific `except` clauses:

```python theme={"dark"}
from strand import (
    InsufficientCreditsError,
    JobFailedError, JobTimeoutError,
)

try:
    job = client.predict.submit(upload.id, markers=["CD4"])
    job.wait(timeout=600)
except InsufficientCreditsError as e:
    print(f"need {e.required} credits; top up first")
except JobFailedError as e:
    print(f"job failed: {e}")
```

| Exception | HTTP |
| - | - |
| `AuthError` | 401 |
| `BadRequestError` | 400 |
| `UnknownMarkerError` | 400 (subclass of `BadRequestError`; carries `.unknown`, `.known_subset`) |
| `InsufficientCreditsError` | 402 (carries `.required`) |
| `NotFoundError` | 404 |
| `JobFailedError` | n/a (terminal status `failed`) |
| `JobTimeoutError` | n/a (`wait()` timeout) |
| `UploadError` | n/a (GCS resumable session failed) |

### Catch unknown markers

Both modes of `predict.submit` validate marker names against the platform's
panel before reserving credits or queueing a job. Unknown names
surface as `UnknownMarkerError`:

```python theme={"dark"}
from strand import UnknownMarkerError

try:
    client.predict.submit(upload.id, markers=["CD3e", "MysteryMarker"])
except UnknownMarkerError as e:
    print("unknown:", e.unknown)              # ["MysteryMarker"]
    print("try one of:", e.known_subset[:5])  # sample of valid names
```

### Recover from a failed pipeline without re-uploading

If `client.predict(...)` raises after the upload step succeeded, the
resulting `upload_id` is attached to the error so you can resume the job
without paying to re-upload the WSI:

```python theme={"dark"}
from strand import JobFailedError

try:
    result = client.predict("slide.svs", markers=["CD3e", "CD4"])
except JobFailedError as e:
    if e.upload_id:
        # Re-submit against the same upload; no re-upload needed.
        job = client.predict.submit(e.upload_id, markers=["CD3e", "CD4"])
        job.wait()
```

The same attribute appears on `JobTimeoutError`, `InsufficientCreditsError`,
and other `StrandError` subclasses raised mid-pipeline.

## Public surface

```python theme={"dark"}
from strand import (
    Client, Job, JobEvent, JobStatus, JobResults,
    Upload, UploadList, Estimate, ModelId,
    MineSampleSummary, PublicSample, PublicSampleSummary,
    Sample, SampleJob, SampleList, SampleScope, UNSET,
    SegmentationJob, SegmentationLayer, SegmentationState,
    PredictResult, ResultExport,
    AuthError, BadRequestError, InsufficientCreditsError,
    JobFailedError, JobTimeoutError, NotFoundError,
    StrandError, UnknownMarkerError, UploadError,
)
```

## See also

* [SDK quickstart](https://docs.strandai.com/sdks/quickstart.md): upload, price, submit, wait, and download.
* [REST API overview](https://docs.strandai.com/api/overview.md): the underlying HTTP surface.
* [Pricing](https://docs.strandai.com/pricing.md): how retained model-grid tissue positions and markers determine credits.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.