Skip to main content
@anyformat/sdk is the TypeScript client for API v3. The wire types and the low-level HTTP client come generated from the API’s OpenAPI document. The layer you use is hand-written, and mirrors the Python SDK method for method. It covers Anyformat, Schema, WorkflowBuilder, Workflow, Run and Result.

Install and auth

The SDK needs Node.js 18 or later. The package ships ESM and CJS bundles with types.
Pass the API key to the constructor. The client does not read the environment for you.
See Authentication for how to mint a key.

Client

new Anyformat(options) is the entry point. Every method returns a Promise.

Build a workflow

af.workflow(name, description?) returns a WorkflowBuilder. Chain one method per node, then await .create() to register the workflow and get a Workflow handle, or await .update(workflowId) to replace an existing workflow’s graph. .build() returns the request body without a network call. The builder assigns node ids (parse_1, extract_1, …) and wires the edges. Pass { id } in the options to choose the id yourself. Each method builds the same typed node the API accepts, so the node schema is the reference for every option. A builder mistake, such as extract() before parse(), throws WorkflowBuilderError before any request is sent. The builder has methods for Parse, Classify, Split, Extract, Validate, Edit, Report generator and Code. For a graph with an If/Else, Slack alert or Knowledge node, write the nodes and edges arrays yourself and send them with af.updateWorkflow(workflowId, definition), or call the create endpoint directly. The wire types (Edge, ClassifyCategory, SplitterRule, ValidationRule, the field and check types) are exported for that.

parse

Adds the one Parse node. Call it first and once. The options are a mode-discriminated union: each tier only accepts its own knobs, so a wrong-tier knob is a compile-time error.
lite takes no knob of its own.

input

Alpha. Adds the Input node in place of parse(): the workflow reads no document and takes its values from each run. Call it first and once. Only reportGenerator() may follow it.

classify

Adds a Classify node after Parse. Takes an array of ClassifyCategory objects (id, name, description).
Every extract() that follows needs { branch }.

split

Adds a Split node. Takes an array of SplitterRule objects (id, name, description, optional partition_key). After classify(), pass { routeFrom } to name the category that feeds the splitter.

extract

Adds an Extract node. Repeatable: one per branch. fields is an array built with Schema.
Schema has one factory per field type: string, integer, float, boolean, date, datetime, enum(name, description, options), multiSelect(name, description, options), and object(name, description, fields). Schema.option(name, description) builds an enum option. Every factory takes a trailing { source, persistentId }: source: "smart_lookup" or "lookup_if_missing" for a lookup field, persistentId to pin a field’s identity across updates.

validate

Adds a Validate node after the most recent extract(), or after the extract on { branch }. Takes an array of ValidationRule objects.

edit

Adds an Edit node after Parse. Call it once.

reportGenerator

Adds a Report generator node after the workflow’s single extract(), or after input(). Call it once. Pass a Markdown template for a model to fill, or the id of a Word template to fill as written, and not both. Each report written costs 25 credits.
af.uploadReportTemplate(workflowId, file) uploads the Word (.docx) document and resolves to its id and the placeholders it reads. af.getReportTemplate(workflowId, templateId) reads one back. Word templates are in alpha.

code

Beta. Adds a Code node after Parse. Call it once. It runs on the single extract’s fields, or on the parsed document when the workflow has no extract.

Run and read

Upload and run

workflow.run(files, opts?) uploads one File or an array of up to 10 as one document packet and starts a run. Every file needs a name so the server can detect its type: pass a File, not a bare Blob.
Filenames are unique within a workflow. A colliding name is rejected with 409; pass { onConflict: "rename" } to auto-rename instead. To upload without spending credits, use workflow.upload(files, opts?). It returns an Upload with documentPacketId and files; call upload.run() later. workflow.uploadFromUrls(urls, opts?) imports up to 10 HTTPS URLs server-side into one packet.
Retrying with the same idempotencyKey replays the original upload or run instead of creating and billing a second one.

Run on values

af.runWorkflow(workflowId, metadata, opts?) starts a run of a workflow that begins at an Input node. No file is sent: each field takes the value under its result key.
A value that is not what its field takes rejects with an ApiError whose errorCode is INPUT_VALUES_REFUSED; params.keys names each key and params.expected what it takes. opts.idempotencyKey and opts.workflowVersionId work as they do on workflow.run(...).

wait

run.wait({ timeoutMs, pollMs }) polls GET /v3/runs/{run_id}/ until the status is terminal and resolves with a Result. Defaults: 300 000 ms budget, 3 000 ms between polls. A transient 429 or 5xx while polling is retried with backoff and honours Retry-After. wait() rejects with ExtractionFailedError on error, ExtractionCancelledError on cancelled, and SDKTimeoutError when the budget runs out.

Result

ParseView has no draw(); rendering pages needs PDF rasterising, which only the Python SDK ships.

