Extract Invoice Data from PDFs into Snowflake with an LLM

Extract supplier invoices from PDFs in Azure Blob Storage into a typed Snowflake table with an LLM and CocoIndex, processing only new or changed files.

TutorialUpdated 11 min read
From invoice PDFs to typed Snowflake rows. A card says every new or changed PDF goes through extract_invoice, 1 LLM call, memoized; an arrow points to 3 rows: INVOICES, 1 row per PDF, typed; MERGE, new or changed rows; DELETE, rows of removed PDFs.
Enlarge cover

Extract Invoice Data from PDFs into Snowflake with an LLM

Zoom in to see details.

From invoice PDFs to typed Snowflake rows. A card says every new or changed PDF goes through extract_invoice, 1 LLM call, memoized; an arrow points to 3 rows: INVOICES, 1 row per PDF, typed; MERGE, new or changed rows; DELETE, rows of removed PDFs.

I recently worked with a clothing manufacturer who wanted to simplify their invoice process. Every day they receive around 20 to 22 supplier invoices as PDFs, all stored in Azure Blob Storage.

The finance team used to open each PDF by hand and copy the details into their system. It took a lot of time, and they already had a backlog of 8,000 old invoices waiting to be processed.

My first version used n8n: read the invoices from Azure Blob Storage, pull the fields out of each PDF with an AI model, then load the results into Snowflake. It worked for a while. As the number of invoices grew, the workflow started to break, and debugging errors inside a no-code tool got harder. That is when I switched to code, with CocoIndex, an open-source Python framework for incremental data pipelines.

This post rebuilds that pipeline on the CocoIndex Snowflake connector. My first CocoIndex version, which replaced the n8n workflow, needed about 120 lines of hand-written MERGE SQL to load rows. Now the table is a Python dataclass, and CocoIndex works out which SQL to send.

What you build: a single main.py, about 200 lines, that

  • reads every PDF in an Azure Blob container,
  • converts each one to Markdown and asks an LLM for the invoice fields,
  • keeps one row per PDF in a Snowflake table with real DATE and NUMBER(12, 2) columns, and
  • on the next run, sends only new or changed PDFs to the LLM and only changed rows to Snowflake.

What you need: Python 3.11 or later, an Azure Storage container with your PDFs, a Snowflake account with a warehouse, and an API key for an LLM provider that litellm supports.

How the pipeline fits together

The pipeline in 4 stages. 1, Azure Blob Storage, the source: the invoice container holds 1 PDF blob per invoice, listed with list_blobs and keyed by blob name. 2, process_invoice, 1 processing component per PDF, mounted with coco.mount_each; it is skipped while the blob is unchanged, and it converts the PDF with pdf_to_markdown, which uses MarkItDown. 3, extract_invoice, 1 LLM call per PDF, through instructor and litellm with the Invoice schema, memoized with memo=True and deps on the prompt and the schema. 4, Snowflake, database INVOICE, schema DBO: the INVOICES table holds 1 row per PDF, declared with declare_row and written with a MERGE on source_file. A bar at the bottom says cocoindex update main lists the container; only new or changed PDFs reach the LLM; rows of removed PDFs are deleted.
The pipelineEnlarge

The pipeline

Zoom in to see details.

The pipeline in 4 stages. 1, Azure Blob Storage, the source: the invoice container holds 1 PDF blob per invoice, listed with list_blobs and keyed by blob name. 2, process_invoice, 1 processing component per PDF, mounted with coco.mount_each; it is skipped while the blob is unchanged, and it converts the PDF with pdf_to_markdown, which uses MarkItDown. 3, extract_invoice, 1 LLM call per PDF, through instructor and litellm with the Invoice schema, memoized with memo=True and deps on the prompt and the schema. 4, Snowflake, database INVOICE, schema DBO: the INVOICES table holds 1 row per PDF, declared with declare_row and written with a MERGE on source_file. A bar at the bottom says cocoindex update main lists the container; only new or changed PDFs reach the LLM; rows of removed PDFs are deleted.

Each PDF becomes its own processing component: a unit of work that CocoIndex runs, tracks, and cleans up on its own. The component for one invoice reads the PDF, extracts the fields, and declares the row that should exist in Snowflake. CocoIndex owns the step from “this row should exist” to the SQL that makes it so.

The rest of the post relies on two ideas:

  • Memoization. A function marked memo=True caches its result. CocoIndex reuses the result while the function’s inputs and code stay the same, so an unchanged invoice goes back to the LLM only when the prompt, the schema, or the model changes.
  • Declared rows. You do not write INSERT, UPDATE, or DELETE. Each run declares the rows that should exist, and the connector compares them with the last run. New rows and changed rows get a MERGE. Rows that are no longer declared are removed with one DELETE per run.

