# Cancel a job Source: https://docs.strandai.com/api-reference/endpoint/cancelJob POST /jobs/{id}/cancel Cancels an active inference job and refunds its credit reservation. Active segmentation is owned by its fenced lifecycle and returns 409; terminal jobs return 400. # Publish an artifact Source: https://docs.strandai.com/api-reference/endpoint/createArtifact POST /artifacts Store an immutable, organization-private HTML case report with provenance and bundled assets. Store a completed HTML report and its assets. Requires `samples:write` and `results:read`. Creation is credit-free; organization and author come from authentication. `description` is required provenance: summarize the data sources, methods and limitations. Titles are trimmed to 1 to 200 characters; descriptions to 1 to 10,000 characters. Blank values are rejected. ```bash theme={"dark"} curl https://app.strandai.com/api/v1/artifacts \ -H "Authorization: Bearer $STRAND_API_KEY" \ -H "Content-Type: application/json" \ -d '{"title":"Study memo","description":"Public example; manual counts; research use only.","html":"

Study memo

Example report.

","sample_ids":[],"job_ids":[],"assets":[]}' ``` * `sample_ids` and `job_ids` are optional arrays of up to 100 unique UUIDs each. Linked resources must belong to the authenticated organization. * `html` is the nonempty UTF-8 entry document, stored as `index.html`. * `assets` accepts up to 128 `{path, content_base64}` objects. Use canonical base64 and unique relative paths such as `assets/figure.png`. Path segments use ASCII letters, digits, `_`, `-` and `.` (including Zarr metadata such as `.zattrs`); dot-only segments `.` and `..` are rejected. Paths are at most 240 characters. Traversal, absolute paths, `index.html` and `_strand_bundle.json` are rejected. * HTML plus decoded assets must fit within **32 MiB**. The application limits encoded JSON to **46 MiB**, but deployment proxy limits can be lower. For example, a 32 MiB encoded-request edge limit leaves roughly 24 MiB for decoded base64 assets, before JSON/HTML overhead. The 32 MiB bundle cap is not a guarantee that every deployment accepts a request of that size. Multipart and signed-upload flows for larger bundles are not implemented. * Reference bundled assets using relative URLs; external network resources are blocked when the report renders. A **201** response contains snake\_case metadata, provenance, linked IDs, auth-derived author, `entry_html_path`, `size_bytes`, `sha256`, `created_at`, and `url`. The relative in-app URL requires an organization member's signed-in session, and metadata responses omit HTML and asset bytes. Invalid input, bundle paths or foreign linked resources return **400**; oversized encoded JSON returns **413**. A deployment proxy may reject a smaller request before it reaches this endpoint. ### Python and MCP ```python theme={"dark"} artifact = client.artifacts.create( title="Study memo", description="Public example; manual counts; research use only.", html="

Study memo

