Skip to main content

Introduction

The extractions.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:
  1. Schema Definition: Define a JSON schema that describes the structure of the data you want to extract.
  2. Extraction: Call client.extractions.create(...) to process the document and retrieve structured data.
  3. Validation & Usage: Validate the extracted data (optionally using likelihood scores) and integrate it into your application.
The SDKs already help here:
  • Python parses message.parsed against the JSON schema you pass in
  • Node accepts a JSON schema object, a schema file path, or a zod schema directly
You can still add your own application-level validation if you want stricter business rules. Unlike the 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

ExtractionRequest
Extraction
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
As a rule of thumb, fields below 0.75 likelihood need attention before production use.

Schema improvement levers

Example: iterating on a schema

Example interpretation:
  • name: 1.0 means the field is stable
  • date: 0.5 usually means the format is underspecified
  • address: 0.25 usually means the field should be decomposed into structured subfields
Common next step:
  • change date to an ISO date field
  • split address into street, city, zip_code, and country
Best practices:
  • Start schema iteration with n_consensus=4 or 5
  • 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 the X-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

Without reasoning, a model may copy 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:
Common anchor types:
  • pdf_bbox: normalized bounding box on a PDF page
  • image_bbox: normalized bounding box on an image
  • csv_cell: row and column reference in CSV
  • spreadsheet_cell: sheet and cell reference in XLSX
  • docx_text_span or docx_table_cell: DOCX paragraph or table-cell location
  • text_span: line and character offsets in plain text
If a field cannot be sourced, Retab still returns the value and sets 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=true and poll (example below). A spreadsheet or CSV runs synchronously only: send it without background, with a client timeout above 40 minutes (see deep_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-large deep 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.
    A spreadsheet or CSV that falls back runs in the same 50-row windows as 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 HTTP 422 and nothing is billed; send it with deep_extraction alone, 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 (with deep_extraction alone 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 with deep_extraction alone.
  • Schema. Put the repeated rows in a top-level array of objects, for example transactions: [{date, description, amount}].
Validation errors. The checks every extraction runs come first, with their own messages: for example an empty 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 with background=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 calling client.extractions.create(...), you can retrieve them later, list them with pagination, and filter them by metadata or date range.

Listing extractions

Use client.extractions.list(...) when you need to browse recent extractions, paginate through large histories, or filter by metadata.
Useful list filters:
  • limit: page size
  • order: asc or desc by creation date
  • before and after: id pagination
  • from_date and to_date: date-range filters
  • metadata: 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.
For full request and response details, see the extraction endpoints in the API Reference.

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

Use instructions 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

Use metadata 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

When multiple metadata keys are provided, all keys are applied together as exact-match filters.

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 description fields: Helps the AI model understand what to extract.
  • Add X-SystemPrompt for 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 > 1 to average results and boost reliability.

Using Instructions

  • Use instructions to 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.