CocoIndex keeps its record of past runs in a small local database file (the path comes from COCOINDEX_DB). There is no separate tracking database to run.

Step 1: Set up credentials and Snowflake

Put the credentials in a .env file next to main.py:

.env
# CocoIndex state: a local file
COCOINDEX_DB=./cocoindex.db

# LLM (any litellm model id + the matching provider key)
OPENAI_API_KEY=sk-*********************
LLM_MODEL=openai/gpt-4o

# Azure Blob
AZURE_ACCOUNT_NAME=your_account_name
AZURE_CONTAINER=invoice
AZURE_SAS_TOKEN=sv=**************************
AZURE_PREFIX=

# Snowflake
SNOWFLAKE_ACCOUNT=ORGNAME-ACCOUNTNAME
SNOWFLAKE_USER=your_username
SNOWFLAKE_PASSWORD=***************
SNOWFLAKE_ROLE=
SNOWFLAKE_WAREHOUSE=COMPUTE_WH
SNOWFLAKE_DATABASE=INVOICE
SNOWFLAKE_SCHEMA=DBO
SNOWFLAKE_TABLE=INVOICES

SNOWFLAKE_ACCOUNT is the account identifier from Snowflake’s Account Details, without .snowflakecomputing.com. The connector currently signs in with a user and password; leave SNOWFLAKE_ROLE blank to use the user’s default role.

The warehouse must exist before the first run. CocoIndex creates the database, the schema, and the table, but not the warehouse:

sql
CREATE WAREHOUSE IF NOT EXISTS COMPUTE_WH
  WAREHOUSE_SIZE = XSMALL
  AUTO_SUSPEND = 60
  AUTO_RESUME = TRUE;

The role needs USAGE on the warehouse, permission to create or use the database and the schema, and permission to create the table and run MERGE and DELETE on it. On a trial account, ACCOUNTADMIN covers all of that.

On the Azure side, the SAS token needs list and read permission on the container. For local development you can sign in with az login and pass DefaultAzureCredential() instead of the token; the Azure Blob connector docs show both.

The invoice container holds the supplier PDFs, one blob per invoice:

The invoice container in the Azure portal, listing supplier invoice PDFs as block blobs with their names, sizes, and last-modified times.
The invoice sourceEnlarge

The invoice source

Zoom in to see details.

The invoice container in the Azure portal, listing supplier invoice PDFs as block blobs with their names, sizes, and last-modified times.

Step 2: Describe what the LLM extracts

The fields to pull from each invoice are a Pydantic model. The field descriptions do two jobs: they document the schema, and they tell the LLM how to fill it in. Here is a real invoice from the sample set, with each captured field highlighted:

A sample supplier invoice with the extracted fields highlighted: invoice number, date, customer, bill-to and ship-to blocks, totals, order ID, and the line-item table.
A supplier invoiceEnlarge

A supplier invoice

Zoom in to see details.

A sample supplier invoice with the extracted fields highlighted: invoice number, date, customer, bill-to and ship-to blocks, totals, order ID, and the line-item table.
main.py
import datetime
import decimal

import pydantic


class LineItem(pydantic.BaseModel):
    description: str = pydantic.Field(description='Item or product name, e.g. "Newell 330".')
    quantity: decimal.Decimal | None = None
    rate: decimal.Decimal | None = pydantic.Field(None, description="Unit price.")
    amount: decimal.Decimal | None = pydantic.Field(None, description="Line total.")
    sku: str = pydantic.Field("", description='Product ID if listed, e.g. "OFF-AR-5309".')
    category: str = pydantic.Field("", description="Category or sub-category if listed.")


class Invoice(pydantic.BaseModel):
    invoice_number: str = pydantic.Field("", description='Invoice number, e.g. "36259".')
    invoice_date: datetime.date | None = pydantic.Field(
        None, description="Invoice date as YYYY-MM-DD."
    )
    customer_name: str = pydantic.Field("", description='Name under "Bill To", without the address.')
    bill_to: str = pydantic.Field("", description='Full "Bill To" block, including address.')
    ship_to: str = pydantic.Field("", description='Full "Ship To" block, including address.')
    subtotal: decimal.Decimal | None = None
    discount: decimal.Decimal | None = pydantic.Field(None, description="Discount amount, not the percent.")
    shipping: decimal.Decimal | None = None
    total: decimal.Decimal | None = None
    balance_due: decimal.Decimal | None = None
    order_id: str = pydantic.Field("", description="Purchase order or Order ID.")
    ship_mode: str = pydantic.Field("", description='Shipping method, e.g. "First Class".')
    notes: str = ""
    terms: str = pydantic.Field("", description="Payment terms, if present.")
    line_items: list[LineItem] = pydantic.Field(default_factory=list)


