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

# Extract fields from documents

> Extract typed fields from files or text through a document reader slot, a model or your own target, then correct and review them.

The extraction library, `@bijectionhq/library-extraction`, extracts typed
fields from your app's documents. An `extraction({...})` instance is a
subtree: its tables (`tables.runs`, `tables.revisions`), continuations and
`runs` functions take their paths where you place it.

```ts bijection/invoices.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, mutation, role, t } from "@bijectionhq/bijection";
import { definition, extraction, layoutMethod } from "@bijectionhq/library-extraction";
import type { LanguageModel, Models } from "@bijectionhq/library-models";

// The pack for this instance is cleared for `invoices`.
declare const ai: Models<{ reader: LanguageModel }>;

export const invoices = label();
export const clerk = role({ clear: [invoices] });

export const invoice = definition({
  name: "invoice",
  revision: "1",
  fields: { vendor: t.string, total: t.number, currency: t.maybe(t.string) },
  instructions: "Extract the vendor, the total amount and its ISO currency code.",
});

export const ap = extraction({
  label: invoices,
  operators: [clerk],
  definitions: { invoice },
  // The instance's document reader: a document-analysis@1 slot at ap.reader.
  reader: { engine: "aws-textract" },
  method: layoutMethod(ai, "reader"),
});

export const intake = mutation(
  { under: invoices, allow: [clerk], args: { file: t.file, source: t.string } },
  async (ctx, { file, source }) => await ap.start(ctx, { definition: "invoice", source, file, text: null }),
);

// app({ invoices, clerk, ap, intake, ... })
```

A run reads its document (a `t.file`, or text) under the instance's label,
and its result, issues and every revision are stored there: a result is
readable exactly where its document is. The method's receiver must be
cleared for the label. One instance holds one label.

## Definitions and methods

* `definition({ name, revision, fields, instructions, questions? })`
  declares the fields as value types; a `t.maybe` field may be absent.
  `questions` gives `queriesMethod` a question per field. Its `digest`
  covers the declaration.
* `layoutMethod(ai, key)` reads the document's layout, tables and form
  fields through the instance's reader, stores the analysis as a File at
  the label (`tables.layouts`, reused by later attempts over the same
  document), then asks a catalog language model with the `structured`
  capability over the layout as text. It suits scans, photos and long PDFs.
* `queriesMethod()` asks the reader one question per field and keeps the
  most confident answers, read as each field's type. No model is asked.
* `modelMethod(ai, key)` uses a catalog language model with the
  `structured` capability, plus `documents` or `images` for files, sending
  the file inline (at most 10 MiB).
* `method({ name, to, args, decode, file? })` uses any target. The `args`
  callback builds the target arguments, and `decode` reads the answer into
  field values. With `file: "reference"`, the callback receives the File at
  `document.ref` without reading its bytes.

## The document reader

`reader: { engine }` places a `document-analysis@1` slot at
`<instance>.reader`, at the instance's label. The protocol is
engine-neutral: `analyze` takes the File by reference and answers the whole
document normalized (pages, lines, words, layout blocks, tables, form
fields, query answers, page-relative boxes), metered in pages. The engine is
code: it is on the slot's line in `bijection.lock`, and deploy refuses a
provider that does not serve it. Who runs it is
[placement](https://docs.bijection.com/operate/placement.md), in the installation's bindings file:

| Binding | What runs |
| - | - |
| none (managed) | `aws-textract` on Bijection's cell account in its region, priced per page by feature. A single page can be analysed inline. For a staged document, a successful answer requires deletion of the staged input. The staging bucket has a one-day lifecycle rule. AWS keeps the asynchronous result for up to seven days. |
| `placement.managed({ account: placement.aws.account({ account, region, staging }) })` | The same engine and driver on your AWS account and bill. Use it for Textract adapters. |
| `placement.endpoint({ url, hosts, credential })` | Any server that speaks the protocol, such as the compute pack's Python reference provider (`tesseract-5`, `pdf-text`, `docling-2`). |

For `placement.aws.account`, set `staging.bucket` to the name of a dedicated S3
bucket with no versioning history. Grant the role `s3:GetBucketVersioning`
on that bucket.
The host gives a send at most ten seconds for processing and cleanup.
Asynchronous analyses that exceed that window can leave the call with an
unknown outcome.

Document labels can require evidence for the provider's region, tenancy,
custody, or retention. Both managed and explicit bindings meet the same
requirements. A standalone reader for other uses is
`documentReader({ label, engine })`.

Every answer is checked field by field. Conforming values are kept; a
missing or non-conforming field becomes an issue `{ field, problem }`. A
method never writes a value its definition refuses.

| Function | What it does |
| - | - |
| `start(ctx, { definition, source, file, text })`, `runs.start` | Store the run and submit its first attempt. One of `file` and `text` is null. |
| `retry(ctx, run)`, `runs.retry` | Start a failed run's next attempt. |
| `correct(ctx, { run, revision, values, note })`, `runs.correct` | Set or clear fields of the current revision, as a new revision. |
| `runs.get`, `runs.list`, `runs.history` | A run, a source's runs, a run's revisions. |

Operators start, retry and correct; readers (the operators by default)
read.

## Review

With `review`, every revision asks the Approvals app with the run's subject,
the revision's digest and a requirement. The decision is recorded on the
run when it is for the current revision and its digest matches:
`approved`, `rejected`, or `void` (`Withdrawn`, `Expired` or any refusal).
A correction asks again.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { release } from "@bijectionhq/bijection";
import { ask } from "@bijectionhq/app-approvals";
// approvals: the installed Approvals app, app({ approvals: approvals({ classes }) })

export const reviewRef = release({ from: invoices, to: label.public, message: "Ask Approvals by reference and digest" });

extraction({
  label: invoices,
  // ...
  review: {
    ask: (ctx, request, options) => ask(ctx, approvals, request, options),
    requirement: { seats: [{ class: "finance", k: 1 }], veto: null, exclude: [] },
    release: reviewRef,
  },
});
```

A protected instance lowers only the subject and digest, through
`review.release`. The functions that ask declare that release.


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