Open-source Python library · MIT · v0.5.1

Fields from documents.Nothing dropped silently.

Give Extractfold a document and a JSON Schema, get back a Python dict checked against that schema. When a model's answer is cut off, rows go missing or a value breaks the schema, the result says so. You see it before the data reaches your books, your CRM or your customer.

result
result.valid            # False
result.data["rows"]       # 412 rows
chunking = result.metadata["chunking"]
chunking["partial"]       # True
chunking["truncated_chunk_indexes"]  # [7]
# chunk 7 stayed cut at the token limit after
# two re-reads: rows may be missing there
Schema in, checked dict outEvery result is validated against your JSON Schema. Numbers and booleans that come back as strings are converted, and a result that still does not fit has valid set to False.
Missing rows are reportedLong documents are split into chunks. A chunk cut at the token limit is extracted again in halves. What still cannot be recovered marks the result as partial.
Your keys, your machineNo hosted service and no data of its own. You call the providers with your own keys, and you can parse a PDF locally and send only its text.

Works with the models and document services you already use

Who it is for

For code that turns documents into rows someone relies on.

Extractfold runs inside your own product or pipeline. It fits when invoices, statements, contracts or forms become records that someone pays, reconciles or signs off on, and a missing line costs more than a second look.

Invoices into accounting

Invoice number, vendor, dates, totals and line items land in your ledger. A total that fails the schema or a line that never came back should stop the import, not slip through.

Long statements and tables

A bank statement or price list runs to hundreds of rows. Extractfold splits it, checks the row count against the document and tells you which part may be incomplete.

Contracts and forms

Parties, dates, amounts and clauses go into fields you define. Each field can point back to the cell, block or page it was read from.

Choosing an engine

Run several engines on your own documents and score them on field accuracy and invented values before you commit to one vendor.

Engines

11 engines. One interface.

Every engine takes the same document and schema and returns the same result object, so switching vendors is one line. You hold the API keys and pay each provider directly. LLM engines have no default model: you always name the model, so a result never changes because a default did.

LLM structured outputs

Schema-guided extraction with a model you choose.

  • Anthropicllm_structured
  • OpenAIllm_structured
  • Geminillm_structured
  • InstructorPydantic models
  • fenicdataframe pipelines

Your own gateway

Plug in the model client your app already has.

  • provider_routerordered fallback across models, JSON repair, your retries and telemetry

Document AI clouds

OCR, forms and query fields with confidence and location.

  • Azure Document Intelligence
  • Google Document AI
  • AWS Textract

Extraction services

Hosted schema extraction.

  • Datalab Liftwith confidence and provenance
  • LlamaExtract

Open model on your hardware

No document leaves the machine.

  • NuExtractHugging Face or vLLM

Parse first

Clean text before the model reads it.

  • docfoldPDF, scans and Office files to Markdown

How it works

A model's answer is a draft, not a record.

The usual script sends a document to a model, asks for JSON and trusts what comes back. On a long statement the answer stops at the token limit, the last rows vanish, and the JSON still parses. Extractfold puts these checks between the model and your database.

Checked against your schema

Required fields, types and nested arrays are validated on every result. Values that arrive as strings are converted when the schema asks for numbers or booleans.

Cut-off answers are caught

A chunk whose answer hit the token limit is split at a line break and read again, up to two levels. If it is still cut off, the result lists that chunk and is marked partial.

Row counts are compared

An optional pre-scan reads the head and tail of the document once and finds totals and row counts. Each chunk's rows are checked against them, and a short chunk can be re-run.

Values point back to the source

Build a catalog of the document's cells, blocks or paragraphs. The model cites entries per field, and Extractfold resolves them to page, cell or block and scores how well the value matches.

Engines are scored on your files

Compare engines on the same document from the CLI, or benchmark a folder against gold answers: field accuracy, schema compliance, precision and recall, and the rate of invented values.

Broken JSON is repaired, not guessed

With repair_json=True an answer that does not parse is repaired when it can be. With several models in the router, a failed answer moves to the next model instead of failing the run.

Your files

Decide what leaves your machine.

Extractfold itself has no server and stores nothing. What reaches a provider depends on the engine you choose. To keep a PDF on your machine, parse it locally with docfold and send only the text. You can read that text before it goes anywhere.

  • LLM engines receive only the text you pass in.
  • Document AI clouds and extraction services receive the file itself, under their own terms.
  • NuExtract runs on your own hardware, and nothing leaves the machine.
invoice.py
import asyncio
from docfold.engines.pymupdf_engine import PyMuPDFEngine
from extractfold.engines import LLMStructuredEngine

schema = {
    "type": "object",
    "required": ["invoice_id", "total"],
    "properties": {
        "invoice_id": {"type": "string"},
        "vendor": {"type": "string"},
        "total": {"type": "number"},
    },
}

async def main():
    # parsed on your machine: only this text goes to the model
    text = (await PyMuPDFEngine().process("invoice.pdf")).content
    engine = LLMStructuredEngine(model="claude-haiku-5-5")
    result = await engine.extract_text(text, schema)
    print(result.valid, result.data)

asyncio.run(main())

Long documents

Know which rows you did not get.

extract_rows_chunked plans chunks by format (spreadsheet, csv, JSON, HTML or Markdown), extracts them in order or in parallel, drops duplicates and keeps rows in document order. Each chunk reports its checks, and the result tells you which chunks were cut off, failed or came back short.

A JSON array that already matches your schema is returned as is, without a model call.

statement.py
from extractfold import extract_rows_chunked, prescan

scan = await prescan(text, llm=my_llm)   # totals, row counts
result = await extract_rows_chunked(
    text, row_schema,
    engine=engine,
    input_format="csv",
    prescan=scan,
    rerun_below=0.8,   # re-read a chunk that comes back short
)

chunking = result.metadata["chunking"]
if not result.valid:
    print(chunking["truncated_chunk_indexes"])

Get started

Extract your first invoice in a few minutes.

Install Extractfold with the LLM extra and docfold's PDF parser, set the API key of the model provider you use, and run the example above on one of your own invoices. Extractfold has no data of its own and no hosted service. Approving results and writing them to your systems stays in your application.

terminal
pip install "extractfold[llm_structured]" "docfold[pymupdf]"
export ANTHROPIC_API_KEY=...
python invoice.py