Skip to main content
The anyformat package is the Python client for API v3. It is hand-written on httpx. You build a workflow with a fluent builder, run a file through it, and read typed results. The TypeScript SDK mirrors it method for method. Two import paths: anyformat.sdk holds the client, the handles and the errors; anyformat.workflow holds the schema factories and the node types.

Install and auth

Requires Python 3.10 or later.
Pass the API key to the client. The client does not read the environment for you.
See Authentication for how to mint a key. The package also installs the afx command, which does read ANYFORMAT_API_KEY.

Client

Client is synchronous. AsyncClient has the same methods with await. Both take the same arguments. Both clients are context managers that close the connection pool. Prefer that over a bare module-level client.
In the async client, create(), update(), run(), upload(), wait() and every client method are awaitable. The builder verbs (parse, extract, and so on) are not.

Build a workflow

client.workflow(name, description=None) returns a builder. Chain one verb per node, then .create() to register the workflow and get a Workflow handle, or .update(workflow_id) to replace an existing workflow’s graph. .build() returns the typed WorkflowDefinition without a network call. The builder assigns node ids (parse_1, extract_1, …) and wires the edges for you. Pass id= to any verb to choose the id yourself. Each verb constructs the same typed node the API accepts, so the node schema is the reference for every argument. A builder mistake, such as extract() before parse(), raises WorkflowBuilderError before any request is sent. The builder has verbs for Parse, Input, Classify, Split, Extract, Validate, Edit, Report generator and Code. For a graph with an If/Else, Slack alert or Knowledge node, build a WorkflowDefinition from the node classes in anyformat.workflow.nodes and pass it to client.create_workflow(definition).

parse

Adds the one Parse node. Call it first and once. mode selects the tier, and the type checker only offers the knobs that belong to that tier.
lite takes no knob of its own. All arguments are keyword-only.

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 report_generator() may follow it.

classify

Adds a Classify node after Parse. Takes one or more ClassifyCategory objects.
Every extract() that follows needs branch=.

split

Adds a Split node. Takes one or more SplitterRule objects. After classify(), pass route_from= to name the category that feeds the splitter.

extract

Adds an Extract node. Repeatable: one per branch. fields is a list built with Schema.
Schema has one factory per field type: string, integer, float, boolean, date, datetime, enum(name, description, options=[Schema.option(...)]), multi_select, and object(name, description, fields=[...]). Every factory accepts source="smart_lookup" or source="lookup_if_missing", and persistent_id= 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 one or more ValidationRule objects.

edit

Adds an Edit node after Parse. Call it once.
upload_edit_references(workflow_id, files) uploads the standing data an Edit node fills from (.csv, .txt, .md, .rst, .pdf). A PDF comes back pending while it is parsed once; poll list_edit_references(workflow_id) until ready. delete_edit_reference(workflow_id, document_id) removes one. The builder does not set font or output_mode; set those in the API JSON.

report_generator

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.
upload_report_template(workflow_id, file) uploads the Word (.docx) document and returns a ReportTemplate with its id and the placeholders it reads. get_report_template(workflow_id, template_id) 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(...) uploads the document as one document packet and starts a run. It accepts a path string, a Path, raw bytes, a list of up to 100 files via files=, or text=. Exactly one of the three.
Filenames are unique within a workflow. A colliding name is rejected with 409; pass on_conflict="rename" to auto-rename instead. A run uses the workflow’s latest version. Pass workflow_version_id= (a version_id from the workflow’s versions list) to run on a chosen version. An unknown version raises a 404 before anything is uploaded.
To upload without spending credits, use workflow.upload(...). It returns an Upload with document_packet_id and files; call upload.run() later.
Retrying with the same idempotency_key replays the original upload or run instead of creating and billing a second one.

Run on values

client.run_workflow(workflow_id, metadata) 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 raises an APIError with error_code INPUT_VALUES_REFUSED; params["keys"] names each key and params["expected"] what it takes. idempotency_key= and workflow_version_id= work as they do on workflow.run(...).

wait

run.wait(timeout=300, poll_interval=3) polls GET /v3/runs/{run_id}/ until the status is terminal and returns a Result. A transient 429 or 5xx while polling is retried with backoff and honours Retry-After. wait() raises ExtractionFailed on error, ExtractionCancelled on cancelled, and SDKTimeout when the budget runs out.

Result