EXTRACT_PROMPT = (
    "Extract the invoice into the Invoice schema. Write amounts as plain numbers "
    '(58.11, not "$58.11"). Use null for a missing amount or date and an empty '
    "string for missing text. Never move a value into a different field."
)

The first CocoIndex version stored every field as text, so "$58.11" and "58.11" could both end up in the total column. Here the amounts are Decimal and the date is a date. Pydantic rejects a reply that does not parse. With max_retries=2 (Step 3), instructor sends the validation error back to the model and asks again before it gives up. A value that reaches Snowflake is already a number or a date, so SUM("total") works without casts.

The invoice prints dates as “Mar 06 2012”. The field description asks for YYYY-MM-DD, which is the format Pydantic parses into a date.

Step 3: Convert the PDF and call the LLM once per invoice

An LLM reads text more reliably than raw PDF bytes, so each file goes through MarkItDown first. It keeps the headings and table rows in reading order:

main.py
import io

from markitdown import MarkItDown, StreamInfo

import cocoindex as coco

_markitdown = MarkItDown()


@coco.fn
def pdf_to_markdown(content: bytes) -> str:
    result = _markitdown.convert_stream(
        io.BytesIO(content), stream_info=StreamInfo(extension=".pdf")
    )
    return result.markdown

MarkItDown is synchronous and CPU-bound. The caller runs it with pdf_to_markdown.as_async(...), which moves the call to a worker thread so the other invoices keep going.

Extraction is one function. It calls the model through litellm, and instructor makes the reply match the Invoice schema:

main.py
import instructor
import litellm

litellm.drop_params = True

LLM_MODEL = coco.ContextKey[str]("llm_model", detect_change=True)


@coco.fn(
    memo=True,
    deps={"prompt": EXTRACT_PROMPT, "schema": Invoice.model_json_schema()},
)
async def extract_invoice(markdown: str) -> Invoice:
    client = instructor.from_litellm(litellm.acompletion, mode=instructor.Mode.JSON)
    result = await client.chat.completions.create(
        model=coco.use_context(LLM_MODEL),
        response_model=Invoice,
        max_retries=2,
        messages=[
            {"role": "system", "content": EXTRACT_PROMPT},
            {"role": "user", "content": markdown},
        ],
    )
    return Invoice.model_validate(result.model_dump())

Three details decide when the LLM runs again:

  • memo=True caches the result per input. The same Markdown returns the cached Invoice with no API call.
  • deps adds the prompt and the schema to the function’s identity. CocoIndex tracks a function’s own source code, but EXTRACT_PROMPT is a module-level constant outside the function body. Without deps, editing the prompt would not re-extract anything. With it, the next run re-extracts every invoice under the new prompt (see the deps docs).
  • LLM_MODEL is a context key with detect_change=True. Switch the model in .env and the cached results stop matching, so each invoice is extracted again by the new model.

Step 4: Describe the Snowflake row as a dataclass

The row is a dataclass. TableSchema.from_class turns its fields into columns, and the connector creates the table to match:

main.py
from dataclasses import dataclass
from typing import Annotated

from cocoindex.connectors import snowflake

Money = Annotated[decimal.Decimal, snowflake.SnowflakeType("NUMBER(12, 2)")] | None


@dataclass
class InvoiceRow:
    source_file: str  # primary key: the blob path
    invoice_number: str
    invoice_date: datetime.date | None
    customer_name: str
    bill_to: str
    ship_to: str
    subtotal: Money
    discount: Money
    shipping: Money
    total: Money
    balance_due: Money
    order_id: str
    ship_mode: str
    notes: str
    terms: str
    line_items: list[dict[str, object]]
The InvoiceRow dataclass on the left maps to the INVOICE.DBO.INVOICES table on the right. source_file, str, becomes source_file VARCHAR NOT NULL, the primary key. invoice_number, str, becomes VARCHAR NOT NULL. invoice_date, date or None, becomes DATE. The 7 str fields from customer_name to terms become 7 VARCHAR NOT NULL columns. The 5 Money fields from subtotal to balance_due become 5 NUMBER(12, 2) columns, highlighted, through SnowflakeType. line_items, list of dict, becomes line_items VARIANT NOT NULL, written with PARSE_JSON. Notes below: Money is Annotated Decimal with SnowflakeType NUMBER(12, 2), or None. Without the annotation, Decimal maps to NUMBER, which Snowflake reads as NUMBER(38, 0), so 58.11 would be stored as 58. Names are quoted, so they stay lowercase: query them as quoted total, not total.
From dataclass to tableEnlarge

