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
DATEandNUMBER(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
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=Truecaches 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, orDELETE. Each run declares the rows that should exist, and the connector compares them with the last run. New rows and changed rows get aMERGE. Rows that are no longer declared are removed with oneDELETEper 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:
# 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:
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:

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:

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:
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:
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=Truecaches the result per input. The same Markdown returns the cachedInvoicewith no API call.depsadds the prompt and the schema to the function’s identity. CocoIndex tracks a function’s own source code, butEXTRACT_PROMPTis a module-level constant outside the function body. Withoutdeps, editing the prompt would not re-extract anything. With it, the next run re-extracts every invoice under the new prompt (see thedepsdocs).LLM_MODELis a context key withdetect_change=True. Switch the model in.envand 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:
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 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(*) > 1query 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:
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:
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:
@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:
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:
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:
| source_fileVARCHAR · key | invoice_numberVARCHAR | discountNUMBER(12, 2) | shippingNUMBER(12, 2) | totalNUMBER(12, 2) |
|---|---|---|---|---|
| invoice_Aaron Bergman_36258.pdf | 36258 | 9.74 | 11.13 | 50.10 |
| invoice_Aaron Bergman_36259.pdf | 36259 | NULL | 4.29 | 58.11 |
| invoice_Aaron Bergman_36260.pdf | '' | NULL | NULL | NULL |
| invoice_Aaron Hawkins_36652.pdf | #36652 | NULL | 1.15 | 17.15 |
| invoice_Adam Shillingsburg_12471.pdf | 12471 | 1522.80 | 97.85 | 1620.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:
-- 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.
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, andLLM_MODELforextract_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 orLLM_MODELchange re-runsprocess_invoicetoo. Editing the code that buildsInvoiceRowre-runsprocess_invoicefor every PDF, butextract_invoicestill 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 oneDELETE.
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.$ 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.
| source_file | invoice_number | total | this run |
|---|---|---|---|
| invoice_Aaron Bergman_36258.pdf | 36258 | 50.10 | inserted |
| invoice_Aaron Bergman_36259.pdf | 36259 | 58.11 | inserted |
| invoice_Aaron Bergman_36260.pdf | '' | NULL | inserted |
| invoice_Aaron Hawkins_36652.pdf | #36652 | 17.15 | inserted |
| invoice_Adam Shillingsburg_12471.pdf | 12471 | 1620.65 | inserted |
- 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, …, "total" NUMBER(12, 2), …, PRIMARY KEY ("source_file"))
- 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', …)
- -- 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'
Changing the table later
Schema changes go through the same comparison:
- Add a nullable field (
... | None = None) toInvoiceRowand the next run sendsALTER TABLE ... ADD COLUMN. Existing rows keepNULLin the new column until their component runs again. If you also changeprocess_invoiceto 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
- The Snowflake connector docs list the full type mapping and the
SnowflakeTypeoptions. - The
snowflake_targetexample is a smaller runnable project with no LLM, useful to check your account setup. - Processing components and functions explain the ownership and memoization rules this post relies on.
- The CocoIndex source is on GitHub.
Frequently asked questions
How do I load PDFs or images into Snowflake with CocoIndex?
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?
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?
How do I extract text and entities from documents, as an alternative to Cortex AI Functions?
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?
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?
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 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?
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?
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?
@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.


