2027 planning guide · Evidence checked 20 November 2026

Document AI API for developers: parsing, chunking, OCR, tables and citations

A document AI API is the ingestion half of a RAG system: it turns PDFs, scans and forms into text, tables and coordinates that a model can cite. The hard parts are reading order, table structure, chunk boundaries and evaluation, not the chat call. This page is the build guide, with the failure modes that decide whether the answer is trustworthy.

Short answer. Parse first, then chunk, then embed, then answer with citations. Separate native text from scanned pages, keep layout and page coordinates, treat tables as structured objects rather than flattened text, and verify every citation against the parsed source before showing it. Evaluate field accuracy, table cells, retrieval recall, citation precision and abstention on your own labelled documents. No accuracy percentage is quoted here because no dated benchmark represents your corpus.

Document AI is a pipeline, not a model

A document AI API usually means one of two things: a model that accepts a page image and returns structured text, or an end-to-end service that also handles ingestion, chunking and retrieval. The distinction matters at procurement time. A model call is easy to swap; a pipeline owns your parsing rules, chunk IDs, index and citation format, and those are the parts that are expensive to rebuild.

The pipeline has eight stages, and each one can fail independently. A good answer requires all of them to be right: the page must be classified, the text must be extracted or recognised, the reading order must be recovered, the table must keep its structure, the chunk must contain the evidence, the index must be current, the model must use the evidence, and the citation must resolve. Optimising only the model leaves seven failure surfaces untouched.

The document AI pipeline, the artefact each stage produces and the failure it prevents
StageArtefactWhat can go wrongControl
ClassifyPage type: native, scan, form, table-heavyOCR applied to a clean text pagePer-page decision, not per-file
ParseText runs, fonts, positionsLost reading order in columnsLayout model plus a reading-order check
OCRCharacters, words, confidenceConfident nonsense on a poor scanConfidence thresholds and a second pass
TablesGrid, headers, merged cells, unitsColumns flattened into a sentenceTable object with coordinates
ChunkClause or section with heading pathEvidence split across two chunksLayout-aware boundaries and parent expansion
EmbedVector plus source metadataSame text, different revisionVersioned IDs and re-index on change
AnswerGrounded response with citationsUnsupported claimCitation verification and abstention
EvaluateLabelled scores by stageDemo passes, production failsHoldout set and regression gate

Parsing: start with the text layer, not the model

A PDF is a container, not a text format. The PDF 1.7 specification defines pages, content streams, fonts and image objects, and a page may carry real text, an image of text, or both. A scanned contract has no text layer; a born-digital report usually does. Extracting the text layer first is cheaper and preserves characters that OCR might misread, but it is not always sufficient: some exports have broken encoding, missing spaces or text runs in an order that does not match the visual layout.

Classify every page and record why. A practical rule set is: extract the text layer, measure characters per page and the ratio of printable characters, compare the extracted word count with an OCR sample on the same page, and flag pages that fall below the threshold. Route only flagged pages to OCR. Keep the original text layer alongside the OCR output so a reviewer can see what changed.

Reading order is the next trap. A two-column academic paper, a three-column annual report and a form with labels on the left all break naive top-to-bottom extraction. Use a layout model that returns blocks with bounding boxes, then order blocks by column and section before joining them. Store the block coordinates; the citation step will need them.

OCR: confidence is not correctness

OCR is necessary for scans, faxes, screenshots and photos, and it is a stage that can produce fluent errors. Tesseract, the long-running open-source OCR engine, returns recognised text with per-word confidence values. Those values describe the engine's certainty about its own output, not the probability that the word is correct in the document. A smudged date can be read confidently and wrongly.

Three controls reduce the damage. First, send low-confidence words to a second engine or a vision model and compare; disagreement is a signal to route the page to a human. Second, validate fields with cheap domain rules: a date must parse, a currency amount must have a plausible magnitude, an invoice total must equal the sum of its lines. Third, keep the page image and the bounding box so a reviewer can check the source in one click.

Language and script change the error profile. Arabic documents need a recogniser that handles right-to-left text, diacritics and mixed Latin numerals; a model trained mostly on English invoices can misread both the script and the number format. Test on documents from each market rather than assuming one engine covers all of them.

Chunking: the boundary decides what can be found

Chunking is a retrieval decision disguised as a preprocessing step. If the evidence spans a chunk boundary, the retriever cannot return it, and the model cannot cite it. Fixed-size chunking is easy to implement and easy to evaluate, but it cuts clauses, splits tables and separates a heading from its content. Layout-aware chunking is harder and usually better for contracts, policies and manuals.

