Introduction
Theextractions.create method in Retab’s document processing pipeline uses AI models to extract structured data from any document based on a provided JSON schema. This endpoint is ideal for automating data extraction tasks, such as pulling key information from invoices, forms, receipts, images, or scanned documents, for use in workflows like data entry automation, analytics, or integration with databases and applications.
The typical extraction workflow follows these steps:
- Schema Definition: Define a JSON schema that describes the structure of the data you want to extract.
- Extraction: Call
client.extractions.create(...)to process the document and retrieve structured data. - Validation & Usage: Validate the extracted data (optionally using likelihood scores) and integrate it into your application.
- Python parses
message.parsedagainst the JSON schema you pass in - Node accepts a JSON schema object, a schema file path, or a
zodschema directly
parse method that focuses on raw text extraction, extract provides:
- Structured Output: Data extracted directly into JSON format matching your schema.
- AI-Powered Inference: Handles complex layouts, handwritten text, and contextual understanding.
- Modality Support: Works with text, images, or native document formats.
- Consensus Mode: Optional multi-run consensus for higher accuracy on ambiguous documents.
- Likelihood Scores: Provides likelihood scores for each extracted field.
- Batch Processing Ready: Efficient for high-volume extraction tasks.
Extract API
An
Extraction record with the extracted data, usage details, consensus
likelihoods, and a persisted id.Build Your Schema
Retab extraction quality depends heavily on schema quality. The fastest way to improve a schema is to run extraction with consensus enabled, inspect unstable fields, and tighten the schema until the low-confidence areas disappear.Why consensus helps
Consensus is Retab’s practical schema debugging loop. Multiple extraction runs using the same schema reveal where the model disagrees. Those disagreements usually mean one of three things:- The field name is ambiguous
- The field description is too loose
- The field type or structure is asking the model to normalize too much at once
0.75 likelihood need attention before production use.
Schema improvement levers
Example: iterating on a schema
name: 1.0means the field is stabledate: 0.5usually means the format is underspecifiedaddress: 0.25usually means the field should be decomposed into structured subfields
- change
dateto an ISO date field - split
addressintostreet,city,zip_code, andcountry
- Start schema iteration with
n_consensus=4or5 - Fix the lowest-likelihood fields first
- Test with diverse documents, not one golden sample
- Treat consensus as a schema debugging tool, not just a scoring feature
Reasoning
Use reasoning when a field requires calculation, conversion, or multi-step logic. Retab supports this through theX-ReasoningPrompt JSON Schema annotation.
The model then produces an auxiliary reasoning___<field_name> output during extraction, which gives it room to work through the logic before returning the final field value.
Example: Celsius to Fahrenheit
22.5 directly. With reasoning enabled, it is more likely to compute 72.5 and explain the conversion in reasoning___temperature.
Use reasoning for:
- unit conversions
- tax or total calculations
- date normalization
- derived fields that depend on multiple source values
Sources
Retab can also return provenance for extraction results. Given an extraction ID,sources returns the same output structure, but every scalar leaf becomes a { value, source } object pointing back to the original document location.
This is useful for:
- review UIs with citations
- provenance audits
- highlighting extracted fields in viewers
- debugging incorrect outputs
Response shape
Every sourced leaf looks like this:pdf_bbox: normalized bounding box on a PDF pageimage_bbox: normalized bounding box on an imagecsv_cell: row and column reference in CSVspreadsheet_cell: sheet and cell reference in XLSXdocx_text_spanordocx_table_cell: DOCX paragraph or table-cell locationtext_span: line and character offsets in plain text
source to null.
Long documents: deep and agentic extraction
A default extraction reads the document in one pass. On long documents with very large arrays (statements, ledgers, invoices with hundreds of line items) one pass can miss rows. Two request fields trade latency for completeness:agentic_extraction implies deep_extraction: you do not need to set both.
What to expect from agentic_extraction:
-
Time. Runs take minutes. Send
background=trueand poll (example below). A spreadsheet or CSV runs synchronously only: send it withoutbackground, with a client timeout above 40 minutes (seedeep_extraction). - Pages. A page is a PDF or Word page, a PowerPoint slide, an image frame, a page of an email’s attachments, 500 non-empty cells of a spreadsheet or CSV, or 3,000 characters of a text file. Once the agent takes the request, HTML, MHTML, audio (its transcript) and emails without paged attachments are counted and billed like text files, one page per 3,000 characters, even if the request then falls back. A request the agent does not take counts each of them as one page, as in a standard extraction (see Fallback below). When the agent takes the request, a CSV that opens with title lines is counted from the row where its table starts; a standard extraction counts such a file as one page.
-
Credits. The same credits per page as
retab-largedeep extraction (see Pricing), whether the agent finishes or the request falls back. - Images and scans. Pages with no text layer (images, scanned PDFs, scanned pages in Word, PowerPoint or email attachments) are read with OCR.
-
Fallback. When agentic extraction does not apply, the request runs the
standard deep extraction instead, with the same response shape:
- documents under 15 pages, counted as above (a single image is one page, so it always falls back);
- schemas without a top-level list of objects;
- spreadsheets with pictures (photos, scans or barcodes) pasted into their cells;
- very long scans: currently more than 400 pages without a text layer (scans or images);
- a PDF over 48 MiB, including a Word or PowerPoint file once converted to PDF;
- a document read as text (a spreadsheet, CSV, text file, HTML, MHTML, audio transcript or email without paged attachments) with more than 3 MiB of text;
- when agentic extraction is not available, including when your organization already has too many agentic extractions running at once in the same region. No agent runs, and a document other than a spreadsheet or CSV is counted and billed exactly as a standard deep extraction: HTML, MHTML, audio and emails without paged attachments count one page each;
- when the agent cannot finish.
deep_extraction, and is billed as those windows are, at least one page per window, so it can cost more than the agent’s answer. The windows get the time the agent left: each minute the agent took removes one of the 40 windows. A sheet that no longer fits returns HTTP422and nothing is billed; send it withdeep_extractionalone, which has all 40 windows. When agentic extraction is not available, no agent runs and the windows keep all 40. After the agent was tried and handed the sheet back (it could not take the request, including when your organization already has too many agentic extractions running at once, or it did not finish), every window is billed, even when it is served from cache (withdeep_extractionalone a window served from cache is not billed). Where agentic extraction is not offered for your request, no agent is tried and the windows are billed as withdeep_extractionalone. -
Schema. Put the repeated rows in a top-level array of objects, for example
transactions: [{date, description, amount}].
json_schema or an n_consensus above 16
returns HTTP 422, and stream=true with background=true returns HTTP 400
stream and background cannot both be true. Then these checks run in this
order. The first one that fails returns HTTP 422 with a body
{"detail": "<message>"}, before any work starts and before anything is
billed:
A document type that extraction does not accept fails the same way with or
without
agentic_extraction.
Failures after the start. Once the agent has taken a synchronous request,
a request that runs out of time, loses its connection, or gets a server error
(5xx) or a rate limit (429) returns HTTP 422 instead, with the reason in
detail. When no answer came back at all, detail is
agentic extraction failed before it returned a result; it was not billed.
This holds whether the agent ran or the request fell back to the standard deep
extraction. Nothing is billed. The SDKs that retry on their own retry only a
429 or a 5xx (see SDK retries below), so no SDK sends this request
again: a retry would start a new agent run. To try again, send a new request:
each request is a new extraction. Other errors keep their usual status.
When the agent could not take the request at all, including when your
organization already has too many agentic extractions running at once in the
same region, a document other than a spreadsheet or CSV runs the standard deep
extraction instead, and its errors keep their usual status: no agent ran, so
an SDK may retry a 429 or a 5xx from it. A spreadsheet or CSV runs in its
50-row windows instead, and a server error or a rate limit from them returns
HTTP 422, as above. A request that reaches a server while it is shutting
down, before the agent started, returns HTTP 503 with
this API instance is shutting down; the agentic extraction did not start and was not billed, retry the request:
nothing ran, so an SDK may retry it.
With background=true, a run that times out (a 504 included) is run again
as the standard deep extraction, and is counted and billed as one. Other
server errors, rate limits, lost connections and unexpected errors are
retried. A run ends with status failed when a retry cannot help (a 4xx
such as 400 or 422), or when the retries run out.
Client timeouts. Use background=true where you can, except for
spreadsheets and CSV. A synchronous request can take up to about 30 minutes,
or about 40 minutes for a spreadsheet or CSV: set your client timeout above
that, for example one hour, as the examples below do except TypeScript. The
SDK defaults are too short and cut the request before it can finish: Python
and Go wait 30 minutes, PHP, Ruby and Rust 60 seconds, .NET 100 seconds. The
Node SDK sends requests with Node’s built-in fetch, which gives up after 5
minutes without response headers (headersTimeout). In Node, pass the client
a fetch that waits longer, with Agent from the undici package:
fetch: (input, init) => fetch(input, { ...init, dispatcher: new Agent({ headersTimeout: 3_600_000, bodyTimeout: 3_600_000 }) } as RequestInit).
The Java SDK sets no timeout and waits until the answer comes.
SDK retries. The Python SDK, and the PHP SDK from v0.1.9, retry a 429 or a 5xx
answer, up to 3 times by default, each after a random wait of up to 1, 2 and
then 4 seconds; they never retry a 422. The other SDKs do not retry.
A synchronous agentic request whose agent started answers those failures as
422 (see Failures after the start), so these SDKs never run the agent again
on their own. PHP SDK releases before v0.1.9 retry every error, 422 included,
at once without waiting, and each retry is a new extraction: with such a release,
create the client with maxRetries: 0, as the PHP example below does.
Run it in the background and poll
A long document can take several minutes. Start the request withbackground=true:
the API answers 202 right away with the extraction id and a queued status.
Then poll the cheap status-only view (include_output=false) until the status is
completed, failed or cancelled, and fetch the output once. See
Background mode for the full lifecycle. A
spreadsheet or CSV cannot run in the background: send it synchronously.
cURL
Managing Saved Extractions
Extractions are persisted resources. After callingclient.extractions.create(...), you can retrieve them later, list them with pagination, and filter them by metadata or date range.
Listing extractions
Useclient.extractions.list(...) when you need to browse recent extractions, paginate through large histories, or filter by metadata.
limit: page sizeorder:ascordescby creation datebeforeandafter: id paginationfrom_dateandto_date: date-range filtersmetadata: exact-match metadata filtering
Getting an extraction by ID
Filtering by metadata
Metadata is useful when you want to organize extractions by tenant, workflow, batch, or any other business key you attached at creation time.Use Case: Extracting Event Information from Documents
Extract structured calendar event data from a booking confirmation image and validate likelihood scores before saving to a database.Use Case: Passing Extra Instructions
Useinstructions to provide a freeform note that guides the extraction — useful for iteration context from a loop, tenant-specific conventions, or any hint that isn’t captured by the schema itself.
Metadata Filters
Usemetadata at extraction time to tag each document with stable identifiers, then filter those extractions later using the same keys.
This is especially important in multi-tenant systems: always include stable tenant-scoping metadata keys to avoid cross-tenant contamination.
1. Tag the extraction request with metadata
2. Filter extractions by metadata
Best Practices
Model Selection
retab-large: Use for complex documents requiring deep contextual understanding.retab-small: Balanced for accuracy and cost, recommended for most extraction tasks.retab-micro: Faster and cheaper for simple extractions or high-volume processing.
Schema Design
- Keep schemas concise: Only include required fields to improve extraction accuracy.
- Use descriptive
descriptionfields: Helps the AI model understand what to extract. - Add
X-SystemPromptfor custom guidance: E.g., “Focus on freight details” for domain-specific extractions.
Confidence Handling
- Set a threshold (e.g., 0.7) for automated processing.
- For critical tasks, enable
n_consensus > 1to average results and boost reliability.
Using Instructions
- Use
instructionsto pass domain-specific hints that aren’t part of the schema. - Ideal for: currency defaults, date format preferences, handling ambiguous abbreviations, or specifying regional conventions.
- Keep the string concise to avoid diluting the extraction focus.