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

# R SDK

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


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