Chunking strategies for document AI, their strengths and the failure each one invites
StrategyBoundaryStrengthFailureBest fit
Fixed token windowEvery N tokens with overlapSimple, predictable costCuts clauses and tablesUniform prose, early prototype
Recursive separatorsParagraph, then sentenceKeeps paragraphs intactIgnores page layoutArticles, support macros
Layout-awareHeading and block structurePreserves sections and reading orderNeeds a layout parserContracts, policies, manuals
Parent-childSmall child, larger parentPrecise retrieval, enough contextMore index storageLong technical documents
SemanticTopic shift between sentencesFollows meaningUnstable boundaries, hard to auditNarrative reports
Table as one unitWhole table plus captionKeeps headers and unitsLarge chunks, coarse retrievalFinancial and spec tables

For a 200-page contract, chunk by clause and keep the heading path (“Schedule 3 → 3.2 → 3.2.1”) on every chunk. Store the page number, the clause ID and the bounding box. Add a parent chunk so a retrieved sentence can expand to the surrounding clause without re-parsing. Overlap is a patch for bad boundaries, not a substitute for them; use it only where a sentence would otherwise be cut.

Tables: structure first, text second

Tables are a common source of confident wrong answers in document AI. A financial table has headers, units, merged cells, footnotes and sometimes a second header row. Flattening it into prose destroys the association between a value and its column. A model that sees “2025: 41.2 2026: 47.8” cannot know whether those are revenue, margin or headcount.

Extract tables as objects: a grid of cells, a header model, row labels, column labels, cell coordinates and a caption. Convert the table to Markdown or JSON for the model, but keep the structured object for validation and citation. Check simple invariants before indexing: a total row should equal the sum of its parts, a percentage column should fall within a plausible range, and every numeric cell should have a unit or a header that supplies one.

Merged cells and multi-row headers are the usual breakpoints. A parser that emits a blank cell where two columns are merged will misalign every later row. Compare the recovered grid with the page image on a sample, and store the table ID so a citation can point to the row and column rather than the whole page.

Citations: a link to the page is not enough

A citation is a claim that the answer came from a specific place. For prose, cite the document ID, revision, page, section and the quoted span. For a table, cite the table ID, row label, column label, page and cell value. For a figure, cite the caption and the page. The reader should be able to verify the claim without searching the document.

Verify every citation mechanically before rendering it. The quoted span must exist in the parsed text for that chunk, the page number must match the chunk metadata, and the document revision must be the one that was retrieved. If a quote cannot be matched, the answer fails closed. A model asked to cite sources can produce a plausible section number that does not exist; string matching is the control that catches it.

NIST's Generative AI Profile, NIST AI 600-1, published in July 2024, treats confabulation as a distinct risk and recommends measurement and mitigation across the lifecycle. For document AI, the practical mitigation is retrieval plus verification plus abstention: when the evidence is missing or the citation does not resolve, the system says so instead of answering. That is a product decision as much as a model setting.

Evaluation: score every stage, not just the answer

A single “accuracy” number hides more than it reveals. If the parser loses a table, the retriever cannot find it, and the answer will be wrong for a reason that an end-to-end score cannot diagnose. Build a labelled set from your own documents, stratify it by document type, scan quality, language and table density, and keep a holdout set that the team does not tune against.

Evaluation metrics for a document AI pipeline and what each one isolates
StageMetricWhat it isolatesHow to label it
Parsing and OCRCharacter and word accuracyRecognition qualityTranscribe a sample page by hand
Field extractionExact match and field-level F1Structured output qualityLabel each field, including nulls
TablesCell accuracy and row alignmentGrid recoveryLabel cells with row and column IDs
RetrievalRecall at k and mean reciprocal rankWhether the evidence is foundMark the supporting chunk per question
AnswerCitation precision and recallWhether the cited span supports the claimReview each citation against the source
AbstentionCorrect refusal rateBehaviour when evidence is missingAdd unanswerable questions to the set
Operationsp95 latency and cost per 1,000 pagesProduction feasibilityMeasure the full pipeline, not the model call

No benchmark claim. This page does not quote an accuracy percentage for any parser, OCR engine or model. Published benchmarks are usually built on public corpora that differ from your scans, languages and layouts. A number from someone else's documents is not evidence about yours; a labelled sample from your own corpus is.

Reference pipeline and API surface

A minimal implementation uses a parser for structure, an embedding model for retrieval and a chat model for the answer. Plugsky's catalogue includes plugsky-parse for page and form parsing, plugsky-embed for 2,048-dimension vectors with an 8,192-token input window, and the main text models for synthesis. The parse model page documents the input and output limits; the embedding model page covers the vector shape and context.

curl https://api.plugsky.com/v1/embeddings \
  -H "Authorization: Bearer $PLUGSKY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "plugsky-embed", "input": ["Clause 4.2: the supplier shall notify the buyer within five business days."]}'

Store the returned vector with the chunk ID, document ID, revision, page, clause path and bounding box. On retrieval, return the metadata with the text so the answer step can cite it. The generation call goes to https://api.plugsky.com/v1/chat/completions with the retrieved passages and an output schema that requires a citation for every factual sentence.