From dataclass to table

Zoom in to see details.

The InvoiceRow dataclass on the left maps to the INVOICE.DBO.INVOICES table on the right. source_file, str, becomes source_file VARCHAR NOT NULL, the primary key. invoice_number, str, becomes VARCHAR NOT NULL. invoice_date, date or None, becomes DATE. The 7 str fields from customer_name to terms become 7 VARCHAR NOT NULL columns. The 5 Money fields from subtotal to balance_due become 5 NUMBER(12, 2) columns, highlighted, through SnowflakeType. line_items, list of dict, becomes line_items VARIANT NOT NULL, written with PARSE_JSON. Notes below: Money is Annotated Decimal with SnowflakeType NUMBER(12, 2), or None. Without the annotation, Decimal maps to NUMBER, which Snowflake reads as NUMBER(38, 0), so 58.11 would be stored as 58. Names are quoted, so they stay lowercase: query them as quoted total, not total.

The mapping follows the Python types. str becomes VARCHAR, datetime.date becomes DATE, and lists, dicts, and nested records become VARIANT, which the connector writes with PARSE_JSON. A type that allows None gives a nullable column; every other column is NOT NULL.

Why the Money annotation. A plain decimal.Decimal maps to NUMBER. Snowflake reads NUMBER without a precision as NUMBER(38, 0), a whole number, so 58.11 would be stored as 58. SnowflakeType("NUMBER(12, 2)") pins the column type. Put the annotation on Decimal and add | None outside it, as above. In version 1.1.1 the other order, Annotated[decimal.Decimal | None, SnowflakeType(...)], is not picked up, and the column falls back to NUMBER.

Why the blob path is the primary key. The first CocoIndex version keyed rows on the invoice number and fell back to the filename when the LLM found no number. Here the key is the blob path, because the row belongs to the file:

  • A misread invoice number cannot move the row to a different key or overwrite another invoice’s row.
  • Deleting a PDF removes its row; renaming it moves the row to the new key.
  • Two PDFs with the same invoice number stay two rows, and a GROUP BY "invoice_number" HAVING COUNT(*) > 1 query finds them.

Why line_items is a list of dicts. The connector JSON-encodes VARIANT values. A list of Pydantic models would not encode as JSON objects, so the code converts each line item with model_dump(mode="json") first. That also turns the Decimal amounts into strings such as "48.71", which Snowflake can cast back with ::NUMBER(12, 2).

Step 5: Process one invoice

One component handles one PDF: read it, convert it, extract the fields, and declare the row. declare_row states which row should exist; it does not send SQL by itself:

main.py
from cocoindex.resources.file import FileLike


@coco.fn(memo=True)
async def process_invoice(
    file: FileLike,
    table: snowflake.TableTarget[InvoiceRow],
) -> None:
    markdown = await pdf_to_markdown.as_async(await file.read())
    inv = await extract_invoice(markdown)
    table.declare_row(
        row=InvoiceRow(
            source_file=file.file_path.path.as_posix(),
            invoice_number=inv.invoice_number,
            invoice_date=inv.invoice_date,
            customer_name=inv.customer_name,
            bill_to=inv.bill_to,
            ship_to=inv.ship_to,
            subtotal=inv.subtotal,
            discount=inv.discount,
            shipping=inv.shipping,
            total=inv.total,
            balance_due=inv.balance_due,
            order_id=inv.order_id,
            ship_mode=inv.ship_mode,
            notes=inv.notes,
            terms=inv.terms,
            line_items=[li.model_dump(mode="json") for li in inv.line_items],
        )
    )

process_invoice is memoized as well. The Azure Blob connector fingerprints each blob by its ETag, which changes whenever the blob is rewritten. While the ETag stays the same, CocoIndex skips the component, does not download the PDF, and keeps the row it declared last time.

Step 6: Wire up the app

The connections are created once, in the app’s lifespan, and the functions read them with coco.use_context:

main.py
import os
from collections.abc import AsyncIterator

from azure.storage.blob.aio import ContainerClient
from dotenv import load_dotenv

from cocoindex.connectors import azure_blob
from cocoindex.resources.file import PatternFilePathMatcher