Quick parse

For a one-off parse with no workflow, af.parse(file) runs the atomic parse operation and returns a run id. af.getParseMarkdown(runId) returns the markdown once the run is processed, or null while it is still running. It throws ExtractionFailedError or ExtractionCancelledError if the run ends that way.

Document packets and runs

Packets and runs stay addressable after wait() resolves. A splitter workflow’s results carry an id on every split that addresses exactly one sub-document: split.id when the rule sets no partition key, and each partition.id when it does (the category’s own id is then null).
Packet statuses: not_started, queued, in_progress, then processed, error or cancelled. Run statuses are the same set without not_started.

Manage workflows

Deletion certificates

Zero-data-retention organizations only; any other gets a ForbiddenError with errorCode ZERO_DATA_RETENTION_REQUIRED. See Deletion Certificates.

Knowledge ask

The TypeScript client has no ask() method yet. Call Ask with fetch:

Evals and datasets

A dataset holds documents with known answers. Upload one document, with optional ground truth, as one packet:
groundTruth keys are the schema’s field identifiers. A scalar maps to string | null; an object field maps to an array of row objects. The call is atomic: a rejected file or a ground-truth failure stores nothing. Bulk upload loops one atomic call per document:
Both are also on the client: af.uploadToDataset(workflowId, files, opts) and af.uploadDocumentsToDataset(workflowId, documents). Read a dataset document’s ground truth, correct it, and write it back. The document is keyed by persistent_id, and a write replaces it whole:
af.getGroundTruth(documentPacketId, { version, nodeId }) reads the current version unless you pass one; nodeId is needed only when the version has more than one extract node. Its ground_truth is null until ground truth is first set. A production packet throws an APIError whose errorCode is NOT_IN_DATASET. See Set ground truth. Then launch an eval and poll it. Omit datasetTagIds and untagged to evaluate the whole dataset, or pick a slice by its dataset tags:
status ends processed, or error when at least one document’s extraction failed or was cancelled; either way the headline covers the documents that finished. af.listEvals(workflowId, { limit, cursor }) lists past evals. af.getEvalAccuracy(workflowId, evalId) breaks an eval down per field, per document and per dataset tag; counts are values, so each row of an object field counts once. Fields are named by persistent_id: read the names with af.getWorkflow(workflowId, { version: detail.version_id }). af.getEvalDocumentPacketFields(workflowId, evalId, documentPacketId) returns one document’s extracted values beside its ground truth; a field with no ground truth has expected: null and is ungraded, not wrong, so compare only the fields in failed_persistent_ids. To compare versions, read the evals you already ran with af.listEvals(workflowId): each carries its version_id and its tag selection, so compare evals launched on the same tags. To compare tags, read by_dataset_tag in af.getEvalAccuracy: one eval of the whole dataset counts every tag. af.iterWorkflowVersions(workflowId) pages every version, newest first.

Correct and verify results

Close the review loop from your own system: read a run, correct a field or a row, then verify. extractionId is the id of an entry of results.extractions. Name a field by its key in the results (sanitizedName) or by its persistentId, not both; a table cell also takes column (with sanitizedName) and rowIndex.
Each call resolves to undefined on 204. A call that names no field, or two, rejects with an AnyformatError before it sends anything. value: null empties a field. addRow and deleteRow are not idempotent: after a timeout, read the run before you retry. A document whose verifier is another user throws an APIError whose errorCode is NOT_ASSIGNED_VERIFIER. See Edit field and Verify extraction.

Webhooks

Subscribe an HTTPS endpoint to run events instead of polling. Only an admin or owner of the organization manages its webhooks; a lower role throws ForbiddenError.
The events (WebhookEvent) are run.completed, run.failed, run.cancelled and run.validated. Verify each delivery’s webhook-signature with the secret, as the webhooks overview describes.

Pagination

Every list resolves to a Page<T> with items and nextCursor. Pass nextCursor back as cursor until it is null. There are no totals or page numbers; limit is capped at 100.
The iter* methods (iterWorkflows, iterDocumentPackets, iterRuns) do this loop for you and fetch each page lazily.

Errors and retries

Every HTTP failure rejects with a subclass of APIError carrying the v3 error envelope: .status, .errorCode, .retryable, .requestId, .recovery and the raw .body. .recovery is the sentence the errors reference prints under How to recover, and is undefined when the API sends none. Outside HTTP, all subclasses of AnyformatError: RunFailedError when wait() sees a terminal failure, subclassed as ExtractionFailedError (error) and ExtractionCancelledError (cancelled), each with .runId and .status; SDKTimeoutError when wait() runs out of budget; WorkflowBuilderError for builder misuse.
wait() retries a transient 429 or 5xx itself, so those never reach your catch while polling.

Version pins

Upgrading from 0.x changes uploads, runs, pagination and workflow updates. Follow the 0.x to 1.0 migration guide.