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

# Extract Data

> Extract structured data from text using AI with a JSON schema

`ai.extract`, Extract structured data from text using AI with a JSON schema

Use `ai.extract` after parsing or collecting text when you need typed JSON back:
invoice fields, contract clauses, email metadata, line items, or classifications
with supporting fields.

Keep the schema as narrow as possible. Enum fields work well for closed choices,
and descriptions should explain business meaning, not just repeat the field
name. For deterministic calculations after extraction, pass the output into
`transform.script` instead of asking the model to do math.

The worker validates the returned JSON against this schema after every provider
call. Missing `required` fields, wrong types, and nested constraint failures
fail the step with a schema-validation error; they are never reclassified as
ordinary “not found” values.

Use `provider` to select an Eigenpal catalog entry such as
`anthropic/claude-sonnet-5-5`. The optional `model` field is only a raw
provider-specific override (for example a vendor model version) and must not
contain an Eigenpal catalog ID. Online validation reports this mix-up before
the workflow runs.

GPT-6.1 Terra is available as `openai/gpt-6.1-terra` for text and image extraction.
Select it explicitly with `provider`; its reasoning effort accepts `none`, `low`,
`medium` (the default), `high`, `xhigh`, and `max`. Workflow requests use the
Responses API. Existing default model selections remain unchanged.

```yaml theme={null}
- name: extract-invoice
  type: ai.extract
  with:
    input: '{{ steps.parse.output.text }}'
    provider: openai/gpt-6.1-terra
    schema:
      type: object
      properties:
        invoice_id: { type: string }
        total: { type: number }
      required: [invoice_id, total]
```

Published provider rates are $1 per million input tokens and $5 per million
output tokens, with $0.05 cache reads and $1.25 standard cache writes. Requests
over 272,000 input tokens cost twice the input/cache rates and 1.5 times the
output rate for the entire request. Agent sandbox sessions use a conservative
272,000-token context limit; workflows retain the model's larger context window.

## Grounding and confidence (on by default)

Grounding is on unless you set `grounded: false`. Step output stays
schema-shaped; provenance lives under a reserved `_grounding` map keyed by
**dotted field path** (array indexes are decimal segments), so nested values
and their grounding line up:

```yaml theme={null}
# {{ steps.extract-invoice.output.vendor }}                              -> "Acme Corp"
# {{ steps.extract-invoice.output._grounding.vendor.confidence }}        -> "high"
# {{ steps.extract-invoice.output._grounding.vendor.needsReview }}       -> false
# {{ steps.extract-invoice.output._grounding['line_items.0.amount'].score }} -> 0.92
```

Each entry carries categorical `confidence` (`high`, `medium`, `low`),
`needsReview`, optional numeric `score`, `reason`, `quote`, `source_span`, and
— when spatial evidence exists — `citations` with page/element references.
Lineage and the full parsed document graph are **never** mixed into step JSON;
they are stored as optional run sidecars for review and audit surfaces.

### OCR word confidence

When the extract input is a `ParsedDocument` whose OCR provider reports
per-word confidence (for example Mistral OCR), each field also carries
`recognitionScore`: how well OCR read the words the value was taken from. It
is the weakest cited word, pulled down slightly when the surrounding words in
the same region also scanned poorly. It never raises a field, only caps it:

* `score` is at most `recognitionScore`.
* Below `0.8` the field is `low`; below `0.9` it is at most `medium`. A
  handwritten name read at `0.53` is found verbatim in the OCR text, but it
  becomes `low`, carries `needsReview: true` and a reason, and human review
  with `metadataFrom: ai.extract` selects it.
* Other fields in the same paragraph keep their own band when their own words
  scanned cleanly.

Fields read from native PDF text, or from OCR providers without per-word
confidence, have no `recognitionScore` and keep the alignment-only result.

### Shared grounded extraction (parse → extract)

When `input` resolves to an object that includes a valid OpenParser
`ParsedDocument` in `structured` (for example the whole
`{{ steps.parse.output }}` from a layout-aware parse) **and** your configured
provider supports a single strict structured extraction call, Eigenpal runs the
same grounded extraction algorithm as OpenParser locally — no call to the hosted
OpenParser extract service. On-prem deployments use the same library in the
worker.

Wire the parse output object, not just `.text`, to unlock spatial citations and
sidecars:

```yaml theme={null}
- name: parse
  type: ai.parse
  with:
    input: '{{ input.document }}'
    parseMode: ocr
    ocrModel: openparser-default

- name: extract-invoice
  type: ai.extract
  with:
    input: '{{ steps.parse.output }}'
    schema:
      type: object
      properties:
        vendor:
          type: string
        total:
          type: number
      required: [vendor, total]
```

