Skip to main content
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 round-trip for results.
See the SDK quickstart for the end-to-end programmatic workflow.

Install

Requires Python 3.12+. If your environment can’t reach PyPI, install from the GitHub mirror:

Configuration

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.
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

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:
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.
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:
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:
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 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.
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:
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.

Predict

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.
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:
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

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.
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:

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:

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:
The same attribute appears on JobTimeoutError, InsufficientCreditsError, and other StrandError subclasses raised mid-pipeline.

Public surface

See also