result.parse.draw("out/") renders every block’s bounding box onto its page, coloured by confidence, and writes one PNG per page. It uses the file you ran as the background; pass source= to use another.

Quick parse

For a one-off parse with no workflow, client.parse(file) runs the atomic parse operation and returns a Run. Poll client.get_markdown(run.id) until it stops raising StillParsing. It raises ExtractionFailed or ExtractionCancelled if the parse run ends that way.

Document packets and runs

Packets and runs stay addressable after wait() returns. Run statuses: queued, in_progress, then processed, error or cancelled.

Download a sub-document

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

Manage workflows

Deletion certificates

Zero-data-retention organizations only; any other gets Forbidden with error_code ZERO_DATA_RETENTION_REQUIRED. See Deletion Certificates.

Knowledge ask

A workflow with a Knowledge node answers questions about what its documents say. workflow.ask(question) and client.ask(workflow_id, question) call Ask and return an Answer.
Answer has .answer, .citations (each with path, quote, file_id, block_id, page, bbox), .steps_used and .thread_id. Pass thread_id="kb-..." to ask a follow-up in the context of earlier questions on that thread. A workflow without a Knowledge node raises APIError with error_code KNOWLEDGE_NOT_ENABLED.

Evals and datasets

A dataset holds documents with known answers. Upload one document, with optional ground truth, as one packet:
ground_truth keys are the schema’s field identifiers. A scalar maps to str | None; an object field maps to a list of row dicts. The call is atomic: a rejected file or a ground-truth failure stores nothing. Bulk upload loops one atomic call per document:
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:
get_ground_truth(document_packet_id, *, version=None, node_id=None) reads the current version unless you pass one; node_id is needed only when the version has more than one extract node. Its ground_truth is None until ground truth is first set. A production packet raises an APIError whose error_code is NOT_IN_DATASET. See Set ground truth. Then launch an eval and poll it. Omit dataset_tag_ids 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. launch_eval(workflow_id, *, version_id=None, idempotency_key=None, dataset_tag_ids=None, untagged=False) evaluates the current version unless you pass one. list_evals(workflow_id, limit, cursor) and iter_evals(workflow_id) list past evals. See Launch eval. get_eval_accuracy 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, so read the names from the evaluated version’s graph, then fetch the values one document got wrong:
A field with no ground truth is ungraded, not wrong: its expected is None, so compare only the fields in failed_persistent_ids. To compare versions, read the evals you already ran: each carries its version_id and its tag selection. Compare evals launched on the same tags:
To compare tags, read by_dataset_tag in get_eval_accuracy: one eval of the whole dataset counts every tag. iter_workflow_versions(workflow_id) 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. extraction_id is the id of an entry of results.extractions. Name a field by its key in the results (sanitized_name) or by its persistent_id, not both; a table cell also takes column (with sanitized_name) and row_index.
Each call returns None on 204. A call that names no field, or two, raises ValueError before it sends anything. value=None empties a field. add_row and delete_row are not idempotent: after a timeout, read the run before you retry. A document whose verifier is another user raises an APIError whose error_code 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 raises Forbidden.
The events are run.completed, run.failed, run.cancelled and run.validated. Verify each delivery’s webhook-signature with the secret, as the webhooks overview describes. AsyncClient has the same four methods.

Pagination

Every list returns a Page(items, next_cursor). Pass next_cursor back as cursor= until it is None. There are no totals or page numbers; limit is capped at 100.
The iter_* methods (iter_workflows, iter_document_packets, iter_runs, iter_evals) do this loop for you and fetch each page lazily.

Errors and retries

Every HTTP failure raises a subclass of APIError carrying the v3 error envelope: .status_code, .error_code, .detail, .retryable, .request_id and .recovery. .recovery is the sentence the errors reference prints under How to recover, and is None when the API sends none. .detail keeps the shape the API sent: a string for most errors, or a list of {type, loc, msg} field errors for a validation failure, such as a 422 GT_INVALID naming each ground-truth key that failed. Four more exceptions live outside HTTP. wait() raises RunFailed on a terminal failure, as ExtractionFailed for error and ExtractionCancelled for cancelled. Both carry .run_id and .status. wait() raises SDKTimeout when it runs out of budget, and MissingResults when a processed run carries no results. StillParsing means a quick parse is not done. WorkflowBuilderError means builder misuse.
wait() retries a transient 429 or 5xx itself, so those never reach your except while polling.

Version pins

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