load_dotenv()

SNOWFLAKE = coco.ContextKey[snowflake.ConnectionConfig]("invoice_snowflake")
AZURE = coco.ContextKey[ContainerClient]("invoice_container")


@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
    builder.provide(LLM_MODEL, os.environ.get("LLM_MODEL", "openai/gpt-4o"))
    builder.provide(
        SNOWFLAKE,
        snowflake.ConnectionConfig(
            account=os.environ["SNOWFLAKE_ACCOUNT"],
            user=os.environ["SNOWFLAKE_USER"],
            password=os.environ["SNOWFLAKE_PASSWORD"],
            warehouse=os.environ.get("SNOWFLAKE_WAREHOUSE"),
            role=os.environ.get("SNOWFLAKE_ROLE") or None,
        ),
    )
    async with ContainerClient(
        account_url=f"https://{os.environ['AZURE_ACCOUNT_NAME']}.blob.core.windows.net",
        container_name=os.environ["AZURE_CONTAINER"],
        credential=os.environ["AZURE_SAS_TOKEN"],
    ) as client:
        builder.provide(AZURE, client)
        yield

Keep the context key names stable. CocoIndex uses "invoice_snowflake" as the identity of the connection when it tracks which rows it manages, so renaming the key later looks like a different target.

app_main mounts the table target, lists the PDFs, and starts one process_invoice component per file with mount_each:

main.py
@coco.fn
async def app_main() -> None:
    table = await snowflake.mount_table_target(
        SNOWFLAKE,
        table_name=os.environ.get("SNOWFLAKE_TABLE", "INVOICES"),
        table_schema=await snowflake.TableSchema.from_class(
            InvoiceRow, primary_key=["source_file"]
        ),
        database=os.environ.get("SNOWFLAKE_DATABASE", "INVOICE"),
        schema=os.environ.get("SNOWFLAKE_SCHEMA", "DBO"),
    )

    files = azure_blob.list_blobs(
        coco.use_context(AZURE),
        prefix=os.environ.get("AZURE_PREFIX", ""),
        path_matcher=PatternFilePathMatcher(included_patterns=["**/*.pdf"]),
    )
    await coco.mount_each(process_invoice, files.items(), table)


app = coco.App(
    coco.AppConfig(name="InvoiceExtraction"),
    app_main,
)

files.items() yields (blob name, file) pairs. mount_each uses the blob name as each component’s key, which is how CocoIndex recognizes the same invoice across runs, and how it notices when a blob is gone.

Run it

Install the dependencies. MarkItDown needs its pdf extra to read PDFs:

sh
pip install "cocoindex[snowflake,azure_blob]>=1.1" instructor litellm "markitdown[pdf]" python-dotenv
cocoindex update main

On the first run, the connector creates the objects and then writes one MERGE per invoice. These are the statements it sends, shortened:

sql
CREATE DATABASE IF NOT EXISTS "INVOICE";
CREATE SCHEMA IF NOT EXISTS "INVOICE"."DBO";
CREATE TABLE "INVOICE"."DBO"."INVOICES" (
  "source_file" VARCHAR NOT NULL,
  "invoice_number" VARCHAR NOT NULL,
  "invoice_date" DATE,
  ...
  "total" NUMBER(12, 2),
  "line_items" VARIANT NOT NULL,
  PRIMARY KEY ("source_file")
);

MERGE INTO "INVOICE"."DBO"."INVOICES" AS target
USING (SELECT %s AS "source_file", %s AS "invoice_number", ..., PARSE_JSON(%s) AS "line_items") AS source
ON target."source_file" = source."source_file"
WHEN MATCHED THEN UPDATE SET "invoice_number" = source."invoice_number", ...
WHEN NOT MATCHED THEN INSERT ("source_file", "invoice_number", ...) VALUES (source."source_file", ...);

MERGE is an upsert: it updates the row if the key exists and inserts it if not. That makes a retry after a failed run safe.

After the first run, the table has one row per PDF:

INVOICE.DBO.INVOICES in this version

Illustrative: blob names and amounts from the sample invoices

source_fileVARCHAR · keyinvoice_numberVARCHARdiscountNUMBER(12, 2)shippingNUMBER(12, 2)totalNUMBER(12, 2)
invoice_Aaron Bergman_36258.pdf362589.7411.1350.10
invoice_Aaron Bergman_36259.pdf36259NULL4.2958.11
invoice_Aaron Bergman_36260.pdf''NULLNULLNULL
invoice_Aaron Hawkins_36652.pdf#36652NULL1.1517.15
invoice_Adam Shillingsburg_12471.pdf124711522.8097.851620.65