Plugsky docs also show https://plugsky.com/v1; both hosts resolve, and the alias is not a second backend. Use https://api.plugsky.com/v1 in examples and keep one host per environment. For an end-to-end RAG design, start at the RAG hub, compare embedding options in best embedding models, and read the embeddings questions before you fix a dimension or a distance metric. For chunking detail, the chunking guide goes deeper than this page.

Failure modes and the control that catches each one

Many document AI incidents are not model failures. They are pipeline failures that the model faithfully reproduces. The table below is the shortest useful incident list we can give a team before launch.

Common document AI failure modes, the symptom a user sees and the control to add
FailureSymptomRoot causeControl
OCR driftWrong date or amount, stated confidentlyLow-quality scan, no second passConfidence threshold, cross-engine check, field rules
Table flatteningValue attributed to the wrong columnTable rendered as plain textStructured grid plus header model
Chunk splitAnswer misses the second half of a clauseFixed-size boundaryClause boundaries and parent expansion
Stale indexAnswer cites a superseded revisionNo re-index on document changeRevision IDs and change-triggered re-index
Fabricated citationSection number does not existModel asked to cite without verificationString-match the quote against the chunk
Unit mismatchThousands versus millionsUnit in a footnote or headerCarry units in the table object and validate
Multilingual misreadArabic text reversed or numerals wrongEnglish-only OCR or tokenizerPer-language evaluation and native review
Over-refusalValid question answered with “not found”Retrieval misses or threshold too strictRecall measurement and threshold tuning

Deployment and cost

Document pipelines handle sensitive material: contracts, invoices, medical records, identity documents and internal policies. Decide the boundary per corpus, not per company. A public manual can use a live region; a contract with personal data may need a private VPC or dedicated endpoint; a regulated archive may need on-premises or air-gapped deployment. Private deployment is contract-led, so confirm scope, storage and support in writing. The private AI page covers the boundary, and /pricing holds the plan limits.

Cost is driven by pages, not by questions. OCR, layout parsing and embedding run once per page or chunk; generation runs per question. That makes ingestion the predictable part and query volume the variable part. Measure cost per 1,000 pages and cost per answered question separately, then decide whether to cache embeddings, re-use chunks across indexes, or route easy questions to a smaller model. Builder at $60/month and Scale at $120/month have no monthly token cap and no per-token overage; fair-use concurrency and RPM limits still apply.

Frequently asked questions

What is a document AI API?

A document AI API turns files into usable structure: it parses pages, runs OCR when a page has no text layer, recovers reading order and tables, splits the result into chunks, and returns text or JSON with page coordinates. In a RAG system it is the ingestion half of the pipeline. The model that answers questions is a separate step, and it should cite the parsed source rather than rely on memory.

Do I need OCR if the PDF has a text layer?

Usually not, but verify per page rather than per file. A PDF can mix native pages, scanned pages and pages whose text layer is garbled or incomplete. Extract the text layer first, measure coverage and character quality, and route only failing pages to OCR. That keeps cost and latency down and preserves the original characters where they are already correct.

How should I chunk a 200-page contract?

Chunk by clause and layout, not by a fixed character count. Keep the heading path, article and page number with every chunk, never split a table from its header, and store parent and child chunks so a small retrieval unit can expand to its surrounding clause. Add overlap only where a sentence would otherwise be cut, and re-chunk when the document revision changes.

How do I cite a table cell?

Store the table as a grid with row and column labels, the page number and a bounding box, then cite the cell by table ID, row label, column label and page. The answer should quote the cell value and its unit. A page-only citation is not enough for a table, because the reader cannot tell which row or column the model used.

How do I evaluate document AI without a published benchmark?

Build a labelled set from your own documents and score the pipeline at each stage: text coverage, field-level exact match or F1, table cell accuracy, retrieval recall at k, citation precision, abstention on missing evidence, p95 latency and cost per 1,000 pages. Publish the set size and the scoring rules so the number can be checked. This page quotes no accuracy percentage because no dated, representative benchmark exists for your corpus.

Can document parsing run in a private deployment?

Yes, but it is contract-led. Private VPC, on-premises and air-gapped deployment can be scoped for workloads that cannot use a shared region, with the scope confirmed in writing. The parser, embedding model and answering model all need to sit inside the same boundary if the document cannot leave it. Check extraction, storage and log retention separately, because a private model does not by itself make the surrounding pipeline private.

Related pages

Measure the pipeline before the model

Prototype parsing and retrieval on the free plan, then size the generation step against your own labelled documents.

Start Free → See pricing

Sources

Official sources below were checked on 20 November 2026. Specifications and guidance change; recheck the edition before a production review.

Official sources used for this page
SourceWhat it supportsChecked
NIST AI 600-1, Generative AI ProfileConfabulation as a risk to measure and mitigate; published July 202420 Nov 2026
Tesseract OCR documentationOpen-source OCR engine and its output model20 Nov 2026
PDF 1.7 specificationPages, text objects and image objects in PDF files20 Nov 2026

Last checked 20 November 2026. Plugsky's canonical plan numbers live at /pricing; this page describes an architecture and does not replace the contract.