", ) print(artifact["url"]) ``` MCP `create_artifact` accepts the same fields and sends report content through the tool call. Keep credentials and patient identifiers out of report content. Artifacts are immutable, with no edit-in-place API. To remove one, use [Delete an artifact](/api-reference/endpoint/deleteArtifact). # Create a custom sample field Source: https://docs.strandai.com/api-reference/endpoint/createSampleField POST /sample-fields Create an organization-scoped field definition with an optional description. Credit-free. Requires samples:write. Create a definition before assigning its values with [Update a sample](/api-reference/endpoint/patchSample). ```bash theme={"dark"} curl https://app.strandai.com/api/v1/sample-fields \ -H "Authorization: Bearer $STRAND_API_KEY" \ -H "Content-Type: application/json" \ -d '{"label":"Study cohort","valueType":"single_select","options":["Discovery","Validation"],"description":"Study arm used for analysis"}' ``` A successful request returns **201** with the new definition, including its `id`, `key`, `label`, `valueType`, `origin`, `storage`, `writable`, `options`, and nullable `description`. The same definition appears in [List sample fields](/api-reference/endpoint/listSampleFields). * Omit `key` to derive it from the label: `Study cohort` becomes `study_cohort`. Explicit keys use 1 to 50 lowercase letters, digits, or `_`, starting with a letter. Reserved system keys cannot be created. * Types: `text`, `number`, `date`, `checkbox`, `single_select`, `multi_select`. `type` is an alias for `valueType`. If both are supplied they must agree. * Select types require 1 to 100 options, each 1 to 80 characters and unique ignoring case. Other types cannot specify options. * Descriptions are optional, trimmed, and limited to 1,000 characters. Empty or whitespace-only descriptions become `null`. NUL characters are rejected. * Invalid input returns **400**. Duplicate keys, case-insensitive duplicate labels, or exceeding 100 custom fields per organization returns **409**. Built-in fields do not count toward the cap. In the dashboard, **Manage Fields** lets you create and edit descriptions. Descriptions appear in field-chip tooltips and the field value popover. # Initiate upload Source: https://docs.strandai.com/api-reference/endpoint/createUpload POST /uploads Initiate a resumable upload by registering an H&E slide's filename, size, and content type, and receive a signed GCS URL to PUT the slide bytes to. # Delete an artifact Source: https://docs.strandai.com/api-reference/endpoint/deleteArtifact DELETE /artifacts/{id} Permanently remove an organization report and revoke access to its bundled files. Requires `samples:write`. Deletes the report for everyone in the organization. Linked samples and jobs are retained. This operation cannot be undone. A **200** response contains `{"id": "", "deleted": true}`. Missing artifacts and IDs from another organization return **404**. Report and asset access is revoked when the database row is removed. Storage cleanup is best-effort, so a storage failure can leave inaccessible objects for later cleanup. ```python theme={"dark"} client.artifacts.delete(artifact_id) ``` The dashboard provides Delete actions with explicit confirmation on the artifact list and report page. Use the dashboard, REST or Python SDK for permanent deletion. The curated MCP catalog omits this operation. # Get an artifact Source: https://docs.strandai.com/api-reference/endpoint/getArtifact GET /artifacts/{id} Read report metadata, provenance and its organization-gated in-app URL. Requires `samples:read` and `results:read`. Credit-free. Supply an artifact UUID. The response contains `id`, `org_id`, `title`, `description`, `sample_ids`, `job_ids`, `author_type` (`user` or `agent`), `author_id`, `entry_html_path` (`index.html`), `size_bytes`, `sha256`, `created_at` and `url`. The URL is a relative in-app path such as `/artifacts/` and requires organization login. HTML and bundled asset bytes are not returned. ```python theme={"dark"} artifact = client.artifacts.get(artifact_id) print(artifact["description"], artifact["url"]) ``` MCP `get_artifact` takes `artifact_id`. Missing artifacts and IDs belonging to another organization return **404**. Responses are private and not cached. # Get job Source: https://docs.strandai.com/api-reference/endpoint/getJob GET /jobs/{id} Fetch a snapshot of a prediction job's status, progress, reserved credits, and result path. Useful for polling clients that do not consume the SSE stream. # Download result file Source: https://docs.strandai.com/api-reference/endpoint/getJobResultFile GET /jobs/{id}/results/files/{path} Proxies a single file from the OME-Zarr result store. `path` is the path within the zarr store (e.g. `zarr.json`, `CD3/zarr.json`, `CD3/c/0/0/0`). Authenticated via the same bearer API key as the rest of `/api/v1/`; org-scoped to the job. Use this when walking the zarr tree from a client that does not have direct GCS credentials. # Read result files in a batch Source: https://docs.strandai.com/api-reference/endpoint/getJobResultFilesBatch POST /jobs/{id}/results/files Reads delivered result files with per-item binary framing. Raw layout accepts up to 16 paths; inner layout accepts up to 256. Duplicate paths produce one record. Records may arrive in shard order. Each record is a uint32 little-endian JSON header length, UTF-8 JSON header (path, status, length, sha256), then length body bytes. Missing files have status 404, length 0 and sha256 null. A zero header length terminates the stream; a missing terminator means failure. Item payloads are capped at 64 MiB, excluding framing. Exceeding the budget emits a status 413 record with error batch_payload_limit_exceeded, length 0 and sha256 null, then the terminator. Storage errors abort the stream without a terminator. Only zarr.json, _marker_frame.json, he/ and delivered markers/ paths are accepted. # Get results URL Source: https://docs.strandai.com/api-reference/endpoint/getJobResults GET /jobs/{id}/results Returns a signed GCS URL for the OME-Zarr root metadata (`zarr.json`) plus the `resultBasePath` of the zarr store. Useful for clients that already have GCS credentials. SDK clients should generally prefer `GET /jobs/{id}/results/files/{path}` (API-key authenticated) for walking the tree. # Get a public sample thumbnail Source: https://docs.strandai.com/api-reference/endpoint/getPublicSampleThumbnail GET /public/samples/{publicId}/thumbnail Authenticated JPEG thumbnail for a public sample. Streamed through this release-keyed endpoint (never a signed GCS URL). Never reserves or spends credits. # Stream a public sample's OME-Zarr Source: https://docs.strandai.com/api-reference/endpoint/getPublicSampleZarr GET /public/samples/{publicId}/zarr/{path} Authenticated byte proxy for a public sample's OME-Zarr store — the H&E image (`he/...`) and every pinned marker channel (`markers/{marker}/...`). The root manifest is `zarr.json`. This is the way to read the actual marker pixel data. Only the `he/` and `markers/` namespaces are served; everything else is denied. Never reserves or spends credits. # Get result export Source: https://docs.strandai.com/api-reference/endpoint/getResultExport GET /jobs/{id}/exports Poll a format-driven result export and refresh expiring artifact URLs. Pass the same format and content-selection query used for the request. Pending/running exports return `202`; ready native or generated artifacts return `200`. # Get an owned or public sample Source: https://docs.strandai.com/api-reference/endpoint/getSample GET /samples/{id} Resolve an org-owned sample id first, returning its curated detail and inference-job history. Otherwise resolve the same path value as a currently-public share UUID and return only public-safe detail. Returns an owned sample with its current and historical inference jobs, or a public sample when the path id is a public share UUID. The required `ownership` field discriminates the two response shapes. # Read segmentation artifact file Source: https://docs.strandai.com/api-reference/endpoint/getSegmentationFile GET /samples/{id}/segmentation/{layerId}/files/{path} Read one org-scoped mask OME-Zarr, cell morphology, marker-expression, or provenance file. Use paths from the layer manifest. `mask/...` addresses the uint32 OME-Zarr store, `features/instances.parquet` contains cell IDs, mask labels, geometry, and morphology, and `features/markers/{marker}.parquet` contains per-cell mean/median expression joined by `instance_id`. # Get segmentation manifest Source: https://docs.strandai.com/api-reference/endpoint/getSegmentationManifest GET /samples/{id}/segmentation/{layerId}/manifest Read the mask, cell morphology/geometry, marker-expression, and provenance contract. Mask pixels are uint32 local labels. Morphology and per-marker Parquet tables join by `instance_id`; these are true cell observations, unlike the pixel-grid matrix produced by ordinary prediction-to-AnnData conversion. # Preflight signed result files Source: https://docs.strandai.com/api-reference/endpoint/getSignedJobResultFiles POST /jobs/{id}/results/files/signed Returns single-object signed GET capabilities for raw stored result objects only, never decoded inner chunks or prefix access. All paths must pass the same organization, sample, readiness and delivered-marker gates as batch reads. Only zarr.json, _marker_frame.json, he/ and delivered markers/ paths are accepted. Duplicate paths are deduplicated in first-requested order. At most 16 paths, 64 MiB per object and 64 MiB total; all authorization, metadata and budget checks precede signing. The server fixes a common expiry no later than 120 seconds after preflight; provider credential expiry or object deletion can make a capability unusable sooner. URLs are replayable bearer secrets until effective expiry, not single-use or application-revocable. Changing API access does not revoke an issued URL. Direct storage reads incur provider requests/egress and bypass application read-byte accounting. No client storage credentials are required. A signed whole-object URL does not restrict the recipient to a Range. objectId is SHA-256 of compact UTF-8 JSON [provider,bucket,canonicalKey,version], an identity hash, NOT a content checksum. Checksums are provider base64 when available; ETag is opaque. Returns short-lived, version-pinned links for whole stored result objects. This is not an inner-chunk or byte-range endpoint. The existing authenticated result proxy remains available. The server validates ownership, marker delivery, all object metadata and the 64 MiB total before signing any link. A request accepts 1 to 16 paths, including duplicates, and returns deduplicated files in first-requested order. Any failure rejects the whole manifest. The expiry is fixed at 120 seconds. > [!WARNING] > > URLs are bearer capabilities. Keep the response in memory; do not save it to > request/response logs, notebooks, receipts or exception bodies. Record only > byte counts, hashes and URL-free metadata. Never send Strand credentials or > cookies to the storage provider, and do not follow redirects. `objectId` fingerprints the provider/bucket/key/version identity. Consumers must verify the pinned generation/version, exact length and available full-object MD5/CRC32C checksums. ETags are opaque and are not SHA-256 or necessarily MD5. The Python SDK exposes complete preflight through `JobResults.get_signed_files()` and direct reads through `get_files_batch(..., transport="signed")`. MCP's `download_results` export workflow is unchanged; this endpoint does not add a URL-printing MCP tool. # Get an upload Source: https://docs.strandai.com/api-reference/endpoint/getUpload GET /uploads/{id} # List artifacts Source: https://docs.strandai.com/api-reference/endpoint/listArtifacts GET /artifacts List organization-private report metadata, filtered by linked samples or jobs. Requires `samples:read` and `results:read`. Credit-free. Optional `sample_id` and `job_id` UUID filters combine with AND. Pagination uses `limit` (1 to 100, default 50) and `offset` (0 to 100000, default 0). The response is `{count, artifacts}`: **count is the returned page length, not the total number of matching artifacts**. Responses are private and not cached. ```python theme={"dark"} page = client.artifacts.list(limit=10, offset=0) for artifact in page["artifacts"]: print(artifact["title"], artifact["description"], artifact["url"]) ``` MCP `list_artifacts` accepts the same filters and pagination arguments. Each item has the same metadata shape as [Get an artifact](/api-reference/endpoint/getArtifact). # List markers Source: https://docs.strandai.com/api-reference/endpoint/listMarkers GET /markers The entitlement-scoped catalog of markers your account can request, so you can discover valid marker names upfront. Credit-free. # List custom sample fields Source: https://docs.strandai.com/api-reference/endpoint/listSampleFields GET /sample-fields Your organization's custom-field definitions, including the ids a `field` filter on List samples binds to. Credit-free. # List samples Source: https://docs.strandai.com/api-reference/endpoint/listSamples GET /samples List the calling organization's samples, the public cohort, or both. Cursor-paginated newest-first; `all` always emits mine first and de-duplicates owned public samples in favor of the mine representation. Credit-free. The facet parameters are byte-identical to the ones the Strand web app puts in a filtered `/samples` URL, so a browser query string is a valid API query string and vice versa. Facets compose with AND; `status` and `workflow` values compose with OR; repeated `marker` and `field` values compose with AND. Tags is addressed through the predefined Tags field definition. The retired `tag` parameter is rejected with 400 rather than ignored. Unknown values, malformed clauses and over-cap arrays are also rejected. A public release supports title search (`q`) only. Under `scope=all` any other facet suppresses the public block; under `scope=public` it is a 400. # List uploads Source: https://docs.strandai.com/api-reference/endpoint/listUploads GET /uploads Returns non-archived uploads newest-first. Cursor-paginated; pass the prior response's `nextCursor` to fetch the next page. # Update a sample Source: https://docs.strandai.com/api-reference/endpoint/patchSample PATCH /samples/{id} Atomically update any combination of an owned sample's display name, unified field values, and isotropic microns-per-pixel value. Public share ids are not patchable. OAuth callers need both `samples:read` and `samples:write` because the response includes full owned detail and job history. When countable `mpp` is supplied, an idempotent recount is enqueued even if the stored value is unchanged; after an enqueue-failure 500, retry the identical patch to heal the recount. Atomically updates any combination of an owned sample's display name, unified field values, and isotropic microns-per-pixel value. The response is the full owned sample detail, including inference-job history. `fields` is keyed by stable definition key. Each supplied value replaces that field's complete value; `null` clears it. This payload replaces Tags: ```json theme={"dark"} { "fields": { "tags": ["baseline", "trial-42"] } } ``` Tags values are trimmed and lowercased, duplicates collapse, each value must be between 1 and 50 characters without commas or control characters, and a sample may carry at most 50 distinct Tags values. Public is readable through `fields.public` but is not writable through this endpoint; publication uses its protected flow. Use `GET /sample-fields` to discover keys, value types, origin, storage, and writability. The retired top-level `tags` property is rejected with HTTP 400. # Renew an upload session Source: https://docs.strandai.com/api-reference/endpoint/renewUploadSession POST /uploads/{id} Mints a fresh create-only (`ifGenerationMatch=0`) GCS resumable session URL for an existing permanent-bucket (`deidBypassed`) `uploading` sample in the calling organization that has no jobs or bound object generation, preserving the sample ID, object path, declared file size, content hash, and MPP snapshot. Replays the caller-supplied `contentType` recorded on new uploads, or infers the canonical WSI MIME type from `filename` on historical rows where `contentType` was not persisted. Prechecks permanent-bucket storage metadata and reconciles an already-finalized object before returning `409`; quarantine uploads are rejected with a non-retryable `409` (`reason: "quarantine_renewal_unsupported"`) without minting a session. Use this only when the prior `uploadUrl` was lost before completion or expired after GCS's 7-day resumable session TTL; when a known `uploadUrl` returns `308 Resume Incomplete`, resume from its acknowledged byte offset instead. Stream the full declared bytes starting from byte offset `0` to the new `uploadUrl`, then poll `GET /uploads/{id}` until the sample leaves `uploading`. # Request result export Source: https://docs.strandai.com/api-reference/endpoint/requestResultExport POST /jobs/{id}/exports Select native OME-Zarr, OME-Zarr ZIP, or OME-TIFF and optional H&E/segmentation contents. Native OME-Zarr is returned without conversion. ZIP and TIFF generation is asynchronous and cached; repeating the same request reuses active/ready work or retries a failed export. The response manifest records selected contents, expiration, retryability, and artifact URLs. # Restore sample Source: https://docs.strandai.com/api-reference/endpoint/restoreSample POST /samples/{id}/restore Available within the 7-day Trash window until permanent deletion starts. Brings the sample back to the active list and extends its expiration so it isn't immediately re-trashed. A deletion already in progress is irreversible and returns 409. Same permission gate as the expiration endpoints. # Cell segmentation lifecycle Source: https://docs.strandai.com/api-reference/endpoint/sampleSegmentation GET /samples/{id}/segmentation Discover credit-free segmentation state and latest layer artifacts for an owned sample. Use `POST` on the same path to start or retry segmentation. The mutation is state-idempotent, observes a retry cooldown, and rejects public sample handles. Completed layers expose a separate manifest for uint32 masks, cell geometry/morphology, and per-cell marker expression. # Set sample expiration Source: https://docs.strandai.com/api-reference/endpoint/setSampleExpiration PATCH /samples/{id}/expiration Set a sample to expire on a specific date, set it to never expire, or clear any custom expiration and follow the org default. Caller must be the sample's creator, an org owner/admin, or a Strand AI admin. # Set sample expiration (bulk) Source: https://docs.strandai.com/api-reference/endpoint/setSamplesExpirationBulk PATCH /samples/expiration All-or-nothing: if any sample fails the permission gate the whole call is rejected before any writes. Max 500 IDs per call. # Start or retry cell segmentation Source: https://docs.strandai.com/api-reference/endpoint/startSampleSegmentation POST /samples/{id}/segmentation Start or retry idempotent, credit-free segmentation for an owned ready sample. Active/completed work is reused. Failed work can be retried after the cooldown. Public, archived, cross-organization, and non-ready samples cannot be mutated. # Stream job (SSE) Source: https://docs.strandai.com/api-reference/endpoint/streamJob GET /jobs/{id}/stream Server-Sent Events stream emitting JSON snapshots of `{status, progress, resultGcsPath}` on each pg_notify. Keep-alive heartbeats every 15s. Closes on terminal status. # Price or submit a prediction Source: https://docs.strandai.com/api-reference/endpoint/submitPrediction POST /predict Validate and price a prediction with dryRun: true and no side effects, or omit dryRun to reserve credits and submit the run. # REST API overview Source: https://docs.strandai.com/api/overview Reference for Strand AI REST endpoints, bearer authentication, prediction lifecycle, and errors. The Strand AI REST API exposes the platform's job infrastructure. The Python and R SDKs use the same API, which can also be called directly from other languages. The OpenAPI spec is hosted at [`https://app.strandai.com/api/v1/openapi.json`](https://app.strandai.com/api/v1/openapi.json). A Markdown variant for LLM agents is available at [`https://app.strandai.com/docs/api.md`](https://app.strandai.com/docs/api.md). The LLM index is available at [`https://app.strandai.com/llms.txt`](https://app.strandai.com/llms.txt). ## Base URL ```text theme={"dark"} https://app.strandai.com/api/v1 ``` ## Authentication Every endpoint requires a bearer credential: either an organization API key or a Strand OAuth access token. ```http theme={"dark"} Authorization: Bearer sk-strand-XXXXXXXXXXXXXXXXXXXXXXXX ``` Generate API keys at [/settings/api-keys](https://app.strandai.com/settings/api-keys). They are org-scoped and suit headless direct REST clients. OAuth access tokens suit clients acting with a user's delegated organization access, including the hosted MCP connector. **Slides must be de-identified before upload.** See [Security and data handling](/security-data-handling). ## Lifecycle A prediction starts with an event-driven upload, followed by pricing, submission, and result retrieval: **1. Upload the slide** `POST /uploads` with the slide's filename, size, content type, and optional `mpp`. The response contains a **resumable upload URL** (signed GCS). `PUT` the declared slide bytes there directly. GCS automatically starts ingest preprocessing when the object finalizes; there is no client finalize request. Automated de-identification is off by default and runs during ingest only when enabled for your organization. Poll `GET /uploads/{id}` while status is `uploading`. **2. Price or submit** `POST /predict` with `dryRun: true` validates the request and returns the exact credit cost without side effects. Send the same request with `dryRun: false` or omit the field to reserve credits atomically and enqueue inference, returning a `jobId`. **3. Poll or stream the job** `GET /jobs/{id}` for snapshots, or `GET /jobs/{id}/stream` for an SSE stream. When `status` reaches `completed`, download the OME-Zarr results as OME-Zarr via `GET /jobs/{id}/results/files/{path}` or `GET /jobs/{id}/results` (signed GCS URL). Use the single format-driven `POST /jobs/{id}/exports` operation for native OME-Zarr, OME-Zarr ZIP, or OME-TIFF plus optional H\&E and segmentation/cell artifacts; poll the same path with `GET` while a generated export is pending. Completion settles and debits delivered work, then releases any unused reservation. Call `POST /jobs/{id}/cancel` to release the reservation for an eligible in-flight job. ## Error model Errors are returned as JSON in a consistent shape: ```json theme={"dark"} { "error": "insufficient_credits", "message": "Org has 120 credits; this job requires 450.", "required": 450 } ``` | HTTP | Meaning | | - | - | | 400 | Bad request: invalid body, unknown marker, etc. | | 401 | Missing or invalid bearer credential. | | 402 | Insufficient credits. `required` carries the credit cost. | | 404 | Resource not found, or scoped to a different org. | | 409 | Resource not ready. Upload ingest or job processing may still be running. | ## SDKs The platform provides first-party SDKs for this API: > [card] [Python](/sdks/python) > > `pip install strand-sdk` > [card] [R](/sdks/r) > > `install.packages("strandai", ...)` # Sample expiration Source: https://docs.strandai.com/expiration Set when samples expire, restore samples from Trash within 7 days, and override the org default per sample. Every sample on Strand AI has an **expiration**: the date it will move to Trash. Trash holds samples for 7 days, after which they are permanently deleted. You can set a custom expiration on any sample, or turn expiration off entirely. ## Org default expiration Every org has a default expiration window (in days). Owners and admins set it from “Settings → Sample expiration”. When you upload a whole-slide image, the resulting sample inherits this default. The setting is “off” by default, so samples never expire until an owner or admin sets a policy. > [!NOTE] > > Changing the org default updates expiration on samples that are still on > the org default. It leaves samples with a custom expiration unchanged. ## What happens when a sample expires When a sample expires, it moves to Trash. Trash holds samples for 7 days. During that window, you can restore them from the “Trash” tab on the “Samples” page. After 7 days, samples in Trash are permanently deleted, including all marker predictions. Billing history is retained. ## Per-sample expiration You can set a custom expiration on any sample you can edit (sample creator, org owner/admin, or Strand admin). Three modes: * “Expire on”: the sample expires on the date you pick. * “Never expire”: the sample has no expiration date and is unaffected by future org-policy changes. * “Use org default”: clears the custom expiration and follows the current org policy. Custom expirations (both “Expire on” and “Never expire”) survive future org-policy changes. Samples on the org default move with the policy. ## Restoring from Trash Open the “Samples” page and switch to the “Trash” tab. Select “Restore” on any sample within the 7-day window. Restoring brings the sample back to the active list and extends its expiration so it isn't immediately re-trashed. Samples past the 7-day Trash window are gone and cannot be restored. ## Permissions | Action | Allowed for | | - | - | | Change org default expiration | Org owner · org admin (via “Settings → Sample expiration”) | | Set per-sample expiration | Sample creator · org owner/admin · Strand admin | | Bulk set expiration (≤ 500) | Sample creator · org owner/admin · Strand admin | | Restore from Trash | Sample creator · org owner/admin · Strand admin | ## API examples ```python Python theme={"dark"} from strand import Client client = Client() # Read a sample; expiration is a field group on it (read-only). sample = client.samples.get(sample_id) if sample.will_expire: print(f"expires in {sample.expires_in_days} days ({sample.expires_at_source})") # Set a single sample to never expire. client.samples.set_expiration(sample_id, expires_at=None, reason="Active research project") # Expire on a specific date. from datetime import datetime, timezone client.samples.set_expiration(sample_id, expires_at=datetime(2026, 12, 31, tzinfo=timezone.utc)) # Bulk: set never-expire. client.samples.set_expiration_bulk([id1, id2, id3], expires_at=None) # Restore from Trash. client.samples.restore(sample_id) ``` ```bash curl theme={"dark"} # Read a sample (expiration is one field group on it — read-only). curl "https://app.strandai.com/api/v1/samples/$SAMPLE_ID" \ -H "Authorization: Bearer $STRAND_API_KEY" # -> {"id": "...", "filename": "...", "status": "ready", ..., # "expiresAt": "...", "expiresAtSource": "custom", # "expiresInDays": 42, "willExpire": true, "trashedAt": null} # Set a sample to never expire. curl -X PATCH "https://app.strandai.com/api/v1/samples/$SAMPLE_ID/expiration" \ -H "Authorization: Bearer $STRAND_API_KEY" \ -H "Content-Type: application/json" \ -d '{"expiresAt": null, "reason": "Active research project"}' # Bulk: set 50 samples to expire on a fixed date. curl -X PATCH "https://app.strandai.com/api/v1/samples/expiration" \ -H "Authorization: Bearer $STRAND_API_KEY" \ -H "Content-Type: application/json" \ -d '{"sampleIds": ["...", "..."], "expiresAt": "2026-12-31T00:00:00Z"}' # Restore a sample from Trash within the 7-day window. curl -X POST "https://app.strandai.com/api/v1/samples/$SAMPLE_ID/restore" \ -H "Authorization: Bearer $STRAND_API_KEY" ``` ```r R theme={"dark"} library(strandai) client <- strand_client() # Read a sample; expiration is a field group on it (read-only). s <- strand_samples_get(client, sample_id) if (s$will_expire) message("expires in ", s$expires_in_days, " days") # Set a single sample to never expire. strand_set_expiration(client, sample_id, expires_at = NULL, reason = "Active research project") # Expire on a specific date. strand_set_expiration(client, sample_id, expires_at = as.POSIXct("2026-12-31", tz = "UTC")) # Bulk: set never-expire. strand_set_expiration_bulk(client, c(id1, id2, id3), expires_at = NULL) # Restore from Trash. strand_restore(client, sample_id) ``` ## Email notifications Use the “Expiration reminders” toggle under [Account → Notifications](https://app.strandai.com/settings/notifications) to control both expiration-related emails: * Weekly digest: sent Mondays at 13:00 UTC to org owners and admins, listing samples that expire in the next 7 days. * Policy-change notice: sent to every org member when an owner or admin shortens the org expiration policy and creates near-term expirations (\< 30 days), so members can set a custom expiration on samples they need to keep. # Spatial proteomics from H&E Source: https://docs.strandai.com/introduction Lattice predicts spatially resolved protein-marker maps from routine H&E, delivered as virtual mIF channels. **Spatial proteomics from H\&E.** Lattice predicts spatially resolved protein-marker maps from routine H\&E, delivered as virtual mIF channels. Each channel is a per-pixel model output for one protein marker. Experimental multiplex measurements remain the training and comparison reference. Lattice is trained on paired H\&E and multiplex immunofluorescence data. The platform accepts a slide, runs inference on our infrastructure, and returns predicted marker channels you can use with the rest of your spatial pipeline. ## Why Strand AI > [card] H\&E in, markers out > > You don't need antibody panels, IF capacity, or a second slide. Submit > the H\&E and request the markers you need. > [card] Spatial outputs > > Predictions are returned as multi-channel OME-Zarr you can open as > `AnnData` (Python) or `SpatialExperiment` (R) and work with using your > existing multiplex tooling. > [card] REST + SDKs > > Python and R clients, a documented REST API, and a credits ledger you > can estimate against before you submit. ## Who this is for Researchers and biotech teams who have H\&E at scale and want predicted spatial proteomics, typically for: * biomarker hypothesis generation in retrospective cohorts, * enriching slides where IF or mIF was not collected, * batch-level QC of multiplex panels against an orthogonal predictor. Lattice is trained primarily on oncology data. Predictions outside an oncology context are exploratory; if you have a non-oncology use case, [email us](mailto:support@strandai.com). ## What's next > [card] [Platform quickstart](/quickstart) > > Sign in, upload an H\&E slide, run Lattice, and inspect the marker layers. > [card] [SDKs](/sdks/quickstart) > > Use Python, R, or the `strand` command line for scripted workflows. > [card] [MCP server](/mcp/overview) > > Connect Claude or another MCP client to a Strand organization. > [card] [API reference](/api/overview) > > Build directly against the canonical HTTP surface. > [!NOTE] > > Strand AI is in beta. You can sign up at > [app.strandai.com](https://app.strandai.com) and run the public marker panel on > your own slides. Email [support@strandai.com](mailto:support@strandai.com) to > discuss an expanded panel or a larger cohort. > [!WARNING] > > **For research use only.** Strand AI predictions are model outputs intended > for research and hypothesis generation. They are not validated for, and must > not be used in, clinical diagnosis, treatment selection, or patient care > decisions. # Supported markers Source: https://docs.strandai.com/markers/index The protein markers Lattice predicts from H&E on the public panel, with genes and curated biology notes. Strand AI predicts spatial protein marker channels directly from an H\&E whole-slide image using **Lattice**, our spatial-proteomics imputation model. Each marker below has a model checkpoint trained against paired multiplex ground truth, predominantly from tumor biology. Predictions outside an oncology context are exploratory; see the [intro page](/introduction) for what this means for non-cancer tissue. ## Public panel The public panel for **new general-access predictions** is the 8-channel set below: a nuclear counterstain plus seven biological markers spanning the T cell, B cell, macrophage, pan-leukocyte, epithelial, and proliferation compartments. Existing delivered predictions remain readable under their original marker names. Published cohorts have separate release panels; this request catalog does not claim that CD4 is already available on every public sample or change the historical TCGA-COAD Hugging Face release. | Marker | Gene | Category | Predicts | | - | - | - | - | | DAPI | DAPI | Nuclear | Nuclear counterstain (sanity-check channel). | | PanCK | KRT | Epithelial & tumor | Pan-cytokeratin; epithelial / tumor compartment. | | CD3e | CD3E | Immune lineage | Pan-T cell marker. | | CD4 | CD4 | Immune lineage | Helper T cells. | | CD20 | MS4A1 | Immune lineage | Mature B cells. | | CD68 | CD68 | Immune lineage | Pan-macrophage. | | Ki67 | MKI67 | Nuclear & proliferation | Proliferation marker. | | CD45 | PTPRC | Immune lineage | Pan-leukocyte marker; immune-cell compartment. | Additional markers are available to contracted partners under agreement. The expanded panel changes as checkpoints are validated, so we do not publish a fixed count: [`GET /markers`](/api-reference/endpoint/listMarkers) is the authoritative list for your account. Contact [support@strandai.com](mailto:support@strandai.com) to discuss an expanded panel for your cohort. ## Discovering markers programmatically The [`GET /markers`](/api-reference/endpoint/listMarkers) endpoint returns the exact set your account may request, so agents and scripts can discover valid names upfront instead of guessing. The list matches what a prediction will accept: a self-signup account sees the public panel; a contracted account sees its expanded panel. ```python Python theme={"dark"} client.markers.list().names ``` ```bash cURL theme={"dark"} curl https://app.strandai.com/api/v1/markers \ -H "Authorization: Bearer $STRAND_API_KEY" ``` ```r R theme={"dark"} strand_markers_list(client)$markers ``` ```bash CLI theme={"dark"} strand markers ``` The MCP server exposes the same list as the `list_markers` tool. ## Reading the predictions Predictions are returned as a multi-channel OME-Zarr aligned to the slide's pixel grid. Each requested marker becomes a separate channel; the SDK helpers convert it to `AnnData` (Python) or `SpatialExperiment` (R) so you can work with it using your existing multiplex tooling. See the [Quickstart](/quickstart) for an end-to-end example and the [Python](/sdks/python) / [R](/sdks/r) SDK reference for the conversion helpers. ## Accuracy caveats * Predictions are **model outputs**, not ground truth. Use them as a hypothesis-generation surface, particularly on cohorts that look out-of-distribution to the training data. * Per-marker confidence varies. Lineage and structural markers (e.g. PanCK, CD8, CD45) generally calibrate better than functional / activation markers in the expanded catalog (e.g. PDL1). * We do not yet publish per-tissue or per-organ accuracy numbers. Those will be added as benchmarks become available. Reach out at [support@strandai.com](mailto:support@strandai.com) if you want pre-publication benchmarks on a specific tissue or marker. # Strand AI in ChatGPT Source: https://docs.strandai.com/mcp/chatgpt Connect ChatGPT to Strand AI to browse your slides, check Lattice estimates, and view predicted marker maps right in the chat. Use Strand AI from ChatGPT to find your slides, check what a Lattice run would cost, follow your runs, and open results in an interactive viewer in the chat. ## Connect ChatGPT Add Strand AI as an app in ChatGPT. Custom apps depend on your ChatGPT plan and workspace settings, so your workspace administrator may need to add it. Use this address: ```text theme={"dark"} https://mcp.strandai.com/mcp ``` ChatGPT then asks you to sign in to Strand AI. Sign in, approve the access request, and pick the Strand AI organization ChatGPT should work in. To use it in a chat, type **@Strand AI** before your request. ## Try these prompts > @Strand AI Show my samples, then open the newest one in the viewer. > @Strand AI How much would CD3e, CD20, and Ki67 cost on sample "Biopsy 12"? > @Strand AI Has my last run finished? Give me the results as OME-Zarr. > @Strand AI Which markers can I predict? ## What works in ChatGPT * **Browsing samples, sample details, and run status.** * **The in-chat viewer.** Ask ChatGPT to open a sample, then pan, zoom, and switch markers. Use **Open in Strand AI platform** for the full workspace. The images stay between you and Strand AI; they're never sent to the AI model. * **Cost estimates** for any markers, free. * **Downloading results.** ChatGPT may ask you to allow it to fetch the result files. That's expected. **Uploading slides:** ChatGPT can't upload whole-slide images. Upload in your browser at [app.strandai.com/samples/upload](https://app.strandai.com/samples/upload), then ask ChatGPT to work with the slide. **Starting runs:** start runs on the Strand AI platform for now. ChatGPT can show you the estimate first. ## Troubleshooting * **Something is missing, or ChatGPT seems out of date.** Refresh the tool list: **Settings → Plugins → Strand AI → Refresh tools**. You don't need to reconnect. * **ChatGPT can't find your sample.** Each connection sees one Strand AI organization. Check you connected the right one in **Settings → Plugins → Strand AI**. * **ChatGPT says a sample ID is required.** Ask it to list your samples first, then open the one you want. Still stuck? Email [support@strandai.com](mailto:support@strandai.com) with the sample or run ID. Don't include slide files, passwords, or API keys. ## Privacy and data Research use only. Not for use in clinical diagnosis, treatment, or patient-care decisions. Upload only de-identified slides you're allowed to use. Your Strand AI agreement governs stored slides and results, and ChatGPT's own privacy settings cover your chat messages. Review or disconnect ChatGPT anytime in [Settings → Connected Apps](https://app.strandai.com/settings/connected-apps). See [Security and data handling](/security-data-handling) and the [Privacy Policy](https://strandai.com/privacy). # Strand AI in Claude Source: https://docs.strandai.com/mcp/claude Connect Claude to Strand AI to get spatial proteomics from H&E with Lattice: browse slides, run predictions, and view results right in the chat. Use Strand AI from Claude to get spatial proteomics from H\&E without leaving the conversation. Lattice predicts spatially resolved protein-marker maps from routine H\&E, delivered as virtual mIF channels. Ask Claude to find a slide, estimate and run Lattice, and open the results in an interactive viewer. ## Connect Claude (web and desktop) **1. Add Strand AI** In Claude, open the [**Strand AI connector**](https://claude.ai/directory/strand-ai) (or **Customize → Connectors**), and add it. **2. Sign in** Claude opens a Strand AI sign-in page. Sign in and approve the access request. **3. Pick an organization** Choose the Strand AI organization Claude should work in. Claude sees that organization's samples, and runs use its credits. That's it. Try: "Show my Strand AI samples." If your Claude organization doesn't allow directory connectors, an administrator can add a custom connector with the address `https://mcp.strandai.com/mcp`. ### Uploading slides from Claude Claude can upload a slide you attach, after one setting change. Ask your Claude organization's administrator to add `storage.googleapis.com` under **Settings → Capabilities → Allow network egress**, then start a new chat. Without it, uploads fail with a `host_not_allowed` message, and everything else still works. For large whole-slide images, it's faster to upload in your browser at [app.strandai.com/samples/upload](https://app.strandai.com/samples/upload) and then ask Claude to work with the slide. ## Claude Code Add Strand AI with one command: ```bash theme={"dark"} claude mcp add --transport http strand-ai https://mcp.strandai.com/mcp ``` Then run `/mcp`, sign in, and pick your organization. Claude Code can upload slides directly. The in-chat viewer isn't available in Claude Code. ## Try these prompts > Show my samples, then open the newest one in the viewer. > Upload this de-identified slide, estimate CD3e, CD4, and Ki67, and wait for > my OK before running. > Has my last run finished? If so, give me a download link. > Set this sample's scale to 0.5 microns per pixel and tag it "cohort-a". > Start cell segmentation on this slide. ## The in-chat viewer Ask Claude to open a sample, and the Lattice viewer appears in the conversation. Pan, zoom, and switch markers as you would on the platform. Use **Open in Strand AI platform** for the full workspace. The images stay between you and Strand AI; they're never sent to the AI model. ## Costs and approvals Browsing, viewing, estimates, and cell segmentation are free. Running Lattice uses your organization's credits. Strand AI tells Claude to show you the estimate and get your OK before starting a run. Keep Claude set to ask before Strand AI tools that make changes. ## Using an API key Some assistants can't sign in for you. They can connect with a Strand AI API key instead, sent as `Authorization: Bearer `. Create one in [Settings → API keys](https://app.strandai.com/settings/api-keys). > [!WARNING] > > **An API key can spend your organization's credits.** It works in your > organization with full access, like signing in as you. Keep it in a password > manager or secret store, never in code, chats, or shared files. To replace a > key, create a new one, update your assistant, then delete the old one. A > deleted or expired key stops working right away. ## Troubleshooting * **Something is missing, or Claude seems out of date.** Refresh the tool list: **Customize → Connectors → Strand AI → ⋯ → Refresh tools list**. You don't need to reconnect. * **Upload fails with `host_not_allowed`.** Add `storage.googleapis.com` to your Claude organization's allowed network egress, then start a new chat. Or upload in your browser instead. * **Claude can't sign in, or says you don't have access.** Disconnect Strand AI and connect again, choosing an organization you belong to. * **A slide says it isn't ready.** New uploads take about a minute to process. Ask Claude again shortly. * **Not enough credits.** Pick a different organization, or ask your Strand AI administrator to add credits. * **A download link expired.** Ask Claude for the results again. Links are short-lived on purpose. * **An OME-TIFF or ZIP download is still preparing.** These are created on request and large slides take a few minutes. Ask again shortly, or ask for OME-Zarr, which is ready immediately. Still stuck? Email [support@strandai.com](mailto:support@strandai.com) with the sample or run ID. Don't include slide files, passwords, or API keys. ## Privacy and data > [!WARNING] > > Research use only. Not for use in clinical diagnosis, treatment, or > patient-care decisions. Slides must be de-identified before upload. Only upload slides you're allowed to use. Automated de-identification is off by default and runs only when enabled for your organization. Your Strand AI agreement and organization settings govern stored slides and results. Review or disconnect Claude anytime in [Settings → Connected Apps](https://app.strandai.com/settings/connected-apps). See [Security and data handling](/security-data-handling) and the [Privacy Policy](https://strandai.com/privacy). Report security issues to [security@strandai.com](mailto:security@strandai.com). # Use Strand AI from your AI assistant Source: https://docs.strandai.com/mcp/overview Connect Claude, ChatGPT, or another AI assistant to Strand AI to browse your slides, check Lattice estimates, and view predicted spatial proteomics from H&E in the chat. Strand AI works inside AI assistants such as Claude and ChatGPT. Once connected, you can ask in plain language to find a slide, check what a run would cost, and look at the results, without leaving the chat. In Claude you can also start runs. Lattice predicts spatially resolved protein-marker maps from routine H\&E, delivered as virtual mIF channels. The assistant works with the same samples, credits, and results you see at [app.strandai.com](https://app.strandai.com). ## What you can do * **Find samples.** "Show my samples from last week" or "Find the TCGA colon slides in the public cohort." * **Organize sample metadata.** Ask to list sample fields or create a field such as "Study cohort" with a description and select options. Creating a definition is free. Assigning its values is a separate sample update. * **View a slide in the chat.** Ask the assistant to open a sample, and an interactive viewer appears in the conversation. Pan, zoom, and switch markers just like on the platform. * **Check the cost before you run.** "How much would CD3e, CD20, and Ki67 cost on this slide?" The estimate is free. * **Run Lattice (Claude).** Strand AI tells your assistant to show you the credit estimate and get your OK before it spends anything. Keep your assistant's "ask before using tools that make changes" setting on. * **Check progress and download results.** Ask whether a run has finished, then get a download link for the predicted markers. * **Segment cells.** Start cell segmentation on a slide (free) to get per-cell measurements with your results. ## Pick your assistant | Assistant | What works | Setup guide | | - | - | - | | Claude (web and desktop) | Everything, including the in-chat viewer and slide upload | [Claude](/mcp/claude) | | Claude Code | Everything except the in-chat viewer | [Claude](/mcp/claude#claude-code) | | ChatGPT | Browsing, the in-chat viewer, estimates, and results. Upload slides and start runs on the platform. | [ChatGPT](/mcp/chatgpt) | | Other assistants | Connect with the server address below | [Other assistants](#other-assistants) | ## Before you start * **You need a Strand AI account** that belongs to an organization. Runs use that organization's credits. [Sign up free](https://app.strandai.com). * **Slides must be de-identified before upload.** Never upload slides or file names that contain patient information. Automated de-identification is off by default and runs only when enabled for your organization. See [Security and data handling](/security-data-handling). * **Large slides upload best in your browser.** For multi-GB whole-slide images, upload at [app.strandai.com/samples/upload](https://app.strandai.com/samples/upload), then ask your assistant to work with the slide. * **Research use only.** Not for use in clinical diagnosis, treatment, or patient-care decisions. Assistants are instructed to decline clinical requests. ## Try these prompts > Show my samples, then open the newest one in the viewer. > Estimate CD3e, CD4, CD20, and Ki67 for sample "Biopsy 12". Don't run it yet. > That estimate looks fine. Run it. (Claude) > Has my last run finished? If so, give me the results as OME-TIFF. > Which markers can I predict? ## Good to know * **The viewer opens one sample at a time.** If you have several samples with similar names, the assistant may ask which one you mean. * **Your slide images stay private.** The viewer shows your results to you, but the images themselves are never sent to the AI model. * **Connections are per organization.** When you connect, you pick one Strand AI organization, and the assistant can only see that organization's samples and the public cohort. To switch organizations, reconnect. * **You stay in control.** See and revoke connected assistants anytime in [Settings → Connected Apps](https://app.strandai.com/settings/connected-apps). * **After an update, refresh the tool list.** If something described here is missing, refresh Strand AI's tools in your assistant. In Claude: **Customize → Connectors → Strand AI → ⋯ → Refresh tools list**. In ChatGPT: **Settings → Plugins → Strand AI → Refresh tools**. ## Other assistants Any assistant that supports remote [MCP](https://modelcontextprotocol.io) connectors can use Strand AI. Add a custom connector with this address, then sign in with your Strand AI account when prompted: ```text theme={"dark"} https://mcp.strandai.com/mcp ``` Assistants that can't sign in for you can use a Strand AI API key instead. See [API keys](/mcp/claude#using-an-api-key). For scripted or bulk work, the [Python SDK](/sdks/python) and [REST API](/api/overview) are usually a better fit than an assistant. ## Help Email [support@strandai.com](mailto:support@strandai.com) with the sample or run ID. Don't include slide files, passwords, or API keys. # Set slide pixel size Source: https://docs.strandai.com/microns-per-pixel Set user-reported microns per pixel when a slide's physical scale metadata is missing or incorrect. Microns per pixel (MPP) describes the physical size represented by one base-level image pixel. Strand uses this scale when normalizing slide pixels for inference. An incorrect value can change the biological scale of the image regions sent to the model. Set an override on the sample after uploading its whole-slide image and before submitting a prediction when the embedded scale is missing or known to be wrong. The user-reported value takes precedence over embedded slide metadata for subsequent jobs on that sample. ## Isotropic pixels Use one value when the horizontal and vertical scales are the same: ```python Python theme={"dark"} client.samples.patch(upload.id, mpp=0.26) ``` ```bash REST theme={"dark"} curl -X PATCH "https://app.strandai.com/api/v1/samples/$SAMPLE_ID" \ -H "Authorization: Bearer $STRAND_API_KEY" \ -H "Content-Type: application/json" \ -d '{"mpp": 0.26}' ``` ```r R theme={"dark"} strand_patch_sample(client, upload$id, mpp = 0.26) ``` The value must be greater than 0 and at most 100 microns per pixel. The response echoes the persisted `mpp` value. Each Strand sample uses one isotropic scale, so a single value governs both axes. The REST endpoint also accepts an `{ "x", "y" }` object when both axes are equal; an object with differing axes is rejected. # Mirax ingest Source: https://docs.strandai.com/mirax-ingest # MIRAX ingest ## Upload contract A MIRAX slide is a `.mrxs` header plus its same-stem companion directory: ```text theme={"dark"} slide.mrxs slide/ Slidedat.ini Index.dat Data0000.dat ... ``` Upload **one slide per ZIP**, either `slide.mrxs.zip` or `slide.zip`. A common enclosing directory is accepted. Archives containing multiple slides, unrelated files outside the companion directory, unsafe paths, duplicate/case-colliding paths, links, encrypted entries, or incomplete companions are rejected. Finder resource forks and `.DS_Store` entries are path/bounds-validated and discarded without extraction. MIRAX INI index/data references must resolve to the extracted companion files, never arbitrary local paths. The Python SDK's `client.uploads.upload_file(Path("slide.mrxs"))` creates a deterministic, streaming ZIP64 temporary archive automatically. Missing companions and symlinks produce specific errors; the temporary archive is cleaned up after success or failure. The browser accepts prepared ZIPs and explains why a bare header is insufficient; it does not zip dropped folders. ## Canonical source Every MIRAX archive requires normalization through quarantine, including organizations with automatic de-identification disabled. Only the validated output becomes the sample's permanent source. The Python normalizer: * Bounds archive entries (10,000), decompressed bytes, decoded pixels (100 billion across levels), and total scratch use. * Reads each native OpenSlide tissue level in bounded 512×512 tiles. * Writes a lossless DEFLATE-compressed, RGB, tiled pyramidal BigTIFF with the exact native level dimensions. * Copies no original metadata, associated images, label/macro pixels, INI bytes, or ICC profile. * Generates only a minimal Aperio `MPP` header and standard per-level X/Y resolution tags in centimeters. OpenSlide exposes native `openslide.mpp-x` and `openslide.mpp-y`; existing dimensions, preprocessing, inference and segmentation readers need no MIRAX-specific changes. * Requires finite, positive, isotropic native MPP (up to 100 µm/px). Anisotropic sources fail closed because the existing product and Aperio MPP representation are isotropic. * Reopens the output independently with OpenSlide, checks dimensions/MPP/absence of associated images, exercises reads at three positions per level, and compares independently decoded TIFF tile patches exactly against source tissue pixels. TIFF readers infer downsample factors from the integer pyramid dimensions, so lower-level factors can differ slightly from MIRAX's exact powers of two at rounded edges. Dimensions and level-0 calibration are preserved. Pixel-equality validation uses decoded TIFF tile coordinates, not interpolated `read_region` locations. The permanent object is a single `.tiff` with `image/tiff` content type. Sample `gcsPath`, filename, byte size, permanent generation and SHA-256 identify this canonical object, not the archive. The original archive hash is retained separately for repeat SDK upload deduplication. Quarantine deletion remains after successful validation, permanent upload and DB repoint. This removes format-defined metadata/associated-image surfaces; it does not inspect or remove identifiers burned into tissue pixels or filenames. ## Scratch and deployment The deid Cloud Run Job requires the accompanying Terraform configuration: **8 vCPU, 32 GiB RAM, 28 GiB RAM-backed `/tmp`**. No separate GPU or inference changes are needed. This PR does not deploy or apply infrastructure. The downloaded archive is removed after successful extraction, before transcoding. Extracted companions are removed after output validation, before upload. Quarantine retains the immutable original generation if conversion fails. The normalizer rejects extraction or output growth beyond its 28 GiB scratch budget rather than relying on the container OOM killer. The remaining 4 GiB is reserved for Node, native decoders and bounded tile buffers. Sources beyond these limits need a larger disk-backed normalization runner; increasing ZIP limits alone is unsafe. ## Local verification Synthetic security, metadata and lossless-transcode tests: ```sh theme={"dark"} python -m unittest discover -s platform/src/jobs/__tests__ -p 'test_mirax*.py' -v python -m unittest discover -s platform/src/jobs/__tests__ -p test_wsi_deid.py -v ``` Opt-in real archive → deid → unchanged production lazy-tiler integration: ```sh theme={"dark"} MIRAX_REAL_SLIDE=/authorized/scratch/slide.mrxs \ python -m unittest discover -s platform/src/jobs/__tests__ -p test_mirax_real.py -v ``` This test uses the source's sibling directory, writes temporary data beside it, requires no GCS/database/GPU, supplies **no MPP override**, and checks that preprocessing decodes 224×224 model patches at the correct native scale. Do not commit source slides or record them in UI proof. ### Real-fixture results All four authorized Human Brain Cancer MIRAX fixtures were downloaded with complete companions and opened with OpenSlide. Every fixture has dimensions **125112×297800**, **nine native levels**, and **0.1725 µm/px on both axes**. All four full-resolution lossless BigTIFF conversions passed independent dimension, calibration, tissue-pixel and associated-image checks. | Blinded fixture | Canonical bytes | Retained model-grid positions | Canonical SHA-256 prefix | | - | -: | -: | - | | A | 7,205,996,135 | 21,622 | `5b2540e9f429` | | B | 11,947,848,176 | 35,970 | `325f7d1988cf` | | C | 8,337,286,978 | 25,433 | `61fb60b4e413` | | D | 18,598,496,881 | 62,267 | `66e7f472a74f` | For each canonical file, the unchanged `read-wsi-dimensions.py` returned the exact native dimensions/MPP. The unchanged `preprocess.tile_wsi_lazy` selected level 1 and decoded a `[4, 3, 224, 224]` patch batch without an MPP override. These CPU-only local checks used `bg_mode="rgb_legacy"`, not the model-backed tissue mask. Fixture A also passed the complete ZIP → sidecar de-identification → lazy-preprocessing integration test; its independently repeated conversion produced the same canonical SHA-256. No real slide pixels, source metadata, or specimen names are committed or included in UI evidence. GCS promotion/dispatch is covered by PGlite/orchestrator integration tests, not a deployed cloud run. # Pricing & credits Source: https://docs.strandai.com/pricing How Strand AI bills predictions in credits per retained tissue model-grid position and marker, how to get the exact price before submission, and when credits come back. Strand AI bills predictions in **credits**. You can get the exact price of a run before you submit it. ## How credits work The model evaluates overlapping positions on an MPP-normalized grid. One credit pays for one retained tissue position on one marker: > [!NOTE] > > **1 credit = 1 retained tissue model-grid position × 1 marker.** The source-pixel footprint of each position depends on the sample's calibrated microns-per-pixel (MPP). It is not a fixed 224×224 region of the uploaded image. Background positions are excluded, so a slide with one small biopsy costs far less than a slide of the same pixel dimensions covered in tissue. Raw byte size, raw pixel dimensions, and formulas such as `ceil(width / 224) × ceil(height / 224)` do not determine the billable count. After sample preparation, `patchCount` is the authoritative retained-position count for the sample's persisted MPP and priced model configuration. A dry run returns that exact count and the credit cost for the request you are about to submit. If the tissue model fails, preparation remains retryable and no price is published. Counting and inference never substitute a different RGB heuristic. There is no separate inference fee, surcharge, or per-job overhead. Only marker predictions cost credits at all. Uploads, ingest, sample and marker reads, dry runs, result downloads, and cell segmentation are free. ## Getting the exact price before you submit `POST /predict` with `dryRun: true` validates and prices the exact request without charging anything or creating a job. Its `patchCount` is the exact number of retained MPP-normalized model-grid positions the run will cover, and `estimatedCredits` is what you will be charged: ```python Python theme={"dark"} est = client.predict.submit( upload.id, markers=["CD8", "PanCK", "Ki67"], dry_run=True, ) print(est.patch_count, est.marker_count, est.estimated_credits) print("balance:", est.org_balance, "pending:", est.org_pending) ``` ```r R theme={"dark"} est <- strand_predict( client, upload$id, c("CD8", "PanCK", "Ki67"), dry_run = TRUE ) message("patches: ", est$patch_count, " markers: ", est$marker_count, " credits: ", est$estimated_credits) ``` ```bash cURL theme={"dark"} curl -X POST https://app.strandai.com/api/v1/predict \ -H "Authorization: Bearer $STRAND_API_KEY" \ -H "Content-Type: application/json" \ -d '{"uploadId":"…","markers":["CD8","PanCK","Ki67"],"dryRun":true}' ``` ## When you are charged, and when you get credits back Correcting a sample's MPP before submission rebuilds its prepared geometry and can change `patchCount`, so price again after an MPP correction. Submitting a run deducts its full estimated cost from your organization's balance in one step, before inference starts. The job atomically snapshots the priced MPP, retained position count, model configuration, and prepared artifact identity alongside that reservation. Inference uses this immutable snapshot even if the sample's MPP is corrected later. The API reports the locked amount as `reservedCredits`, which means: * **The price of a submitted run cannot change.** If we change our per-patch price later, runs already submitted keep the price you were charged. * **Failed and cancelled runs are credited back automatically.** If a job ends as `failed` or you cancel it, the full amount returns to your balance. Marker channels already written stay on the sample. * **You pay only for delivered markers.** If a run delivers some of its markers and not others, you are charged for the delivered ones and credited back for the rest. * **A run you cannot afford is rejected, not partially charged.** The request returns 402 with a `required` field showing the full cost. ## Buying credits Credits are sold in prepaid tiers. There is no self-serve top-up yet, so email [support@strandai.com](mailto:support@strandai.com) with the volume you need and we'll add them to your organization. ## See also * [API reference](/api-reference/endpoint/submitPrediction): `POST /predict` dry-run pricing, submission, and 402 / 429 behavior. * [Supported markers](/markers): which markers count toward a job's credit cost. # Platform quickstart Source: https://docs.strandai.com/quickstart Sign in to the Strand AI web platform, upload an authorized de-identified H&E slide, run Lattice, inspect marker layers, and download results. Use the web platform for the standard Strand AI workflow. No API key or local software is required. > [!WARNING] > > **For research use only.** Strand AI predictions are model outputs intended > for research and hypothesis generation. They are not validated for, and must > not be used in, clinical diagnosis, treatment selection, or patient care > decisions. ## 1. Sign in and choose an organization Open [app.strandai.com](https://app.strandai.com). Follow your Strand invitation. On the “Get started free” page, choose “Continue with Google” or “Continue with email”. Your active organization owns the samples, credits, and runs you create. If you belong to more than one organization, open the organization menu and choose “Switch org” before uploading. ## 2. Upload an H\&E slide Select “Upload” in the platform sidebar to open “Upload Sample”. Drag a TIFF, TIF, SVS, NDPI, SCN, or MRXS file onto “Drag and drop your slides here”, or click the drop zone to browse files. Upload only data that your organization is authorized to process. **Slides must be de-identified before upload.** Do not upload protected health information. See [Security and data handling](/security-data-handling). “Run cell segmentation” is selected by default. Segmentation finds individual cells in the H\&E and costs no credits. It is not billed like a marker run. Keep it selected for per-cell readouts. Clear it if you only need marker channels. Segmentation can be started or retried later from an SDK or MCP client. Segmentation produces viewer overlays and three artifacts on the “Export” tab: a label mask, a per-cell morphology table, and a manifest. Per-marker cell expression (mean and median per cell) is available through the [REST API](/api/overview), the SDKs, and MCP `download_results`. The `AnnData` and `SpatialExperiment` objects built from a prediction are pixel-grid marker matrices, not per-cell tables. Multiple files queue automatically, with up to two uploads active at once. ## 3. Wait for ingest and confirm slide scale A single completed upload opens its sample automatically. For a batch, use the “Upload complete. Open sample” link on each completed row. Ingest preprocessing and the H\&E pyramid begin automatically after the final byte is committed. Automated de-identification is off by default and runs during ingest only when enabled for your organization. The sample page shows “Slide scale confirmation required” only when the embedded physical scale is absent or conflicts with the objective metadata. Choose “Use slide tag”, accept the suggested “Use … µm/px” value, or choose “Enter manually” after checking the scanner metadata. A valid scale appears inline and is ready to use. Scale is a property of the sample, not of a run. You can correct it at any point before submitting, and a corrected value applies to every later run on that sample. See [Set slide pixel size](/microns-per-pixel) for the API, SDK, and command-line equivalents. ## 4. Choose markers and review cost From the sample page, choose “Submit a run” or “New run” to open “Run Lattice”. 1. Review the “Sample” and “Slide Scale” cards. 2. Choose channels under “Select Markers”. The picker offers only markers available to the active organization and identifies completed coverage. 3. Review “Eligibility and estimate”. It shows the jobs to create, exact credits, resolved samples, already-covered samples, and your organization balance. 4. Select “Run Lattice (… markers)” to charge the displayed credits and submit the run. The button remains unavailable when no marker is selected, scale confirmation is required, or the organization does not have enough credits. ## 5. Monitor the run Submission returns to the sample's “Markers” tab. The page reports queued and running state, completed marker count, partial delivery, or failure. You can leave the page. The run continues server-side, and the platform posts a notification when it finishes. ![A completed Lattice run with eight delivered marker channels and a successful analysis status.](https://mintcdn.com/strandai/WlYormin9DYd-a9S/images/quickstart-run-detail.webp?fit=max\&auto=format\&n=WlYormin9DYd-a9S\&q=85\&s=8acd879a1ee6ed510511b1eb9f75568e) ## 6. Inspect and download results Open “Viewer” to compare the original H\&E with delivered marker layers. Use the viewer controls to toggle markers, change colors and intensity, switch views, and inspect cell-segmentation overlays when available. See [Viewer keyboard shortcuts](/viewer/keyboard-shortcuts) for navigation controls. ![The Strand viewer showing H\&E alongside a CD8 prediction layer on a de-identified TCGA demo slide.](https://mintcdn.com/strandai/WlYormin9DYd-a9S/images/quickstart-viewer-cd8.webp?fit=max\&auto=format\&n=WlYormin9DYd-a9S\&q=85\&s=8a1c08d89d549b3994f7fed480fcdbbc) Open “Export” for downloads: * use the marker download controls for individual OME-Zarr marker pyramids; * choose “Generate OME-TIFF”, then “Download”, for a run-scoped pyramidal OME-TIFF after a prediction completes; and * download segmentation layers when the sample includes them. OME-Zarr is the stored format, so those downloads start immediately. An OME-TIFF is rendered on request: “Generate OME-TIFF” starts the render and “Download” stays unavailable until it finishes, which takes minutes on a large slide. The rendered file is cached, so a second request for the same run returns the existing file. The archive contains the run's predicted marker channels as a pyramidal image and includes the source H\&E. Segmentation layers download separately. ![The Export tab with eight individual marker pyramids, including CD3e.](https://mintcdn.com/strandai/WlYormin9DYd-a9S/images/quickstart-export.webp?fit=max\&auto=format\&n=WlYormin9DYd-a9S\&q=85\&s=2c81d5d332199f84a52698fe53f010a1) ## Programmatic workflows > [card] [SDK quickstart](/sdks/quickstart) > > Run the same workflow from Python or R with an API key. > [card] [Command line](/sdks/cli) > > Upload, estimate, submit, wait, cancel, and export from `strand`. > [card] [Claude connector](/mcp/claude) > > Authorize Claude against one Strand organization. > [card] [REST API](/api/overview) > > Integrate directly from another language or service. # Command line (strand) Source: https://docs.strandai.com/sdks/cli Run H&E slides through Lattice from your terminal. Upload, estimate, submit, wait, cancel, inspect, and export through the Python SDK. The Python SDK includes the `strand` command for running the upload-to-results workflow without a script. It uses the same `strand.Client` as the library and MCP tools. Each command maps one-to-one to an SDK method and uses the same argument names. ## Install ```bash theme={"dark"} pip install strand-sdk # with the extras needed to open results as AnnData: pip install "strand-sdk[anndata]" ``` Installing the package puts `strand` on your `PATH`. ```bash theme={"dark"} strand --help strand --version ``` ## Configuration The CLI reads the same environment variables as `strand.Client()`. | Variable | Purpose | Default | | - | - | - | | `STRAND_API_KEY` | API key (`sk-strand-…`). Required. | none | | `STRAND_BASE_URL` | API base URL. | `https://app.strandai.com` | ```bash theme={"dark"} export STRAND_API_KEY="sk-strand-…" ``` Generate a key at [app.strandai.com](https://app.strandai.com/settings/api-keys). Commands print machine-readable JSON to stdout, so they compose with [`jq`](https://jqlang.github.io/jq/) and shell pipelines. On failure the CLI writes a one-line message to stderr and exits with a non-zero status. ## End-to-end run ```bash theme={"dark"} # 1. Upload a slide. Capture the sample id from its current ingest snapshot. sample_id=$(strand upload biopsy.svs --mpp 0.25 | jq -r .id) # 2. Wait until automatic ingest makes the sample prediction-ready. while :; do status=$(strand samples get "$sample_id" | jq -r .status) case "$status" in ready) break ;; *failed) echo "ingest failed: $status" >&2; exit 1 ;; esac sleep 2 done # 3. Price the exact request without creating a job or reserving credits. strand predict "$sample_id" --markers CD3e,CD4,PanCK --dry-run | jq # 4. Submit the same prediction and capture its job id. job_id=$(strand predict "$sample_id" --markers CD3e,CD4,PanCK | jq -r .job_id) # 5. Wait for a terminal status (SSE with polling fallback). strand wait "$job_id" --timeout 1800 # 6. Download OME-Zarr results or a pyramidal OME-TIFF. strand results "$job_id" --out ./results/ strand export "$job_id" --format ome-tiff --out ./result.ome.tiff --timeout 1800 ``` ## Commands ### `strand markers` List the markers your account can request (credit-free). The names printed are exactly what `strand predict` will accept for your account. ```bash theme={"dark"} strand markers ``` Wraps `client.markers.list()`. ### `strand upload` Upload a local whole-slide image. The command performs a resumable chunked upload and prints the sample's current ingest state. Dimensions may still be absent while ingest preprocessing continues. ```bash theme={"dark"} strand upload biopsy.svs strand upload biopsy.svs --mpp 0.25 strand upload biopsy.svs --content-type image/tiff --if-not-exists ``` | Option | Description | | - | - | | `--mpp FLOAT` | Microns per pixel for the slide (isotropic). Persisted at creation and takes precedence over the slide's own calibrated scale. | | `--content-type TEXT` | MIME type override. Auto-detected from the file extension when omitted. | | `--if-not-exists` | Dedup by content hash. Skips the byte upload when a matching sample already exists in your org. | Wraps `client.uploads.upload_file(...)`. Before an immediate dry run or submission, poll `strand samples get SAMPLE_ID` until `status` is `ready`. ### `strand predict` Price or submit a prediction against an uploaded sample. `--dry-run` prints the full estimate without creating a job or reserving credits. The default submission reserves credits and prints the job id. ```bash theme={"dark"} strand predict --markers CD3e,CD4,PanCK --dry-run strand predict --markers CD3e,CD4,PanCK strand predict -m CD4,Ki67 --model v0.7 ``` | Argument / option | Description | | - | - | | `SAMPLE_ID` | Sample id returned by `strand upload`. | | `--markers`, `-m` | Comma-separated marker names like `CD3e,CD4,PanCK`. | | `--model TEXT` | Lattice version. The server picks the current default when omitted. | | `--dry-run` | Validate and price the request without creating a job or reserving credits. | Wraps `client.predict.submit(..., dry_run=...)`. See [Markers](/markers/index) for the predictable panel. ### `strand status` Print a point-in-time status snapshot for a job: state, progress, markers, and the served model. ```bash theme={"dark"} strand status ``` Wraps `client.jobs.get().status`. ### `strand wait` Wait for a terminal job snapshot. The command prefers the job's SSE stream and falls back to status polling if the stream disconnects. ```bash theme={"dark"} strand wait strand wait --timeout 1800 --poll-interval 2 ``` | Option | Description | | - | - | | `--timeout FLOAT` | Maximum seconds to wait. Omit it to wait indefinitely. | | `--poll-interval FLOAT` | Seconds between status requests when polling is needed. Defaults to 2. | Wraps `client.jobs.get().wait(...)`. A failed job or elapsed timeout prints an error and exits non-zero; completed, partially failed, and cancelled snapshots print as JSON. ### `strand cancel` Cancel an eligible in-flight job, release its credit reservation, and print the refreshed post-cancel snapshot. ```bash theme={"dark"} strand cancel ``` Wraps `client.jobs.get().cancel()`. ### `strand results` Download a completed job's OME-Zarr result tree to a local directory. Streams the files through the API-key result proxy. ```bash theme={"dark"} strand results --out ./results/ ``` | Option | Description | | - | - | | `--out`, `-o` | Directory to write into. Created if missing. Defaults to `./results`. | Wraps `client.jobs.get().download_results(dir)`. ### `strand export` Request or reuse a generated result export, wait until it is ready, write it to the required destination path, and print that path. ```bash theme={"dark"} strand export --format ome-tiff --out ./result.ome.tiff strand export --format ome-zarr-zip --out ./result.zip --include-segmentation ``` | Option | Description | | - | - | | `--format` | Required: `ome-tiff` or `ome-zarr-zip`. Native OME-Zarr uses `strand results`. | | `--out`, `-o` | Required destination file. Parent directories are created. | | `--include-segmentation` | Attach the latest mask/cell manifest to the export response. | | `--timeout FLOAT` | Maximum seconds to wait for export. Omit it to wait indefinitely. | | `--poll-interval FLOAT` | Seconds between export-status requests. Defaults to 2. | Wraps `client.jobs.get().download_export(...)`. ### `strand samples list` List owned samples, the public cohort, or both through one cursor-paginated surface. The JSON envelope contains `items` and `next_cursor`; every item has canonical `id` and an `ownership` discriminator. ```bash theme={"dark"} strand samples list strand samples list --scope public --limit 50 strand samples list --scope all --cursor ``` | Option | Description | | - | - | | `--scope [mine\|public\|all]` | Sample scope. Defaults to `mine`. | | `--limit INTEGER` | Page size (API range 1 to 100). Defaults to 48. | | `--cursor TEXT` | Pagination cursor from a prior response's `next_cursor`. | Wraps `client.samples.list(...)`. ### `strand samples get` Read an owned or public sample using its canonical id. Owned output includes `jobs` and `job_count`. Public output includes geometry and marker channels. `--download` mirrors a public sample's OME-Zarr store. ```bash theme={"dark"} strand samples get strand samples get --download ./public-sample.zarr ``` Wraps `client.samples.get(...)`. ### `strand samples patch` Patch an owned sample's display name, unified fields, and/or physical scale. Omitted options are not sent. ```bash theme={"dark"} strand samples patch --name "Trial 42 baseline" strand samples patch --fields '{"tags":["trial-042","baseline"]}' --mpp 0.26 strand samples patch --clear-name ``` | Option | Description | | - | - | | `--name TEXT` | Set the display name. Mutually exclusive with `--clear-name`. | | `--clear-name` | Revert the display name to the filename. | | `--fields JSON` | Complete field values keyed by stable key. Use `{"tags":[]}` to clear Tags. | | `--mpp FLOAT` | Set isotropic microns per pixel. | Wraps `client.samples.patch(...)`. ### `strand uploads list` List resumable upload records for your organization. This is distinct from the scoped sample catalog. ```bash theme={"dark"} strand uploads list strand uploads list --limit 50 --cursor ``` | Option | Description | | - | - | | `--limit INTEGER` | Page size (1 to 200). Defaults to 100. | | `--cursor TEXT` | Pagination cursor from a prior response's `next_cursor`. | Wraps `client.uploads.list(...)`. ## See also * [Python SDK](/sdks/python) for the full library surface and result handling. * [SDK quickstart](/sdks/quickstart) for the Python and R end-to-end paths. # Python SDK Source: https://docs.strandai.com/sdks/python 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](/sdks/quickstart) 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](/microns-per-pixel) 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](/sdks/quickstart): upload, price, submit, wait, and download. * [REST API overview](/api/overview): the underlying HTTP surface. * [Pricing](/pricing): how retained model-grid tissue positions and markers determine credits. # SDK quickstart Source: https://docs.strandai.com/sdks/quickstart Create a Strand API key and predict spatially resolved protein-marker maps from H&E with Python or R. Lattice predicts spatially resolved protein-marker maps from routine H\&E, delivered as virtual mIF channels. This guide covers the programmatic workflow: upload, side-effect-free pricing, job submission, waiting, and result download. For the standard browser workflow, start with the [Platform quickstart](/quickstart). > [!WARNING] > > **For research use only.** Strand AI predictions are model outputs intended > for research and hypothesis generation. They are not validated for clinical > use. Do not use them for diagnosis, treatment selection, or patient care > decisions. ## 1. Create an API key Sign in to [app.strandai.com](https://app.strandai.com), select the organization your integration should use, and open [Settings → API keys](https://app.strandai.com/settings/api-keys). Choose “Create key” and copy the `sk-strand-…` value when it appears. The full value is shown only once. ```bash theme={"dark"} export STRAND_API_KEY=sk-strand-XXXXXXXXXXXXXXXXXXXXXXXX ``` > [!TIP] > > Treat the API key like a password. It is scoped to the selected organization > and uses that organization's sample access and credit balance. ## 2. Install a client ```bash Python theme={"dark"} pip install "strand-sdk[anndata]" ``` ```r R theme={"dark"} install.packages( "strandai", repos = c("https://strand-ai.r-universe.dev", "https://cloud.r-project.org") ) BiocManager::install("SpatialExperiment") ``` ## 3. Upload and price the run **Slides must be de-identified before upload.** Automated slide de-identification is off by default and runs only when enabled for the organization. It does not determine whether a slide satisfies HIPAA or any other legal de-identification standard, and it does not inspect or remove identifiers in tissue pixels or filenames. See [Security and data handling](/security-data-handling). ```python Python theme={"dark"} import time from strand import Client, StrandError client = Client() # reads STRAND_API_KEY upload = client.uploads.upload_file("biopsy.svs", mpp=0.26) markers = ["CD4", "PanCK", "Ki67"] # Automatic ingest preprocessing has started. Wait for sample metadata. deadline = time.monotonic() + 600 poll_seconds = 2.0 while True: sample = client.samples.get(upload.id) if sample.ownership != "mine": raise RuntimeError(f"uploaded sample resolved as {sample.ownership!r}") if sample.status == "ready": if not sample.width_px or not sample.height_px or not sample.mpp: raise RuntimeError("sample is ready but lacks prediction dimensions or MPP") break if sample.status.endswith("failed"): raise RuntimeError(f"ingest failed: {sample.status}") if sample.status not in {"uploading", "preprocessing"}: raise RuntimeError(f"unexpected ingest status: {sample.status}") if time.monotonic() >= deadline: raise TimeoutError(f"sample metadata was not ready: {sample.status}") time.sleep(poll_seconds) poll_seconds = min(poll_seconds * 1.5, 15.0) # Tissue-tile counting can finish later. A successful dry run is final readiness. deadline = time.monotonic() + 600 poll_seconds = 2.0 while True: try: estimate = client.predict.submit(upload.id, markers, dry_run=True) break except StrandError as err: if (err.status_code, err.error_code) != (409, "sample_not_ready"): raise if time.monotonic() >= deadline: raise TimeoutError("sample was not priceable after 10 minutes") from err time.sleep(poll_seconds) poll_seconds = min(poll_seconds * 1.5, 15.0) print(estimate.estimated_credits, estimate.org_balance) ``` ```r R theme={"dark"} library(strandai) client <- strand_client() # reads STRAND_API_KEY upload <- strand_upload_file(client, "biopsy.svs", progress = TRUE, mpp = 0.26) markers <- c("CD4", "PanCK", "Ki67") # Automatic ingest has started. Wait for sample metadata. deadline <- Sys.time() + 10 * 60 poll_seconds <- 2 repeat { sample <- strand_samples_get(client, upload$id) if (!identical(sample$ownership, "mine")) { stop("uploaded sample resolved as ", sample$ownership) } if (identical(sample$status, "ready")) { geometry <- c(sample$width_px, sample$height_px, sample$mpp) if (length(geometry) != 3L || any(!is.finite(geometry)) || any(geometry <= 0)) { stop("sample is ready but lacks prediction dimensions or MPP") } break } if (grepl("failed$", sample$status)) stop("ingest failed: ", sample$status) if (!sample$status %in% c("uploading", "preprocessing")) { stop("unexpected ingest status: ", sample$status) } if (Sys.time() >= deadline) stop("sample metadata was not ready: ", sample$status) Sys.sleep(poll_seconds) poll_seconds <- min(poll_seconds * 1.5, 15) } # Tissue-tile counting can finish later. A successful dry run is final readiness. deadline <- Sys.time() + 10 * 60 poll_seconds <- 2 repeat { estimate <- tryCatch( strand_predict(client, upload$id, markers, dry_run = TRUE), strand_api_error = function(e) e ) if (!inherits(estimate, "strand_api_error")) break if (!identical(estimate$status_code, 409L) || !identical(estimate$error_code, "sample_not_ready")) { stop(estimate) } if (Sys.time() >= deadline) stop("sample was not priceable after 10 minutes") Sys.sleep(poll_seconds) poll_seconds <- min(poll_seconds * 1.5, 15) } message(estimate$estimated_credits, " credits; balance ", estimate$org_balance) ``` `strand_upload_file()` returns after the storage event starts ingest. Sample metadata and tissue-tile pricing become ready asynchronously, so both bounded checks are required before an immediate prediction. Omit `mpp` when the slide's embedded calibration is authoritative. The dry run reports the exact price without creating a job or reserving credits. ## 4. Submit and wait ```python Python theme={"dark"} job = client.predict.submit(upload.id, markers) status = job.wait(timeout=1800) print(status.status) ``` ```r R theme={"dark"} job <- strand_predict(client, upload$id, markers) status <- strand_job_wait(job, timeout = 1800, progress = TRUE) message(status$status) ``` Submission reserves credits atomically. The job continues server-side if the client disconnects. ## 5. Download results ```python Python theme={"dark"} adata = job.download_results() job.download_export("ome-tiff", "result.ome.tiff", timeout=1800) ``` ```r R theme={"dark"} spe <- strand_download_results(job) strand_export_download(job, "ome-tiff", "result.ome.tiff") ``` The in-memory Python result is an `AnnData`. The R result is a `SpatialExperiment`. Both contain the requested marker channels aligned to the slide coordinate system. ## Next steps > [card] [Python SDK](/sdks/python) > > Typed samples, jobs, events, exports, and selective result reads. > [card] [R SDK](/sdks/r) > > `strand_*` functions and Bioconductor result handling. > [card] [Command line](/sdks/cli) > > Run the workflow from a shell without writing a script. > [card] [REST API](/api/overview) > > Use the canonical HTTP contract directly. # R SDK Source: https://docs.strandai.com/sdks/r Install the strandai R SDK, configure an API key, upload H&E slides, submit marker predictions, and load results as a SpatialExperiment for Bioconductor. The R SDK (`strandai`) provides idiomatic R functions for owned and public samples, prediction jobs, and result downloads. Functions use the `strand_*` prefix. Prediction results can be returned as a [`SpatialExperiment`](https://bioconductor.org/packages/SpatialExperiment/) for downstream Bioconductor pipelines. ## Install Install the released package from [r-universe](https://strand-ai.r-universe.dev/strandai): ```r theme={"dark"} install.packages( "strandai", repos = c("https://strand-ai.r-universe.dev", "https://cloud.r-project.org") ) # Or install the development version from GitHub: remotes::install_github("Strand-AI/strand-sdk-r") ``` For the recommended `SpatialExperiment` result, install: ```r theme={"dark"} BiocManager::install("SpatialExperiment") ``` ## Configuration | Source | Argument / variable | Default | | - | - | - | | Arg | `strand_client(api_key = ...)` | reads env | | Env | `STRAND_API_KEY` | required | | Env | `STRAND_BASE_URL` | `https://app.strandai.com` | ```r theme={"dark"} library(strandai) client <- strand_client() # reads STRAND_API_KEY client <- strand_client(api_key = "sk-strand-…") # explicit ``` ## Full pipeline One blocking call runs upload, submit, wait, and download: ```r theme={"dark"} result <- strand_run( client, "biopsy.ome.tiff", markers = c("PanCK", "CD4", "CD45"), output_dir = "./outputs/" ) cat("used", result$credits_used, "credits;", length(result$marker_outputs), "markers written\n") ``` `strand_run()` returns a `strand_predict_result` list with `job_id`, `status`, `credits_used`, `marker_outputs` (one path per marker under `output_dir`), `output_dir`, and `job` (the underlying `strand_job` handle). A `predict.strand_client` S3 method dispatches to the same pipeline: ```r theme={"dark"} result <- predict(client, "biopsy.ome.tiff", markers = c("PanCK", "CD4")) ``` Pass `on_progress = function(stage, fraction) ...` to follow the four stages (`"upload"`, `"submit"`, `"wait"`, `"download"`). ## Samples `strand_samples_list()` exposes one cursor-paginated collection with three exact, case-sensitive scopes: ```r theme={"dark"} mine <- strand_samples_list(client) # scope = "mine" public <- strand_samples_list(client, scope = "public", q = "TCGA-COAD") definitions <- strand_sample_fields_list(client) tags_id <- Filter(function(field) field$key == "tags", definitions)[[1]]$id all <- strand_samples_list( client, scope = "all", limit = 100L, status = "ready", workflow = "has_results", marker = strand_marker_filter("CD20", "completed"), field = strand_field_filter(tags_id, "eq", "trial-042") ) if (!is.null(all$next_cursor)) { next_page <- strand_samples_list( client, scope = "all", limit = 100L, cursor = all$next_cursor ) } ``` Use `strand_sample_fields_list()` to discover field definition IDs, including predefined Tags and Public. Definitions identify `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"`. Every list item has `ownership`, canonical `id`, and `app_url`; each page has an `app_url` for its exact filtered browser view. Owned and public fields remain distinct: | Ownership | List item fields | | - | - | | `"mine"` | `id`, `app_url`, `name`, `filename`, `status`, `file_size`, `fields`, `created_at` | | `"public"` | `id`, `app_url`, `title`, `thumbnail_url` | Pass either branch's `id` to `strand_samples_get()`: ```r theme={"dark"} sample <- strand_samples_get(client, all$items[[1]]$id) if (sample$ownership == "mine") { message(sample$job_count, " jobs; ", length(sample$jobs), " returned") } else { message("public markers: ", paste(sample$markers, collapse = ", ")) } ``` Owned detail contains up to the 50 newest inference jobs plus the uncapped `job_count`. Public detail contains geometry, live markers, and public asset URLs; `jobs` and `job_count` are absent. Update owned sample attributes with one patch. `NULL` omits a field, `clear_name = TRUE` restores the filename as the display name, and each entry in `fields` replaces the complete value. Public is read-only: ```r theme={"dark"} sample <- strand_patch_sample( client, upload$id, name = "Baseline biopsy", fields = list(tags = c("baseline", "responding")), mpp = 0.26 ) strand_patch_sample(client, upload$id, clear_name = TRUE) strand_patch_sample(client, upload$id, fields = list(tags = list())) ``` ### Cell segmentation Segmentation belongs to the sample rather than to a prediction job, and it costs no credits. Uploads segment automatically unless the organization or the upload opts out; start or retry it explicitly with `strand_segmentation_start()`: ```r theme={"dark"} state <- strand_segmentation_get(client, sample$id) if (state$status %in% c("not_started", "failed")) { state <- strand_segmentation_start(client, sample$id) } manifest <- strand_segmentation_manifest(client, sample$id, state$layer$id) ``` The call is idempotent: completed or active work is returned unchanged, a failed layer is retried after the server's 60-second cooldown, and public samples are read-only. The manifest describes the uint32 label-mask OME-Zarr, the per-cell geometry and morphology table, and per-marker expression tables. The tables join each other on `instance_id`, and each row ties back to the mask through `local_label`. The `SpatialExperiment` from `strand_download_results()` is a pixel-grid matrix of marker predictions, not per-cell expression. ## End-to-end ```r theme={"dark"} upload <- strand_upload_file(client, "biopsy.svs", progress = TRUE, mpp = 0.26) # GCS starts ingest automatically after the final chunk. upload_file waits for # that event to advance the sample beyond `uploading`; no finalize call exists. # Optional: set a display name and unified fields. strand_patch_sample( client, upload$id, name = "Baseline biopsy", fields = list(tags = c("baseline", "responding")) ) markers <- c("CD4", "PanCK", "Ki67") est <- strand_predict(client, upload$id, markers, dry_run = TRUE) message("will cost ~", est$estimated_credits, " credits") job <- strand_predict(client, upload$id, markers) status <- strand_job_wait(job, progress = TRUE) spe <- strand_download_results(job) # SpatialExperiment # Or download a single pyramidal OME-TIFF for QuPath or Fiji. strand_export_download(job, "ome-tiff", "result.ome.tiff") ``` To cancel an in-flight job and refund its reserved credits: ```r theme={"dark"} status <- strand_job_cancel(job) ``` ### Selecting a model `strand_predict()` and `strand_run()` accept an optional `model =`: * `"v0.7"`: current dispatchable version and default. Omit `model` (or pass `NULL`) 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. ```r theme={"dark"} result <- strand_run( client, "slide.svs", markers = c("CD4", "Ki67", "PanCK"), model = "v0.7" ) ``` `strand_predict_result$model` (and the `model` field on `strand_job_get()` output) contain the canonical `v0.X` label the platform 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`. `strand_run()` returns the `strand_job` handle as soon as upload and submission complete: ```r theme={"dark"} job <- strand_run(client, "slide.svs", markers = c("CD3e", "CD4"), wait = FALSE) message("submitted ", job$id) # ...do other work, or shut down the process. The job runs server-side. # Later (same process or a fresh one via `strand_job_get(client, job$id)`): status <- strand_job_wait(job) spe <- strand_download_results(job) ``` When `wait = FALSE`, the `"wait"` and `"download"` progress stages don't fire, and `timeout_sec` / `poll_interval_sec` / `output_dir` are ignored. ## Function reference | Function | What it does | | - | - | | `strand_client(api_key, base_url)` | Construct a client handle. | | `strand_upload_file(client, path, progress)` | Resumable chunked upload of a WSI to GCS. | | `strand_uploads_list(client, limit, cursor)` | List uploads with cursor pagination. | | `strand_uploads_get(client, upload_id)` | Retrieve one upload. | | `strand_samples_list(client, scope, limit, cursor, q, status, uploaded_from, uploaded_to, workflow, marker, field)` | List and filter owned samples, public samples, or both. | | `strand_marker_filter(marker, state)` / `strand_field_filter(field_id, operator, value)` | Build typed list-filter clauses. | | `strand_sample_fields_list(client)` | Discover organization custom-field definitions. | | `strand_samples_get(client, sample_id)` | Read an owned sample with job history or public detail by share id. | | `strand_patch_sample(client, sample_id, name, fields, mpp, clear_name)` | Update owned sample attributes. | | `strand_markers_list(client)` | List the markers your account can request (credit-free). | | `strand_predict(client, upload_id, markers, model, dry_run = TRUE)` | Price a prediction without side effects. | | `strand_predict(client, upload_id, markers, model)` | Submit a prediction and reserve credits. | | `strand_run(client, image_path, markers, model, wait, ...)` | Full pipeline. `wait = FALSE` returns a `strand_job` after submit. | | `strand_job_get(client, job_id)` | Refetch a job snapshot. | | `strand_job_cancel(job)` | Cancel an in-flight job and return its refreshed status. | | `strand_job_wait(job, progress, timeout)` | Block until terminal status. | | `strand_segmentation_get(client, sample_id)` | Read cell-segmentation lifecycle state. | | `strand_segmentation_start(client, sample_id)` | Start or retry segmentation. Credit-free and idempotent. | | `strand_segmentation_manifest(client, sample_id, layer_id)` | Read the mask, morphology, and expression manifest. | | `strand_download_results(job)` | Return results as `SpatialExperiment`. | | `strand_export_request(job, format, ...)` | Request native OME-Zarr, OME-Zarr ZIP, or OME-TIFF with optional processed H\&E, segmentation, or the separate stored original upload (`include_original_upload = TRUE`). The original can be multi-GB. After ingest de-identification, it is the stored de-identified copy. Its 15-minute URL is a bearer link. Keep it private. Refresh or resume may request a new link, subject to issuance limits. | | `strand_export_download(job, format, path)` | Wait for and download a generated ZIP or TIFF. | ## Error handling Documented HTTP error codes map to typed conditions you can dispatch on: | HTTP | Condition class | | - | - | | 400 | `strand_bad_request_error` | | 401 | `strand_auth_error` | | 402 | `strand_insufficient_credits_error` (carries `required`) | | 404 | `strand_not_found_error` | ```r theme={"dark"} tryCatch( strand_predict(client, upload$id, markers), strand_insufficient_credits_error = function(e) { message("need ", e$required, " credits; top up the org first.") } ) ``` ## See also * [SDK quickstart](/sdks/quickstart): upload, price, submit, wait, and download. * [REST API overview](/api/overview): the underlying HTTP surface. * [Pricing](/pricing): how retained model-grid tissue positions and markers determine credits. # Security and data handling Source: https://docs.strandai.com/security-data-handling How Strand AI stores, encrypts, retains, and deletes your data, and our commitment never to train on it without your opt-in. This page describes how Strand AI handles the data you send us: what we store, how it is protected, how long we keep it, and how it is deleted. For the mechanics of setting expiration windows and restoring from “Trash”, see [Sample expiration](/expiration). ## What we store Uploading a whole-slide image creates a sample: the persistent Strand entity that carries organization ownership, status, jobs, and results. We store two kinds of data for that sample: * **Uploaded whole-slide image**: the source image you upload for prediction. * **Marker predictions**: the per-marker outputs generated from that image, including the image pyramids served back to you. We also keep operational records (see [Logs are retained separately](#logs-are-retained-separately) below) that are distinct from your sample data. ## De-identified input requirement **Slides must be de-identified before upload.** Do not upload protected health information (PHI) or other regulated identifiable health information unless a separate written agreement with Strand AI expressly authorizes that processing. This requirement covers the slide pixels, embedded label and macro images, scanner metadata, and filename. Whole-slide images often carry identifiers in an embedded **label image**, a **macro image**, scanner-written **metadata fields**, or the filename. Remove these identifiers before upload. If identifiers are baked into the tissue region, crop or re-scan the slide before uploading. ## Optional de-identification at ingest Automated slide de-identification is **off by default** and runs only when Strand AI enables it for your organization. When enabled, the ingest pipeline removes embedded label and macro images and known PHI-bearing metadata fields, then validates the result before permanent storage. Unsupported formats or failed validation stop that enabled path. The enabled path does not retain an unprocessed copy in permanent storage. Automated de-identification does not scan or redact identifiers in the tissue image or filename. It does not replace de-identification before upload, and it is not a representation that data satisfies HIPAA or any other legal de-identification standard. ## Encryption Your data is encrypted **in transit** and **at rest**. Strand AI runs on enterprise-grade cloud infrastructure with encryption applied to stored objects and database records, and TLS protecting data moving between you and our services. ## Retention & deletion Retention is under your control. Expiration is **opt-in**: samples never expire until an owner or admin sets a policy (see [Sample expiration](/expiration) for how to configure it). When a sample expires, it moves to “Trash”, where it is held for **7 days**. During that window you can restore it. After the window closes, the sample and its marker predictions are **permanently deleted 7 days after expiry**. Both the stored objects and the corresponding database records are removed. > [!NOTE] > > Deletion happens over a **window** rather than instantly. A sample is permanently > deleted 7 days after it expires, once it has passed through the Trash grace > period, and remains restorable until then. ### Logs are retained separately Your **sample data** (uploads and the predictions derived from them) is deleted according to your retention policy as described above. **Operational and audit logs are kept separately** and are retained beyond your sample data for security, billing, and compliance purposes. These logs do not contain your slide images or prediction outputs; billing history is preserved even after the underlying samples are deleted. ## Access control & audit logging Access to samples is scoped to your organization and governed by role-based permissions (see the permissions table in [Sample expiration](/expiration#permissions)). Retention actions (automatic archival on expiry and permanent deletion after the grace window) are **audit-logged**, recording what was deleted and when. ## We do not train on your data We do not use your data to train our models. If that ever changes, we will notify you in advance, and any such use will be opt-in. ## MCP connections and explicit conversation context The hosted MCP endpoint authorizes each action against the connected user and organization, using OAuth or an organization-bound API key. Slide transfer goes directly to GCS rather than through MCP. Core upload/result tool responses contain expiring bearer URLs in model-visible context; keep them out of prose, logs, and screenshots. Do not use chat to relay multi-GB slides or PHI. The in-chat Lattice viewer is read-only, and result pixels never enter the model's context. `strand_ai.view_sample` requires an organization-scoped sample ID returned by `list_samples`; the same public slide can have a different ID in another organization. Opening a sample gives the model a bounded sample card (ID, ownership, name, readiness, MPP, segmentation status, the latest job's status, progress, and markers, and a platform link) and a result summary (count, and the newest result's status, markers, and completion time); the result IDs the viewer switches between stay in the viewer. Core tools such as `get_sample` and `get_job` return job IDs to the model as usual. The viewer reads result files with a short-lived, read-only permission for one result, checked on every read against the live connection. A compliant host keeps the app-only `strand_ai.viewer_session` and its result away from the model; the server cannot enforce a malicious host's model delivery choices. Conversation-host policies govern sample metadata shared in chat separately from Strand AI sample retention. Candidate paid approval state contains only bounded normalized arguments, a fresh UUID, and exact patch/marker/credit estimate, encrypted and bound to audience, principal/organization, method, tool, and arguments for 600 seconds. It contains no bearer credential or sample display name. The approved REST replay mapping lasts while the associated job remains stored; permanent deletion of the job/sample/organization/account removes it. This is not a claim that current production already provides native approval or exactly-once submission. ## Related policies The [Strand AI Privacy Policy](https://strandai.com/privacy) explains how we collect and use personal information. The [Terms of Service](https://strandai.com/terms) govern use of the Strand AI services. # Viewer keyboard shortcuts Source: https://docs.strandai.com/viewer/keyboard-shortcuts Keyboard shortcuts for panning, zooming, toggling layers, and controlling markers in the slide viewer. The slide viewer supports keyboard shortcuts for common actions. Press ? at any time (or select the “?” button in the viewer toolbar) to open the same cheatsheet inside the viewer. ## Layers | Shortcut | Action | | - | - | | H | Toggle the H\&E background layer | | A | Auto-contrast the selected marker | | \[ / ] | Select the previous / next marker | | Alt + click a marker's checkbox | Solo that marker (show only it); Alt-click again to restore | ## View | Shortcut | Action | | - | - | | S | Toggle split / single view | | F | Toggle fullscreen | | Arrow keys | Pan the slide | | Scroll | Zoom in / out | ## Tools | Shortcut | Action | | - | - | | V | Pan / select tool | | M | Measure tool | | Esc | Cancel measure, or close the shortcuts panel | ## Help | Shortcut | Action | | - | - | | ? | Show or hide the shortcuts panel | Shortcuts are ignored while typing in a text field, so they never interfere with search or numeric inputs.