4: Snowflake Document Processing

    AI_PARSE_DOCUMENT with OCR mode, LAYOUT mode, page_split, and page_limit options

    How it works

    AI_PARSE_DOCUMENT is the single point of entry for turning a binary document file in a Snowflake stage into addressable text or structured markdown.

    It is a SQL function that takes a stage reference and a settings dictionary, calls a Snowflake-hosted parsing model on the binary, and returns a structured result.

    Every other document workflow in this chapter, including AI_EXTRACT calls, Cortex Search ingestion of unstructured assets, and downstream Cortex Analyst joins against extracted metadata, starts with an AI_PARSE_DOCUMENT call.

    The function is metered per page processed, so the configuration of its mode and paging behavior is not just a quality decision; it is a cost decision that compounds across millions of pages per month in any real production pipeline.

    The function signature accepts a FILE object (typically built with TO_FILE from a stage path) and a settings object with four keys that matter for production tuning: mode, page_split, page_limit, and an optional language hint.

    The mode key takes one of two literal string values: 'OCR' or 'LAYOUT'.

    The mode choice changes what the function returns, what model it runs internally, what document classes it can handle, and what the per-page price is.

    Confusing the two is the single most common Snowflake document processing mistake in production, and it is heavily tested.

    OCR mode is the right choice for documents that are primarily linear text and where downstream consumption is plain-text RAG ingestion, classification, or sentiment analysis.

    The model walks the document page by page, recognises characters, applies basic line and paragraph reconstruction, and returns a single text payload per page (or per document, if page_split is false). The output schema is a JSON document with a top-level content array of objects, each carrying index (the page number), text (the recognised characters), and a few diagnostic fields including confidence.

    OCR mode handles:

    • handwritten content
    • scanned receipts
    • low-quality photographs of printed pages
    • rotated images

    It tolerates skew up to a few degrees and applies de-warping internally. What it does not do is preserve table structure, column alignment, list nesting, or heading hierarchy. A two-column financial statement parsed in OCR mode produces interleaved text that requires significant downstream cleanup before it is usable.

    Comparison

    LAYOUT mode runs a different internal model that is layout-aware. It detects tables, headings, lists, and reading order across columns, then emits the document as markdown. Tables are rendered with pipe-delimited markdown syntax, headings carry the right number of hash symbols, and lists are bulleted in source order.

    LAYOUT mode is the right choice for any document where structure carries meaning:

    • contracts with numbered clauses
    • invoices with line-item tables
    • reports with multi-column layouts
    • technical manuals with code blocks
    • any document that downstream feeds Cortex Search with SPLIT_TEXT_MARKDOWN_HEADER as the chunking strategy

    The per-page price is higher than OCR mode because the layout model is heavier, but the downstream cost savings often outweigh that delta: markdown that already carries heading anchors does not need a second pass to recover structure.

    The page_split boolean (default true) controls whether the result returns one payload per page or one concatenated payload for the whole document.

    Set page_split to false only when the downstream consumer treats the whole document as a single retrieval unit (a typical Cortex Search service with chunk_size 1000 will re-chunk anyway, so the page boundary does not matter much).

    Keep page_split as true for any pipeline that does per-page error handling, per-page cost attribution, or per-page audit.

    With page_split true, the content array carries one element per page; downstream Streams that count pages-processed work cleanly off the array length.

    The page_limit integer caps the number of pages the function will process from the front of the document.

    The default behavior is to process every page; setting page_limit to a small positive integer (a value of 5 is a common production setting for invoice or receipt pipelines) hard-caps both the latency of a single call and the per-call credit spend.

    For documents where the relevant content is always near the front (cover pages of contracts, header pages of statements, the first page of a multi-page receipt scan), page_limit is the single most effective cost control in the function.

    It is also a guardrail: a 500-page accidentally-uploaded PDF will be processed only for the first N pages, not the full 500.

    OCR mode and LAYOUT mode in practice

    -- OCR mode call with paging on
    SELECT
     AI_PARSE_DOCUMENT(
     TO_FILE('@DOC_AI_DB.INGEST.RAW_DOCS', 'receipts/2024Q4_batch_001.pdf'),
     {
     'mode': 'OCR',
     'page_split': TRUE,
     'page_limit': 10
     }
     ) AS parse_result;
    
    -- LAYOUT mode call returning markdown for a multi-column contract
    SELECT
     AI_PARSE_DOCUMENT(
     TO_FILE('@DOC_AI_DB.INGEST.RAW_DOCS', 'contracts/master_services_agreement.pdf'),
     {
     'mode': 'LAYOUT',
     'page_split': TRUE
     }
     ) AS parse_result;
    

    The returned parse_result is a Snowflake OBJECT. Production pipelines bind the result into a column and then expand it with FLATTEN to land one row per page:

    CREATE OR REPLACE TABLE DOC_AI_DB.PARSED.RECEIPTS_PAGES AS
    SELECT
     f.relative_path AS file_path,
     p.value:index::INT AS page_index,
     p.value:text::VARCHAR AS page_text,
     p.value:confidence::FLOAT AS confidence,
     parse_result:metadata:page_count::INT AS doc_page_count,
     CURRENT_TIMESTAMP() AS parsed_at
    FROM DIRECTORY('@DOC_AI_DB.INGEST.RAW_DOCS') f,
    LATERAL FLATTEN(input => AI_PARSE_DOCUMENT(
     TO_FILE('@DOC_AI_DB.INGEST.RAW_DOCS', f.relative_path),
     {'mode': 'OCR', 'page_split': TRUE}
    ):content) p
    WHERE f.relative_path ILIKE 'receipts/%';
    

    Decision Tree: Choosing OCR mode vs LAYOUT mode

    📊 Limit: AI_PARSE_DOCUMENT is metered per page processed by the parsing model. A document with page_limit = 5 against a 200-page PDF bills for 5 pages; a document with the default unlimited setting against the same PDF bills for 200 pages.

    💡 Exam Trap: OCR mode does not return markdown. A scenario that requires a downstream call to SPLIT_TEXT_MARKDOWN_HEADER must use LAYOUT mode; otherwise the markdown header splitter has no # anchors to split on and falls back to whole-document chunks.

    💡 Exam Trap: page_split defaults to true. If a scenario shows a single concatenated string returned by AI_PARSE_DOCUMENT, the call must have explicitly set page_split to false; do not assume that default OCR mode returns one payload per document.

    ⚠️ Anti-Pattern: Calling AI_PARSE_DOCUMENT with LAYOUT mode on a single-column low-structure receipt scan. The layout model adds cost without improving downstream quality on documents whose only structural cue is a vertical line of items.

    Fine-tuning arctic-extract models for custom extraction quality

    For document classes that have a stable visual template but a vocabulary the base model has not seen (an internal expense form, a country-specific tax return, a bespoke insurance loss report), neither OCR mode nor LAYOUT mode out of the box reaches the extraction precision a production workflow needs.

    Snowflake exposes a fine-tuning surface for the arctic-extract family of extraction models that lets a team supply labelled examples and produce a private model that the AI_PARSE_DOCUMENT call routes to under the hood. The fine-tuned model is registered in the account and selected via a model_name setting in the AI_PARSE_DOCUMENT call's settings dictionary.

    Fine-tuning data is a set of document-and-extraction pairs: the source document file plus the structured extraction the model should produce. Labelling is done in the Document AI builder UI inside Snowsight, which lets a labeller draw bounding boxes around fields and assign field names. Snowflake builds a training set from those labels, runs a managed fine-tune job on the arctic-extract base model, and registers the resulting model under a name the team chooses.

    Twenty to fifty labelled documents per template variant is the typical floor for a measurable quality lift; below that, the fine-tune does not generalise and may overfit to the specific test documents.

    -- Calling a fine-tuned arctic-extract model from AI_PARSE_DOCUMENT
    SELECT
     AI_PARSE_DOCUMENT(
     TO_FILE('@DOC_AI_DB.INGEST.RAW_DOCS', 'expense_forms/q1_batch_017.pdf'),
     {
     'mode': 'LAYOUT',
     'model_name': 'DOC_AI_DB.MODELS.EXPENSE_FORM_V3',
     'page_split': TRUE
     }
     ) AS parse_result;
    

    💡 Exam Trap: Fine-tuning the arctic-extract model is supported only for documents whose template variation falls inside a narrow band. A team that submits documents from three different expense form vendors as one training set will produce a model that performs worse than the base. Split the training set per template and produce three separate fine-tuned models.

    🎯 Scenario: A claims operations team submits 80,000 insurance loss reports per month from twelve regional offices. Each office uses its own template, with field labels in the local language. The team starts with one fine-tuned arctic-extract model on the merged set and sees extraction accuracy drop from the base model's 78 percent to 71 percent. They split the training set into twelve template-specific buckets, fine-tune one model per template, route documents at parse time using the office identifier, and reach 94 percent average accuracy across the merged output.

    Decision Anchor: Choose OCR mode when the document is text-dominant and the downstream consumer is a chunked Cortex Search service that re-shapes content anyway. Choose LAYOUT mode when tables, headings, or column structure carry semantic meaning that downstream consumers must preserve.

    Choose a fine-tuned arctic-extract model only when (a) the document template is stable, (b) the labelled training set covers the variation, and (c) the base-model accuracy on a labelled holdout is below the workflow's quality bar. ---

    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Snowflake - SnowPro Specialty Gen AI learning hub.