Passing only `{{ steps.parse.output.text }}` still works; extraction and
grounding fall back to the text path described below.

### Text grounding fallback

When there is no valid `ParsedDocument`, or the provider cannot run one strict
structured call, Eigenpal uses the legacy text grounding pass over the resolved
text. That path may set `_grounding._degraded: true` with a truthful `_reason`
(for example unsupported provider, missing grounding model, or credit quota too
low for the second pass). It does **not** emit lineage sidecars.

* `high` means the value appears verbatim in the source text, `medium` means it
  matches approximately or is derived from a highlighted passage the model
  attested, and `low` means no supporting source could be located.
* Fields at or below the `reviewOn` threshold carry `needsReview: true`. Default
  is `low_only`; use `medium_or_low` to also flag approximate matches.
* `source_span` holds character offsets into the resolved text; the run view
  highlights them in the Grounding panel. Long documents are chunked
  automatically on the text path.

The text pass uses your workspace default model unless `groundingModel` picks a
different one. Set `grounded: true` to fail the step when grounding cannot run
instead of degrading; `grounded: false` removes `_grounding` entirely.

Note that text grounding confidence measures whether the value is supported in
the source the step saw, not whether OCR read the original document correctly;
only the shared path above folds in OCR word confidence. For
numeric cross-checks (for example rate times hours equals gross), add a
`transform.script` step.

### Current limitations

* Spatial citations and lineage sidecars require **one** canonical
  `ParsedDocument` on the extract input. Multiple merged documents are not
  supported for bbox identity yet.
* Legacy text grounding never writes lineage sidecars — only `_grounding` in
  step output.
* Human review decisions are not yet appended back into lineage.

## Configuration

Configuration goes inside the step's `with:` block.

**input** `string` *required*

Text content or template expression

**schema** `object` *required*

JSON Schema defining the structure to extract. Fields not listed in `required` come back null when the document does not contain them; a missing required field fails the step.

**schema properties**

**type** `string` *required*

**properties** `record\<string, unknown\>` *required*

**required** `array\<string\>`

**prompt** `string`

Custom prompt template for extraction

**provider** `string`

Provider ID (e.g., "openai/gpt-6-luna")

**model** `string`

Model override

**reasoningEffort** `"none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"`

Reasoning effort for models that support it. Omit to use the selected model's default.

**maxInputTokens** `integer`

Max input tokens. Truncates input text and logs a warning when exceeded. Omit for no limit.

**grounded** `boolean`

Grounding is ON by default: each schema field gets a source span + confidence (high=verbatim, medium=fuzzy, low=ungrounded) under a reserved `_grounding` output key, and fields whose value cannot be located in the source are flagged for human review. Values stay the reliable schema-typed ones. The pass runs through the workspace LLM (any provider) and chunks long documents automatically. Tri-state: unset (default) = on, degrading gracefully to deterministic text alignment (`_grounding._degraded: true`) if no grounding model is available; `true` = strict, the step fails when the grounding model cannot be resolved; `false` = off, no `_grounding` key at all.

**groundingModel** `string`

Provider/model for the grounding pass. Defaults to the workspace default LLM. Any configured provider works; the pass only fails the step when `grounded: true` is set explicitly and no model resolves.

**groundingReasoningEffort** `"none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"`

Reasoning effort for models that support it. Omit to use the selected model's default.

**groundingExamples** `array\<object\>`

Optional few-shot examples pinning grounding to verbatim source text per field.

**groundingExamples properties**

**text** `string` *required*

**extractions** `array\<object\>` *required*

**extractions properties**

**field** `string` *required*

**text** `string` *required*

**reviewOn** `"medium_or_low" | "low_only"`

Which grounding confidences set needsReview on a field. Default: low\_only (only fields whose value could not be located in the source). Use medium\_or\_low to also flag approximate and derived matches.

## Output

Returns `record<string, unknown>`. Extracted structured data matching the provided schema. Unless grounding is disabled (grounded: false), the output also carries a reserved `_grounding` map keyed by dotted field path: `_grounding["line_items.0.amount"] = &#123; confidence: high|medium|low, score?, recognitionScore?, needsReview, reason?, quote?, citations?, source_span }`. When the parsed document carries per-word OCR confidence, `recognitionScore` is the recognition of the cited words and caps the field: `score` never exceeds it, below 0.8 the field is low, below 0.9 at most medium. The map also holds reserved `_degraded: true` / `_reason` markers when grounding could not run the shared algorithm or the EigenPal text pass. Lineage is never included in this JSON.


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