Not shown: invoice_date, customer_name, bill_to, ship_to, subtotal, balance_due, order_id, ship_mode, notes, terms and line_items. Query the columns with quotes, as in SELECT "total".

This table differs from the first CocoIndex version’s table in three ways. Column names are lowercase. The amounts are NUMBER(12, 2) instead of text, and a missing amount is NULL. The key column is source_file. In the first version, when the LLM found no invoice number, the filename took its place in invoice_number. In this version, such a row keeps its blob name as the key and an empty invoice_number, as for invoice_Aaron Bergman_36260.pdf above. A query for empty invoice numbers lists the PDFs to check by hand. The #36652 row shows another kind of slip: the LLM kept the # that the PDF prints before the number. The re-run demo fixes it in two ways, with a prompt edit or with a code edit.

Query the table

The connector quotes every identifier, so the column names keep their lowercase spelling. In Snowflake, an unquoted name is read as uppercase: SELECT total looks for a column TOTAL and fails. Quote the column names:

sql
-- Monthly totals
SELECT DATE_TRUNC('month', "invoice_date") AS month,
       COUNT(*) AS invoices,
       SUM("total") AS total
FROM INVOICE.DBO.INVOICES
GROUP BY 1
ORDER BY 1;

-- One row per line item
SELECT i."invoice_number",
       li.value:description::STRING AS item,
       li.value:quantity::NUMBER AS quantity,
       li.value:amount::NUMBER(12, 2) AS amount
FROM INVOICE.DBO.INVOICES i,
     LATERAL FLATTEN(input => i."line_items") li;

-- PDFs where the LLM found no invoice number
SELECT "source_file" FROM INVOICE.DBO.INVOICES WHERE "invoice_number" = '';

The database and schema names are uppercase, so they work quoted or unquoted.

What a re-run does

Incremental runs are where the time and cost savings come from. On the client project we first loaded the backlog of about 8,000 invoices, then ran the pipeline daily on the 20-odd new ones. The daily run does not send the 8,000 unchanged invoices to the LLM, and it does not touch their rows in Snowflake.

What a re-run sends to the LLM and to Snowflake, in 8 cases. First run, empty table, outlined in green: 1 LLM call per PDF; CREATE DATABASE, SCHEMA and TABLE, then a MERGE per PDF. Nothing changed, outlined in dashed gray: 0 calls, nothing sent. New PDF uploaded, green: 1 call; MERGE inserts its row. PDF replaced with a new ETag, periwinkle: 1 call; MERGE updates its row if a value changed. PDF deleted, rose: 0 calls; DELETE where source_file is in the removed keys. Prompt, schema or LLM_MODEL edited, periwinkle: 1 call per PDF; MERGE only for rows whose values changed. Row code edited in process_invoice, periwinkle: 0 calls; MERGE only for rows whose values changed. Field added to InvoiceRow, periwinkle: 0 calls; ALTER TABLE ADD COLUMN. A legend maps dashed gray to unchanged, green to rows added, periwinkle to rows changed and rose to rows deleted. A note says each changed row is one MERGE statement, and a re-extraction that returns the same values sends no SQL.
What a re-run doesEnlarge

What a re-run does

Zoom in to see details.

What a re-run sends to the LLM and to Snowflake, in 8 cases. First run, empty table, outlined in green: 1 LLM call per PDF; CREATE DATABASE, SCHEMA and TABLE, then a MERGE per PDF. Nothing changed, outlined in dashed gray: 0 calls, nothing sent. New PDF uploaded, green: 1 call; MERGE inserts its row. PDF replaced with a new ETag, periwinkle: 1 call; MERGE updates its row if a value changed. PDF deleted, rose: 0 calls; DELETE where source_file is in the removed keys. Prompt, schema or LLM_MODEL edited, periwinkle: 1 call per PDF; MERGE only for rows whose values changed. Row code edited in process_invoice, periwinkle: 0 calls; MERGE only for rows whose values changed. Field added to InvoiceRow, periwinkle: 0 calls; ALTER TABLE ADD COLUMN. A legend maps dashed gray to unchanged, green to rows added, periwinkle to rows changed and rose to rows deleted. A note says each changed row is one MERGE statement, and a re-extraction that returns the same values sends no SQL.

