Overview
A workflow runs tool steps: any website tool, one after another, each reading the previous step's output without a new upload. Build workflows in the Automations builder or with POST /api/v2/workflows, and add triggers, schedules, branches, approvals and agent steps around the tool steps.
A chain is a workflow made only of tool steps. POST /api/v2/document-chains still runs one in a single request, with the same SDK and MCP methods, but it is deprecated in favour of workflows. Each chain request creates and runs a workflow, so you can also read, cancel and replay the chain as a workflow run.
- In a workflow graph, a tool-steps node is
{"type": "action", "action": "document-chains.create", "configuration": {"steps": [...]}}, charged one request unit per step when the node starts. It takes the same steps, sources, inputs, keep and metadata as a chain request. - A single tool is a
document-operations.createstep. Cancelling a run stops every step that has not started and refunds its request unit, as cancelling a chain does. - The chain routes return
Deprecation: trueand aLinkheader that names/api/v2/workflowsas their successor. They keep working.
Deprecated chain routes and what they do now
| Route (deprecated) | What it does now |
|---|---|
POST /api/v2/document-chains | Creates a published workflow with one tool-steps node (document-chains.create) holding your steps, and starts a run of it. The response is the chain, with chain.workflow {id, versionId, runId}. |
GET /api/v2/document-chains/{chainId} | Reads the chain, as before. |
POST /api/v2/document-chains/{chainId}/cancel | Cancels the chain and its workflow run, like POST /api/v2/workflow-runs/{runId}/cancel. Steps that have not started are cancelled and their request units refunded. |
POST /api/v2/document-chains/{chainId}/resume | Runs the failed or cancelled steps again as a new run of the same workflow (replayMode RESUME). |
GET /api/v2/document-chains/{chainId}/events | Streams the chain as before. |
No limit on tool steps
There is no fixed limit on how many tools you chain. Each operation can take the output of any earlier operation, and a chain can continue from another chain, so a document can pass through as many steps as you need, in any order. One document-chains request carries up to 25 steps; continue past that by starting the next chain from the last step. The snippet builder in the API reference (Snippeted) stops at 10 steps only to keep the generated code readable. Your plan's request units, credits and concurrency are the only limits.
Tool steps and customization have no limit beyond the snippet builder. Snippeted (/docs/developer-api/snippet-builder) builds up to 10 steps; the code on this page works with any number of steps and any logic of your own between them.
- Every website tool is one document operation (
POST /api/v2/document-operations) with its own request, SDK method and Snippet, includingocr-pdfand the multi-part tools. - Several of them run on one document as the tool steps of one workflow; the deprecated one-request form (
POST /api/v2/document-chains) creates that workflow for you. Each step reads the previous step's output, so the file is uploaded once. - Each operation can also name any earlier operation as its input with
source.operationId, so you can build any shape of flow yourself: linear, branching, fan-out over parts and merge back.
Beyond ten steps, and your own customization
Snippeted, the snippet builder in the API reference, chains up to 10 tools or features. That keeps the generated code readable; it is not an API limit. To go further, copy the builder's code and add steps yourself: one document-chains request carries up to 25 steps, and the next request continues from the last step's operation, so there is no total limit (see Continue past 25 steps).
To customize, wrap the SDK calls in your own code: a function of your own (cleanUp, archiveContract) that builds the steps from your settings, an approval or branch in your service between two steps (name the previous output with source.operationId, so nothing is uploaded again), or a workflow with triggers, schedules and approvals if you prefer not to run a server.
- More than ten steps: build the steps array in a loop or from your own configuration; the generated code's upload, wait and download parts stay the same.
- Your own functions: put the steps behind a function your app calls (the example below), so a change of tools or settings happens in one place.
- Your own buttons: browser code calls your server; your server holds the key and calls the SDK (see Your own logic between steps). The tool embed adds your own buttons and hooks to a Wellfriend tool workspace (/docs/developer-api/tool-embeds).
- Conditions, schedules, approvals and agents: workflows (/docs/automations), whose tool-steps node takes the same steps.
// Your own method around the SDK: any number of steps, built from your settings, one upload.
import { Wellfriend } from "wellfriend-document-sdk";
const wf = new Wellfriend({ apiKey: process.env.WELLFRIEND_API_KEY ?? "YOUR_API_KEY" });
type Step = { tool: string; params?: Record<string, unknown> };
type Input = string | { documentId: string; versionId: string };
export async function cleanUpForArchive(path: string, client: string, extra: Step[] = []) {
const steps: Step[] = [
{ tool: "repair-pdf" },
{ tool: "compress-pdf", params: { profile: "balanced" } },
{ tool: "ocr-pdf", params: { languages: "en" } },
{ tool: "add-watermark", params: { type: "text", text: `Client ${client}` } },
...extra, // more steps from your own configuration: 11, 20 or 50 of them
];
// One pipeline runs up to 10 steps; the next one starts from the last output, so nothing is uploaded again.
let input: Input = path;
for (let start = 0; start < steps.length; start += 10) {
const result = await wf.pipeline(steps.slice(start, start + 10)).run(input);
const [output] = result.outputs;
input = { documentId: output.documentId, versionId: output.versionId };
}
return input; // { documentId, versionId } of the final result
}One request, many steps
This is the code the Snippet panel prints for a four-step chain. Each step's main input is the previous step's output; merge-pdf adds a cover from a second upload. The response is 202 with the chain: wait for it, follow its events, or receive a webhook when it ends.
#!/usr/bin/env bash
# Needs curl and jq.
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
set -euo pipefail
API="${WELLFRIEND_API_URL:-https://wellfriend.dev}"
WELLFRIEND_API_KEY="${WELLFRIEND_API_KEY:-YOUR_API_KEY}"
AUTH="Authorization: Bearer $WELLFRIEND_API_KEY"
RUN=$(uuidgen) # reuse this value to retry safely
# upload FILE CONTENT_TYPE KEY: prints the document id and its version id
upload() {
curl -sS --fail-with-body -X POST "$API/api/v2/documents" -H "$AUTH" -H "Idempotency-Key: $3" \
-H "Content-Type: $2" -H "X-Wellfriend-Filename: $(basename "$1")" --data-binary "@$1" \
| jq -r '"\(.document.id) \(.document.currentVersion.id)"'
}
read -r DOCUMENT_ID VERSION_ID < <(upload 'invoice.pdf' 'application/pdf' "$RUN-upload")
read -r FILE1_DOC FILE1_VER < <(upload 'cover.pdf' 'application/pdf' "$RUN-file-1")
# 4 steps in one request; each step reads the previous step's output on the server.
# Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
STEPS='[{"id":"step-1","toolId":"compress-pdf","parameters":{"profile":"best"}},{"id":"step-2","toolId":"ocr-pdf","parameters":{"languages":"en,hi"}},{"id":"step-3","toolId":"merge-pdf","parameters":{}},{"id":"step-4","toolId":"pdf-to-word","parameters":{}}]'
CHAIN=$(jq -n --arg doc "$DOCUMENT_ID" --arg ver "$VERSION_ID" --arg key "$RUN" --arg file1d "$FILE1_DOC" --arg file1v "$FILE1_VER" --argjson steps "$STEPS" \
'{idempotencyKey: $key, source: {documentId: $doc, versionId: $ver}, steps: ($steps | .[2].inputs[0] = {documentId: $file1d, versionId: $file1v})}' \
| curl -sS --fail-with-body -X POST "$API/api/v2/document-chains" -H "$AUTH" \
-H "Content-Type: application/json" -H "Idempotency-Key: $RUN" --data-binary @- | jq -r .chain.id)
while :; do
RESULT=$(curl -sS --fail-with-body "$API/api/v2/document-chains/$CHAIN" -H "$AUTH")
STATE=$(echo "$RESULT" | jq -r .chain.state)
case "$STATE" in completed) break ;; failed|canceled) echo "$RESULT" | jq .chain.error >&2; exit 1 ;; esac
sleep 1
done
DOCUMENT_ID=$(echo "$RESULT" | jq -r .chain.output.documentId)
VERSION_ID=$(echo "$RESULT" | jq -r .chain.output.versionId)
# Download the result
curl -sS --fail-with-body "$API/api/v2/documents/$DOCUMENT_ID/versions/$VERSION_ID/content" -H "$AUTH" -o 'invoice-wellfriend.docx'// Node.js 20+, no dependencies. An ES module (top-level await): save it as .mjs.
import { readFile, writeFile } from "node:fs/promises";
import { basename } from "node:path";
// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
const API = process.env.WELLFRIEND_API_URL ?? "https://wellfriend.dev";
const auth = { Authorization: `Bearer ${process.env.WELLFRIEND_API_KEY ?? "YOUR_API_KEY"}` };
const run = crypto.randomUUID(); // reuse this value to retry safely
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function call(path, init = {}) {
const response = await fetch(`${API}${path}`, { ...init, headers: { ...auth, ...init.headers } });
if (!response.ok) throw new Error(`${response.status} ${path}: ${await response.text()}`);
return response;
}
async function post(path, body) {
const response = await call(path, { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": body.idempotencyKey }, body: JSON.stringify(body) });
return response.json();
}
async function upload(path, contentType, key) {
const response = await call("/api/v2/documents", {
method: "POST",
headers: { "Content-Type": contentType, "X-Wellfriend-Filename": basename(path), "Idempotency-Key": `${run}:${key}` },
body: await readFile(path),
});
const { document } = await response.json();
return { documentId: document.id, versionId: document.currentVersion.id };
}
let source = await upload("invoice.pdf", "application/pdf", "upload");
const file1 = await upload("cover.pdf", "application/pdf", "file-1");
// 4 steps in one request; each step reads the previous step's output on the server (no re-upload).
// Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
let { chain } = await post("/api/v2/document-chains", {
idempotencyKey: run,
source,
steps: [
{ id: "step-1", toolId: "compress-pdf", parameters: { profile: "best" } },
{ id: "step-2", toolId: "ocr-pdf", parameters: { languages: "en,hi" } },
{
id: "step-3",
toolId: "merge-pdf",
parameters: {},
inputs: [
file1,
],
},
{ id: "step-4", toolId: "pdf-to-word", parameters: {} },
],
});
while (!["completed", "failed", "canceled", "cancelled"].includes(chain.state)) {
await sleep(1000);
({ chain } = await (await call(`/api/v2/document-chains/${chain.id}`)).json());
}
if (chain.state !== "completed") throw new Error(`Step ${chain.failedStep} ${chain.state}: ${JSON.stringify(chain.error ?? null)}`);
source = chain.output;
const output = await call(`/api/v2/documents/${source.documentId}/versions/${source.versionId}/content`);
await writeFile("invoice-wellfriend.docx", Buffer.from(await output.arrayBuffer()));# Python 3.9+ with requests (pip install requests).
import os
import time
import uuid
import requests
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
API = os.environ.get("WELLFRIEND_API_URL", "https://wellfriend.dev")
AUTH = {"Authorization": "Bearer " + os.environ.get("WELLFRIEND_API_KEY", "YOUR_API_KEY")}
run = uuid.uuid4().hex # reuse this value to retry safely
def call(method, path, **kwargs):
response = requests.request(method, API + path, headers={**AUTH, **kwargs.pop("headers", {})}, timeout=300, **kwargs)
if not response.ok:
raise RuntimeError(f"{response.status_code} {path}: {response.text}")
return response
def post(path, body):
return call("POST", path, json=body, headers={"Idempotency-Key": body["idempotencyKey"]}).json()
def upload(path, content_type, key):
with open(path, "rb") as handle:
document = call("POST", "/api/v2/documents", data=handle, headers={
"Content-Type": content_type,
"X-Wellfriend-Filename": os.path.basename(path),
"Idempotency-Key": f"{run}:{key}",
}).json()["document"]
return {"documentId": document["id"], "versionId": document["currentVersion"]["id"]}
source = upload("invoice.pdf", "application/pdf", "upload")
file1 = upload("cover.pdf", "application/pdf", "file-1")
# 4 steps in one request; each step reads the previous step's output on the server (no re-upload).
# Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
chain = post("/api/v2/document-chains", {
"idempotencyKey": run,
"source": source,
"steps": [
{
"id": "step-1",
"toolId": "compress-pdf",
"parameters": {"profile": "best"},
},
{
"id": "step-2",
"toolId": "ocr-pdf",
"parameters": {"languages": "en,hi"},
},
{
"id": "step-3",
"toolId": "merge-pdf",
"parameters": {},
"inputs": [
file1,
],
},
{"id": "step-4", "toolId": "pdf-to-word", "parameters": {}},
],
})["chain"]
while chain["state"] not in ("completed", "failed", "canceled", "cancelled"):
time.sleep(1)
chain = call("GET", "/api/v2/document-chains" + "/" + chain["id"]).json()["chain"]
if chain["state"] != "completed":
raise RuntimeError(f"Step {chain.get('failedStep')} {chain['state']}: {chain.get('error')}")
source = chain["output"]
output = call("GET", f"/api/v2/documents/{source['documentId']}/versions/{source['versionId']}/content")
with open("invoice-wellfriend.docx", "wb") as handle:
handle.write(output.content)// wellfriend-document-sdk: npm install wellfriend-document-sdk@latest. An ES module (top-level await): save it as .mts.
// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
import { Wellfriend } from "wellfriend-document-sdk";
const wf = new Wellfriend({ apiKey: process.env.WELLFRIEND_API_KEY ?? "YOUR_API_KEY" });
// 4 steps; each takes the previous result, which stays on the server (nothing is uploaded again).
// Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
const step1 = await wf.tools.compressPdf("invoice.pdf", { profile: "best" });
const step2 = await wf.tools.ocrPdf(step1, { languages: "en,hi" });
const step3 = await wf.tools.mergePdf([step2, "cover.pdf"]);
const step4 = await wf.tools.pdfToWord(step3);
const result = step4;
await result.save("invoice-wellfriend.docx");# wellfriend-document-sdk: pip install -U wellfriend-document-sdk
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
import os
from wellfriend import Wellfriend
wf = Wellfriend(api_key=os.environ.get("WELLFRIEND_API_KEY", "YOUR_API_KEY"))
# 4 steps; each takes the previous result, which stays on the server (nothing is uploaded again).
# Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
step1 = wf.tools.compress_pdf("invoice.pdf", profile="best")
step2 = wf.tools.ocr_pdf(step1, languages="en,hi")
step3 = wf.tools.merge_pdf([step2, "cover.pdf"])
step4 = wf.tools.pdf_to_word(step3)
result = step4
result.save("invoice-wellfriend.docx")// go get wellfriend.dev/go/wellfriend@latest
package main
import (
"context"
"fmt"
"os"
"wellfriend.dev/go/wellfriend"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
apiKey := os.Getenv("WELLFRIEND_API_KEY")
if apiKey == "" {
apiKey = "YOUR_API_KEY"
}
wf := wellfriend.New(wellfriend.WithAPIKey(apiKey))
ctx := context.Background()
// 4 steps; each takes the previous result, which stays on the server (nothing is uploaded again).
// Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
step1, err := wf.Tools.CompressPDF(ctx, wellfriend.File("invoice.pdf"), &wellfriend.CompressPDFParams{Profile: wellfriend.Ptr(wellfriend.CompressPDFProfile("best"))})
if err != nil {
return err
}
step2, err := wf.Tools.OCRPDF(ctx, wellfriend.ExistingDocument(*step1.Output().DocumentID, *step1.Output().VersionID), &wellfriend.OCRPDFParams{Languages: wellfriend.String("en,hi")})
if err != nil {
return err
}
step3, err := wf.Tools.MergePDF(ctx, []wellfriend.FileInput{wellfriend.ExistingDocument(*step2.Output().DocumentID, *step2.Output().VersionID), wellfriend.File("cover.pdf")}, nil)
if err != nil {
return err
}
step4, err := wf.Tools.PDFToWord(ctx, wellfriend.ExistingDocument(*step3.Output().DocumentID, *step3.Output().VersionID), nil)
if err != nil {
return err
}
res := step4
return res.Save(ctx, "invoice-wellfriend.docx")
}#!/usr/bin/env bash
# Needs the wellfriend CLI: npm install -g wellfriend-document-sdk@latest
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
set -euo pipefail
export WELLFRIEND_API_KEY="${WELLFRIEND_API_KEY:-YOUR_API_KEY}"
# 4 steps; each takes the previous result, which stays on the server (nothing is uploaded again). Needs jq.
# Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
DOCUMENT=$(wellfriend compress-pdf invoice.pdf --param profile=best --no-download --json | jq -r '.outputs[0].documentId')
DOCUMENT=$(wellfriend ocr-pdf "$DOCUMENT" --param languages=en,hi --no-download --json | jq -r '.outputs[0].documentId')
DOCUMENT=$(wellfriend merge-pdf "$DOCUMENT" cover.pdf --no-download --json | jq -r '.outputs[0].documentId')
wellfriend pdf-to-word "$DOCUMENT" -o invoice-wellfriend.docx// cargo add wellfriend-document-sdk serde_json && cargo add tokio --features full
use serde_json::json;
use wellfriend::{FileInput, types::CompressPdfParams, types::OcrPdfParams, Wellfriend};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
let api_key = std::env::var("WELLFRIEND_API_KEY").unwrap_or_else(|_| "YOUR_API_KEY".into());
let wf = Wellfriend::builder().api_key(api_key).build()?;
// 4 steps; each takes the previous result, which stays on the server (nothing is uploaded again).
// Each step uses 1 request unit whatever its page count; OCR steps also use credits by page (POST /api/v2/quote prices a run).
let stored = |result: &wellfriend::ToolResult| {
let output = &result.outputs[0];
FileInput::version(output.document_id.clone().unwrap_or_default(), output.version_id.clone().unwrap_or_default())
};
let params1: CompressPdfParams = serde_json::from_value(json!({ "profile": "best" }))?;
let step1 = wf.tools().compress_pdf(FileInput::from("invoice.pdf"), Some(params1)).await?;
let params2: OcrPdfParams = serde_json::from_value(json!({ "languages": "en,hi" }))?;
let step2 = wf.tools().ocr_pdf(stored(&step1), Some(params2)).await?;
let step3 = wf.tools().merge_pdf([stored(&step2), FileInput::from("cover.pdf")], None).await?;
let step4 = wf.tools().pdf_to_word(stored(&step3), None).await?;
step4.save("invoice-wellfriend.docx").await?;
Ok(())
}// Wellfriend MCP server (your API key, YOUR_API_KEY, goes in your MCP client's config): call document_chain, then document_chain_get until it is completed.
{
"tool": "document_chain",
"arguments": {
"idempotencyKey": "<run>",
"source": {
"documentId": "<documentId from document_upload_url>",
"versionId": "<versionId>"
},
"steps": [
{
"id": "step-1",
"toolId": "compress-pdf",
"parameters": {
"profile": "best"
}
},
{
"id": "step-2",
"toolId": "ocr-pdf",
"parameters": {
"languages": "en,hi"
}
},
{
"id": "step-3",
"toolId": "merge-pdf",
"parameters": {},
"inputs": [
{
"documentId": "<documentId of cover.pdf>",
"versionId": "<versionId of cover.pdf>"
}
]
},
{
"id": "step-4",
"toolId": "pdf-to-word",
"parameters": {}
}
]
}
}Request and response
| Field | Meaning |
|---|---|
| idempotencyKey | Required. Replaying the same key returns the same chain (200, accepted false) and never runs or charges it twice. Keys are 8 to 200 characters of letters, digits and . _ : - (join parts with ":", never "/"). |
| source | {documentId, versionId?}: a stored version; or {operationId, output?}: the output of any earlier operation, including the last step of another chain. |
| steps[] | 1 to 25 steps: {id?, toolId, parameters?, inputs?, assets?, keep?}. id defaults to step-N. |
| steps[].inputs, steps[].assets | Further inputs (merge-pdf) and asset files (a watermark logo): stored versions, {operationId, output?}, or {step: "<id>", output?} for an earlier step of this chain. |
| steps[].keep | Keep this step's output after 1 hour. The last step is always kept; other steps' outputs are intermediates. |
| metadata | Your own string labels, returned on the chain and in its events. |
| chain.state | running, completed, failed or canceled. The state values are spelt as the API returns them, so a cancelled chain reads canceled. |
| chain.steps[] | Each step's state (waiting, queued, running, completed, failed or canceled, spelt as the API returns it), operationId, attempt, output version, whether it is an intermediate and when it expires, and its error. |
| chain.units | Request units reserved, refunded and charged. |
chain.failedStep, chain.error | The step that stopped the chain and why. |
| chain.output | The last step's output version once the chain completes. |
Continue past 25 steps, without limit
One request carries up to 25 steps. That is a request-size limit, not a chaining limit: start the next chain from the last step's operation and keep going for as many steps as you need.
// Past one pipeline: run the next steps on the last step's output, where it is stored (nothing is uploaded again).
const first = await wf.pipeline(steps.slice(0, 10)).run("big.pdf", { idempotencyKey: `${run}:part-1` });
const [last] = first.outputs; // { documentId, versionId, filename, ... }
const second = await wf.pipeline(steps.slice(10, 20)).run(last, { idempotencyKey: `${run}:part-2` });
await second.save("out.pdf");
// …and so on: there is no limit on how many runs follow one another.# Past one pipeline: run the next steps on the previous result, where it is stored (nothing is uploaded again).
first = wf.pipeline(steps[:10]).run("big.pdf", options={"idempotency_key": f"{run}:part-1"})
second = wf.pipeline(steps[10:20]).run(first, options={"idempotency_key": f"{run}:part-2"})
second.save("out.pdf")# Continue from the last step of an earlier chain (or any operation), with nothing uploaded again.
curl -sS -X POST "$API/api/v2/document-chains" -H "$AUTH" -H "Content-Type: application/json" \
-H "Idempotency-Key: $RUN:part-2" -d '{
"idempotencyKey": "'"$RUN"':part-2",
"source": { "operationId": "'"$LAST_OPERATION_ID"'" },
"steps": [ { "toolId": "protect-pdf", "parameters": { "password": "correct horse battery staple" } } ]
}'Use an earlier operation as the input
Any document operation can take another operation's output instead of a stored version. If that operation is still running, the new one is created in the waiting state and starts when its source completes; if the source fails, it fails with SOURCE_FAILED and its request unit is refunded. A source must belong to the same workspace and environment.
/api/v2/document-operations{
"source": {
"operationId": "op_7Kc…"
},
"toolId": "compress-pdf",
"parameters": {
"profile": "best"
},
"idempotencyKey": "invoice-0921-step-2"
}Multi-part outputs, fan-out and merge back
split-pdf, pdf-to-images and pdf-table-extraction produce several parts. GET /api/v2/document-operations/{operationId}/outputs lists them: index 0 is the whole output (the ZIP, for downloads) and 1 to N are the parts, at most 500. Any operation or chain step takes one part with source {operationId, output: n}; in a chain, {step: "<id>", output: n}. A part becomes its own stored document the first time it is used.
To run steps on every part, loop over the parts in your own code (fan-out) and pass the results to merge-pdf as inputs (fan-in).
// Split, then run your own steps on every part (fan-out), then merge them back (fan-in).
const split = await wf.tools.splitPdf("contract.pdf", { mode: "each" }, { idempotencyKey: `${run}:split` });
const { outputs } = await wf.documentOperations.outputs(split.operation.id); // index 0 is the ZIP, 1..N the parts
const stamped = [];
for (const part of outputs.filter((output) => output.index > 0)) {
// Each part is read where it is stored: the operation names the split and the part (source.output).
const { operation } = await wf.documentOperations.create(
{ toolId: "add-watermark", source: { operationId: split.operation.id, output: part.index }, parameters: { type: "text", text: `Page ${part.index}` } },
{ idempotencyKey: `${run}:stamp-${part.index}` },
);
const done = await wf.documentOperations.wait(operation.id);
stamped.push(done.outputs[0]);
}
const merged = await wf.tools.mergePdf(stamped, {}, { idempotencyKey: `${run}:merge` });
await merged.save("stamped.pdf");Idempotency, failure and resume
- Create every chain with a key you store before the call. Repeating the call after a timeout returns the same chain; nothing runs or is charged twice.
- A failing step stops the chain: the chain becomes failed,
failedStepnames the step,errorsays why, and every later step is cancelled and refunded. - Outputs of the steps that completed stay readable (intermediates for 1 hour, kept steps under your normal retention), so a partial result is never lost.
POST /api/v2/document-chains/{chainId}/resumere-runs the failed step and the steps after it with the same parameters; completed steps are not repeated.POST …/cancelstops waiting and queued steps; a running step finishes and its output stays readable.
# After a failure (for example credits ran out at the OCR step): fix the cause, then resume.
# Completed steps are not run again; the failed step and the ones after it get a new attempt.
curl -sS -X POST "$API/api/v2/document-chains/$CHAIN/resume" -H "$AUTH" -H "Content-Type: application/json" \
-H "Idempotency-Key: $RUN:resume-2" -d '{"idempotencyKey": "'"$RUN"':resume-2"}'
# Cancel instead: waiting and not-yet-started steps stop and their request units are refunded.
curl -sS -X POST "$API/api/v2/document-chains/$CHAIN/cancel" -H "$AUTH"Events: SSE and webhooks
GET /api/v2/document-chains/{chainId}/events streams the chain as Server-Sent Events until it ends. Webhook endpoints can subscribe to com.wellfriend.document-operation.completed.v2, com.wellfriend.document-operation.failed.v2 and com.wellfriend.document-operation.canceled.v2 for every operation, and com.wellfriend.document-chain.completed.v2, com.wellfriend.document-chain.failed.v2 and com.wellfriend.document-chain.canceled.v2 for chains. Deliveries are signed, retried and replayable like every other Wellfriend event.
# Follow a chain as it runs (Server-Sent Events). Each event "chain" carries the chain; the stream ends at a final state.
curl -N "$API/api/v2/document-chains/$CHAIN/events" -H "$AUTH" -H "Accept: text/event-stream"Your own logic between steps
Chains have no conditions or loops; your code decides. Run a step, check its result with your own rules or services, then choose the next step, naming the previous output so nothing is uploaded again.
- Keep your API key on your server. Browser code calls your own routes; your server calls Wellfriend.
- For conditions, schedules and approvals without your own server, use workflows (/docs/automations): branch nodes and
document-operations.createsteps run the same operations, and onedocument-chains.createnode runs a whole chain on the run input's document and version (or a configuredsource). It is charged one request unit per step and finishes when its last step finishes. - To embed a tool workspace in your own page with your own buttons and hooks, use the tool embed (/docs/developer-api/tool-embeds).
- Agents use the MCP tools
document_chain,document_chain_get,document_chain_cancelanddocument_processwithsource.operationId.
# Your logic between steps, on your server. Nothing is uploaded again: each call takes the previous result.
ocr = wf.tools.ocr_pdf(document_id, languages="en", output_mode="searchable-pdf", options={"idempotency_key": f"{run}:ocr"})
if needs_review(ocr): # your own rule: size, pages, your own service, a database lookup…
my_review_queue.put(ocr.outputs[0].version_id)
else:
wf.tools.compress_pdf(ocr, profile="best", options={"idempotency_key": f"{run}:compress"}).save("archive.pdf")// Continue when a signed webhook says an operation finished (no polling, no long-lived process).
import express from "express";
import { verifyWebhook, WebhookVerificationError } from "wellfriend-document-sdk";
const app = express();
app.post("/wellfriend/events", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = verifyWebhook(req.body, req.headers, process.env.WELLFRIEND_WEBHOOK_SECRET ?? "");
} catch (error) {
if (error instanceof WebhookVerificationError) return res.status(400).end();
throw error;
}
res.status(204).end(); // acknowledge first, then work
if (event.type === "com.wellfriend.document-operation.completed.v2") await saveToMyCase(event.data);
if (event.type === "com.wellfriend.document-operation.failed.v2") await alertMyTeam(event.data);
});// A button in your app calls your server; your server holds the key and starts the run.
app.post("/hooks/clean-up", express.raw({ type: "application/pdf", limit: "100mb" }), async (req, res) => {
const run = crypto.randomUUID();
const document = await wf.documents.upload({ data: req.body, filename: "upload.pdf" }, { idempotencyKey: `${run}:upload` });
const operation = await wf.tools.compressPdf(document, { profile: "best" }, { idempotencyKey: run, wait: false });
res.json({ operationId: operation.id }); // your page then reads your own status route, never Wellfriend directly
});Limits
| Limit | Value | What happens |
|---|---|---|
| Tools in one chain | No limit | Continue from the last step of the previous chain. |
| Steps per document-chains request | 25 | A request with more is refused with 400 CHAIN_INPUT_INVALID before any work or charge. |
| Steps the snippet builder builds | 10 | The builder only; the code on this page works with any number. |
| Parts of one multi-part output | 500 | Larger outputs stay downloadable as one ZIP. |
| Waiting operations per workspace | 1,000 | 429 TOO_MANY_PENDING with Retry-After. |
| Running steps and request rate | Your plan's concurrency and rate | Steps over your concurrency wait their turn; see /docs/developer-api/rate-limits. |
| Intermediate outputs | 1 hour | Set keep: true on a step to keep its output. |
How each step is charged
- Each step uses 1 request unit, exactly as one document operation does, whatever its page count. A chain reserves every step's units when it is accepted; if your plan cannot cover them all, the request is refused with 429
API_REQUEST_UNITS_EXHAUSTEDbefore any work. POST/api/v2/quoteanswers what a chain will cost before you send it (free, no key needed). - Steps that never run (after a failure, or when you cancel) are refunded. A completed step is not refunded.
- OCR (
ocr-pdf) steps also use credits from the same plan, for the pages they read: 5 credits for up to 15 pages, then 3.5 credits per additional page, rounded up per job. There is no separate OCR plan, allowance or pack. - Reading a chain, its events and its operations is free.
- The free plan, the Developer D1, D2 and D3 plans and Team seats cover every tool through the same request units and credits; see the Pricing page.
SDK methods
| Language | Run a chain | Read and wait | Cancel and resume | Use an earlier output |
|---|---|---|---|---|
| TypeScript | wf.pipeline(steps).run(input) | run() waits and returns the result; { wait: false } returns the run to wait on later | wf.workflowRuns.cancel, wf.workflowRuns.replay | pass an output's { documentId, versionId } as the input |
| Python | wf.pipeline(steps).run(input) | run() waits and returns the result; wait=False returns the run | wf.workflow_runs.cancel, wf.workflow_runs.replay | pass an output's document and version ids as the input |
| Go | wf.Pipeline(steps...).Run(ctx, input) | Run waits and returns the result | wf.WorkflowRuns.Cancel, wf.WorkflowRuns.Replay | wellfriend.DocumentVersion(documentID, versionID) as the input |
| Rust | wf.pipeline(steps).run(input) | run() waits and returns the result | wf.workflow_runs().cancel, wf.workflow_runs().replay | wellfriend::Input::version(document_id, version_id) as the input |
| CLI | wellfriend pipeline in.pdf --step … -o out.pdf | waits and saves the result | wellfriend api POST /workflow-runs/<runId>/cancel | pass a document id in place of a file |
| MCP | document_chain | document_chain_get | document_chain_cancel | document_process with source.operationId |
| REST | POST /api/v2/document-chains | GET /api/v2/document-chains/{id}, …/events | POST …/cancel, POST …/resume | source in POST /api/v2/document-operations; GET …/document-operations/{id}/outputs |