Two layers decide what happens:

  • Which functions run. CocoIndex compares each memoized call with the last run: the blob’s ETag for process_invoice; the Markdown, the prompt, the schema, and LLM_MODEL for extract_invoice; and the source code of both. Only calls with a difference run again, and a memoized call also runs again when a function it calls is out of date, which is why a prompt or LLM_MODEL change re-runs process_invoice too. Editing the code that builds InvoiceRow re-runs process_invoice for every PDF, but extract_invoice still hits its cache, so the LLM is not called.
  • Which rows are written. The connector fingerprints each declared row and compares it with the fingerprint from the last run. A row with the same values sends nothing, even if the LLM just re-extracted it. A row whose values changed gets one MERGE. Keys that were declared last time and not this time, because their PDFs are gone, are removed in one DELETE.

Try each case below. We checked every outcome in the figure and the demo on cocoindex 1.1.1 with the functions from this post, a fake Snowflake cursor that records SQL, local copies of the PDFs, and a mocked LLM.

Change one thing, run cocoindex update main

Simulated; outcomes checked against cocoindex 1.1.1. Values are illustrative.
Change the data
Change the code or config
first run, empty table
$ cocoindex update main
LLM calls
5
process_invoice runs
5
SQL statements
8

First run: every PDF is new, so each one is converted and sent to the LLM once. The connector creates the database, the schema and the table, then sends one MERGE per row.

INVOICE.DBO.INVOICES
source_fileinvoice_numbertotalthis run
invoice_Aaron Bergman_36258.pdf3625850.10inserted
invoice_Aaron Bergman_36259.pdf3625958.11inserted
invoice_Aaron Bergman_36260.pdf''NULLinserted
invoice_Aaron Hawkins_36652.pdf#3665217.15inserted
invoice_Adam Shillingsburg_12471.pdf124711620.65inserted
SQL sent to Snowflake
  1. CREATE DATABASE IF NOT EXISTS "INVOICE"
  2. CREATE SCHEMA IF NOT EXISTS "INVOICE"."DBO"
  3. CREATE TABLE "INVOICE"."DBO"."INVOICES" ("source_file" VARCHAR NOT NULL, "invoice_number" VARCHAR NOT NULL, …, "total" NUMBER(12, 2), …, PRIMARY KEY ("source_file"))
  4. MERGE INTO "INVOICE"."DBO"."INVOICES" AS target USING (SELECT %s AS "source_file", %s AS "invoice_number", …) AS source ON target."source_file" = source."source_file" WHEN MATCHED THEN UPDATE SET … WHEN NOT MATCHED THEN INSERT … -- params: ('invoice_Aaron Bergman_36258.pdf', '36258', …)
  5. -- 4 more MERGE statements, one per row: 'invoice_Aaron Bergman_36259.pdf', 'invoice_Aaron Bergman_36260.pdf', 'invoice_Aaron Hawkins_36652.pdf', 'invoice_Adam Shillingsburg_12471.pdf'
LLM calls so far: 5

Changing the table later

Schema changes go through the same comparison:

  • Add a nullable field (... | None = None) to InvoiceRow and the next run sends ALTER TABLE ... ADD COLUMN. Existing rows keep NULL in the new column until their component runs again. If you also change process_invoice to fill the field, its code change re-runs every component, and the LLM results come from the cache.
  • Remove a field and the connector drops the column. Change a field’s type and it drops and re-adds the column, then rewrites every row so the column is filled again.
  • Change the primary key or rename the table and the connector treats it as a new table: it drops the old one, creates the new one, and writes all rows again.

With managed_by="system" (the default), CocoIndex owns the table. If the table belongs to someone else and must already exist, pass managed_by="user" to mount_table_target; CocoIndex then writes rows but does not create, alter, or drop the table.

Limits and what to watch for

Accuracy. Because an LLM reads the invoices, the output is not perfect. On the original client data, many fields were mismatched at first, and refining the prompt improved accuracy. Clean, structured PDFs are the easy case; messy or inconsistent ones can still trip the model up. With deps on the prompt, each prompt revision re-extracts the whole set, so you can compare runs on the same invoices.

Parsing. CocoIndex runs the pipeline and tracks what changed; the extraction step is yours to choose. I used OpenAI here, but Google Document AI, a specialized invoice parser, or a fine-tuned model could replace the body of extract_invoice.

Write volume. The connector sends one MERGE statement per changed row and one DELETE per batch of removed keys. For a backlog of 8,000 invoices, the first run sends 8,000 MERGE statements. After that, the daily run sends only the 20-odd new ones.

Authentication. The connector signs in with a user and password. ConnectionConfig accepts account, user, password, warehouse, and role. Key-pair authentication is not covered by the connector yet.

Where to go next

Frequently asked questions

How do I load PDFs or images into Snowflake with CocoIndex?
CocoIndex handles extraction and transformation: convert PDFs with MarkItDown or marker, embed images with CLIP or ColPali, and pass the text to any LLM. The Snowflake connector loads the result: it creates the table from a Python dataclass, maps the types to columns, and upserts rows with MERGE by primary key, so the hand-written target code from the original version is gone. For field-level accuracy on structured PDFs, see Patient intake form extraction.
How do I auto-ingest new files from S3 or Azure Blob?
Point azure_blob.list_blobs, or the Amazon S3 source at your container or bucket and hand the files to coco.mount_each. CocoIndex fingerprints each file (for Azure Blob, by its ETag), and each cocoindex update processes only the files that changed, whether you schedule it with cron, Azure Functions, or GitHub Actions. You do not need per-bucket notifications. See S3 incremental ETL for the S3 walkthrough.
CocoIndex vs. Snowflake Openflow for unstructured data: when to pick which?
Openflow keeps compute inside Snowflake and fits SQL-first teams who want a managed no-code surface. CocoIndex is an open-source Python framework that is incremental by default and does not depend on the target store. The same app can write to Snowflake, Postgres, Qdrant, LanceDB, Apache Doris, or Kafka. Pick CocoIndex if you want to mix LLM providers (OpenAI, Mistral, and local Ollama in one app), control LLM cost with memoization, or trace each row back to its source file.
How do I extract text and entities from documents, as an alternative to Cortex AI Functions?
A CocoIndex function calls the model through litellm and instructor with a Pydantic schema, across OpenAI, Mistral, Gemini, Anthropic, Ollama, or any provider litellm supports, and returns typed values. The schema's field descriptions also serve as instructions to the model. Walkthroughs: Structured extraction with DSPy, with BAML, and patient intake forms. For on-prem, Ollama + CocoIndex shows the local-model path.
How do I build RAG or a chatbot over my documents without Cortex Search?
The CocoIndex recipe: ingest, chunk with RecursiveSplitter (syntax-aware for Markdown and 20+ programming languages), embed with SentenceTransformers or a litellm-backed API model, write to Qdrant, LanceDB, Postgres with pgvector, or Apache Doris, then query. The vector store is a separate step, so you can swap it without changing the upstream logic. See Text embeddings 101, Codebase RAG, and multi-modal ColPali.
How do I generate and store embeddings for unstructured data?
Embed a value with SentenceTransformerEmbedder or a litellm-backed model inside a processing component, then declare the vector as a column on your target row. CocoIndex handles batching and loads the model lazily. Image embeddings with CLIP or ColPali's multi-vector scheme are supported. Live image search with CLIP walks through it end to end.
How do I process only new or changed files, Snowflake Streams-style?
CocoIndex does this by default. A memoized function is skipped while its inputs, its code, and its declared dependencies stay the same. On the next cocoindex update, unchanged files skip the LLM call, and the Snowflake connector sends SQL only for rows whose values changed: a MERGE per new or changed row and a DELETE for rows whose source file is gone. You do not need Streams, Tasks, or triggers. See Incremental processing for the mechanics and Continuous updates for live sources.
Where does CocoIndex keep its processing state?
In a small local database file. Set its path with the COCOINDEX_DB environment variable (for example COCOINDEX_DB=./cocoindex.db in .env) or with db_path in the app settings. The file records which files were processed, the cached function results, and which rows CocoIndex wrote. A Snowflake-target pipeline needs no separate tracking database; the original version of this pipeline used Postgres for that. For a team deployment where workers share state across hosts and restarts, CocoIndex Plus keeps it in Postgres; see CocoIndex Plus.
How do I trace a Snowflake column back to its source document?
Every declared row is owned by the processing component that produced it, and in this pipeline the primary key is the blob path, source_file. A row therefore points at its source PDF directly, and the chain runs: Snowflake row, the component for one invoice, LLM extraction, Markdown conversion, source PDF.
How do I keep LLM costs down on large-corpus pipelines?
Two levers that combine: (1) memoization: @coco.fn(memo=True) caches a result per input and code version, so a daily run on top of an 8,000-invoice backlog calls the LLM only for the new invoices. Add the prompt to deps so a prompt edit re-extracts. (2) provider routing: litellm lets you send bulk work to a local Ollama model and keep a hosted model such as GPT-4o for harder documents, from the same app. Changing the model re-extracts every file, and the connector still writes only the rows whose values changed.

Build fresh context for your agents.

CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.