{"slug":"grounded-rag-ingestion","title":"grounded-rag-ingestion","summary":"Chunk a document into provenance-carrying JSONL ready for embedding via the Nutrient Data Extraction API (`/extraction/parse`, spatial output). Every chunk carries element type, page index, bounding box, confidence, and reading order, traceable to a specific page region. Use for ","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-11-29T00:42:57.323881Z","repo":{"url":"https://github.com/PSPDFKit-labs/nutrient-skills","stars":18,"forks":1,"license":null,"updatedAt":"2026-11-26T02:45:46Z"},"bodyHtml":"<hr>\n<h2>name: grounded-rag-ingestion\ndescription: &gt;-\nChunk a document into provenance-carrying JSONL ready for embedding via the Nutrient Data\nExtraction API (<code>/extraction/parse</code>, spatial output). Every chunk carries element type, page\nindex, bounding box, confidence, and reading order, traceable to a specific page region. Use\nfor grounded or auditable RAG, cited retrieval, confidence-aware ingestion, or any pipeline\nthat must prove which document region a retrieved answer came from. Triggers include grounded\nRAG, auditable RAG, RAG with provenance, chunk with bounding box, cite page, provenance-carrying\nchunks, confidence-aware chunking, or embedding pipeline. Not for cheap Markdown — use\ndocument-extraction-api with <code>--output-format markdown</code> for that. Not for known target fields\n— if the user wants specific fields (\"invoice number and total\", \"map to my schema\", \"return these fields cited\"), use document-extraction-api's <code>extract</code> (one cited call), not whole-document\nchunking.\nlicense: MIT\nmetadata:\nauthor: nutrient-sdk\nversion: \"1.0\"\nhomepage: \"https://www.nutrient.io/api/data-extraction-api/\"\nrepository: \"https://github.com/PSPDFKit-labs/nutrient-skills\"\ncompatibility: \"Requires Python 3.10+, uv, and internet. Works with Claude Code, Codex CLI, Gemini CLI, OpenCode, Cursor, Windsurf, GitHub Copilot, Amp, or any Agent Skills-compatible product.\"\nshort-description: \"Chunk documents into provenance-carrying JSONL for grounded, auditable RAG\"</h2>\n<h1>Grounded RAG Ingestion</h1>\n<p>Turn a document into a stream of <strong>provenance-carrying chunks</strong> — one JSONL line per chunk,\neach tagged with its element type, page index, bounding box, confidence score, and\nreading-order index, all traceable back to a specific region of the source page.</p>\n<p>The differentiator is provenance, a capability frontier-LLM Markdown extraction structurally\ncannot supply: a downstream system can highlight the exact region of the source document a\nretrieval result came from. That is the compliance-grade requirement for RAG in finance,\nhealthcare, and legal workflows where \"the model said so\" is not an acceptable citation. This\nskill does not relitigate raw Markdown quality (see the <code>pdf-to-markdown</code> skill for that) — it\nadds the provenance layer on top of Nutrient extraction.</p>\n<p>This is a <strong>doer skill</strong>: a bundled <code>uv</code>-runnable Python script (<code>chunk.py</code>) drives the pipeline\nend to end and emits JSONL to stdout or a file. It is <strong>embedding-agnostic</strong> — it stops at the\nchunk boundary. No vector DB client, no embedding provider import.</p>\n<h2>When to use</h2>\n<ul>\n<li><strong>Grounded / cited RAG</strong>: retrieval results include <code>page_index</code> and <code>bbox</code> so the UI can draw\na highlight box on the source document.</li>\n<li><strong>Confidence-aware ingestion</strong>: gate on <code>confidence &gt;= threshold</code> to suppress low-confidence\nchunks before they reach the index.</li>\n<li><strong>Reading-order-aware chunking</strong>: preserve <code>reading_order</code> so sliding-window chunking respects\nthe document's logical sequence.</li>\n<li><strong>Auditable pipelines</strong>: regulated workflows that must prove which page region a retrieved\nanswer came from — the <code>bbox</code> + <code>page_index</code> tuple is the audit trail.</li>\n</ul>\n<p><strong>Not for</strong> cheap whole-document Markdown — that stays in <code>document-extraction-api</code> with\n<code>--output-format markdown</code>. <strong>Not for known target fields</strong> — if the request names specific\nfields (\"the invoice number and total\", \"extract these fields\", \"map to my schema\", \"return these fields cited\"), use <code>document-extraction-api</code>'s <code>extract</code> (one call returns your schema's fields,\neach cited) instead of chunking the whole document for open-ended retrieval. Reach for this\nskill when retrieval is open-ended (semantic search over the whole document), not when the\ntarget fields are already known. Not for vector-store upsert or embedding generation — this\nskill stops at the chunk JSONL.</p>\n<h2>Dependency: <code>document-extraction-api</code></h2>\n<p>This skill calls <code>document-extraction-api</code> under the hood. <strong>Read that skill first</strong> for mode\nselection, key setup, and credit-cost guidance. <code>chunk.py</code> reuses its <code>create_client()</code> helper\nand <code>client.parse(..., output_format=\"spatial\")</code> call — it does not re-implement the API call.</p>\n<p>The extraction skill must be present in the same plugin at\n<code>../document-extraction-api/scripts/</code>. If it lives elsewhere, set <code>PARSE_SCRIPT_PATH</code> to its\n<code>scripts/</code> directory; <code>chunk.py</code> fails fast with a clear message if it cannot find it.</p>\n<h2>Setup</h2>\n<p>DWS Extract is a separate product from DWS Processor and has its own API key.</p>\n<ul>\n<li>Get a Nutrient DWS Extract API key at <a href=\"https://dashboard.nutrient.io/\">https://dashboard.nutrient.io/</a>.</li>\n<li>Export it as <code>NUTRIENT_EXTRACT_API_KEY</code>:\n<pre><code>export NUTRIENT_EXTRACT_API_KEY=\"pdf_live_...\"\n</code></pre>\n</li>\n<li>Run from the directory containing this SKILL.md:\n<pre><code>cd &lt;directory containing this SKILL.md&gt; &amp;&amp; uv run scripts/chunk.py --help\n</code></pre>\n</li>\n</ul>\n<p>If your tenant has migrated to global DWS API keys, a single key set as either\n<code>NUTRIENT_EXTRACT_API_KEY</code> or <code>NUTRIENT_API_KEY</code> works for both products.</p>\n<h2>Mode selection</h2>\n<p>Mode selection for this skill follows the <strong>same rules as <code>document-extraction-api</code></strong> (mode →\ncost → when to use). Pass <code>--mode</code> through to the parse call; the default is <code>structure</code>.</p>\n<table>\n<thead>\n<tr>\n<th>Mode</th>\n<th>Cost (cr/pg)</th>\n<th>When</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>text</code></td>\n<td>1</td>\n<td>Cheapest; incompatible with spatial — <strong>not usable here</strong> (this skill requires spatial)</td>\n</tr>\n<tr>\n<td><code>structure</code></td>\n<td>1.5</td>\n<td><strong>Default.</strong> OCR + spatial typed elements with bounds and tables</td>\n</tr>\n<tr>\n<td><code>understand</code></td>\n<td>9</td>\n<td>AI layout: <strong>required for <code>keyValueRegion</code> and <code>formula</code> elements</strong></td>\n</tr>\n<tr>\n<td><code>agentic</code></td>\n<td>18</td>\n<td>VLM: adds <code>altDescription</code> on pictures</td>\n</tr>\n</tbody>\n</table>\n<blockquote>\n<p><strong>Mode-gating — important.</strong> <code>keyValueRegion</code> and <code>formula</code> elements are <strong>only populated by\n<code>understand</code> mode or higher</strong>. Under the default <code>structure</code> mode the key-value and formula\nchunk paths produce <strong>nothing</strong>. <code>chunk.py</code> warns on stderr when KV/formula content would be\nexpected but the mode is too low. To exercise key-value chunking, pass <code>--mode understand</code>.</p>\n</blockquote>\n<h2>Invocation</h2>\n<pre><code>uv run scripts/chunk.py --input doc.pdf --out chunks.jsonl \\\n  [--doc-id ID] [--mode structure] \\\n  [--strategy element|reading-order-window|table-row] [--window-size 512] \\\n  [--min-confidence 0.0] [--skip-pictures] [--yes]\n</code></pre>\n<ul>\n<li><code>--out -</code> writes JSONL to stdout; otherwise to the named file (created with <code>0600</code>\npermissions — the JSONL carries extracted document text).</li>\n<li>Credit usage is printed to <strong>stderr</strong> after the parse call.</li>\n</ul>\n<h2>Provenance chunk schema</h2>\n<p>Each JSONL line is one chunk:</p>\n<table>\n<thead>\n<tr>\n<th>Field</th>\n<th>Type</th>\n<th>Source</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>chunk_id</code></td>\n<td>string</td>\n<td>deterministic — see below</td>\n</tr>\n<tr>\n<td><code>doc_id</code></td>\n<td>string</td>\n<td><code>--doc-id</code> or content hash of input bytes (never the basename)</td>\n</tr>\n<tr>\n<td><code>source_doc</code></td>\n<td>string</td>\n<td>input basename, <strong>display-only</strong></td>\n</tr>\n<tr>\n<td><code>element_type</code></td>\n<td>string</td>\n<td><code>paragraph</code>, <code>table</code>, <code>table_row</code>, <code>key_value_pair</code>, <code>formula</code>, <code>picture</code>, <code>handwriting</code></td>\n</tr>\n<tr>\n<td><code>page_index</code></td>\n<td>int|null</td>\n<td><code>element.page.pageIndex</code> (null when the element carries no page — never fabricated <code>0</code>)</td>\n</tr>\n<tr>\n<td><code>reading_order</code></td>\n<td>int|null</td>\n<td><code>element.readingOrder</code> (null sorts last)</td>\n</tr>\n<tr>\n<td><code>bbox</code></td>\n<td>object|null</td>\n<td><code>{x, y, width, height}</code> (normalized at runtime — see OQ-1; null when bounds are missing, never <code>{0,0,0,0}</code>)</td>\n</tr>\n<tr>\n<td><code>confidence</code></td>\n<td>float|null</td>\n<td>element-level <code>confidence</code> (0–1); null when unknown</td>\n</tr>\n<tr>\n<td><code>text</code></td>\n<td>string</td>\n<td>element text per type-dispatch rules</td>\n</tr>\n<tr>\n<td><code>chunking_warning</code></td>\n<td>string?</td>\n<td>present <strong>only</strong> on table span-expansion fallback chunks</td>\n</tr>\n</tbody>\n</table>\n<p><strong><code>chunk_id</code></strong> is deterministic: <code>{doc_id}__p{page_index}_r{reading_order}_e{element_index}{disc}</code>.</p>\n<ul>\n<li><code>_e{element_index}</code> (the element's position in the <code>(page_index, reading_order)</code> sort)\nguarantees <strong>inter-element</strong> uniqueness even when <code>reading_order</code> is <code>null</code> or shared by two\nelements.</li>\n<li><code>{disc}</code> is the <strong>intra-element</strong> discriminator for elements that emit multiple chunks:\n<code>_tr{row}</code> (table-row), <code>_kv{pair_index}</code> (key-value pairs), <code>_w{window_index}</code>\n(reading-order windows); empty for single-chunk elements.</li>\n<li><code>doc_id</code> is <code>--doc-id</code> if supplied, else a short content hash of the input bytes — <strong>never the\nbasename</strong>, so two same-named files in different directories get disjoint IDs and upsert stays\nidempotent and tenant-safe.</li>\n</ul>\n<p>Full spec: <code>references/provenance-chunk-schema.md</code>.</p>\n<h2>Chunking strategies</h2>\n<ul>\n<li><code>--strategy element</code> (<strong>default</strong>): one chunk per typed spatial element — the purest expression\nof the grounding value prop. A <code>table</code> becomes one whole-table TSV chunk.</li>\n<li><code>--strategy table-row</code>: each table row becomes its own chunk (<code>_tr{row}</code>) — better precision on\nwide financial tables.</li>\n<li><code>--strategy reading-order-window</code>: sliding window over reading-order-sorted text elements\n(<code>--window-size</code> in tokens, <code>_w{window_index}</code>) — better retrieval coherence for prose, at some\nprovenance precision (a window may span two elements' bboxes).</li>\n</ul>\n<h2>Cost gate</h2>\n<p><code>chunk.py</code> runs its <strong>own</strong> preflight before the network call: it counts the input PDF's pages\nlocally and estimates <code>pages × mode-cost</code>. If the estimate exceeds <strong>200 credits</strong> (or the API's\n<code>remainingCredits</code> when known), it refuses to proceed unless <code>--yes</code> is passed or interactive\nconfirmation is given. (The extraction skill's 200-credit rule is an agent instruction, not\nenforceable code — this gate is real code here.) For non-PDF inputs where local page count is\nunavailable, the gate requires <code>--yes</code> for <code>understand</code>/<code>agentic</code> runs.</p>\n<h2>Illustrative: passing chunks to an embedder</h2>\n<p>The boundary is the chunk schema. See <code>examples/embed-chunks-illustrative.py</code> for a minimal,\n<strong>illustrative-only</strong> example of loading the JSONL and passing <code>text</code> to an embedder while\nkeeping <code>chunk_id</code> + <code>bbox</code> + <code>page_index</code> provenance attached to each embedding record. Swap the\nprovider import for your stack — no embedding library is a dependency of this skill.</p>\n<h2>Anti-patterns</h2>\n<ul>\n<li>Do <strong>not</strong> use this skill when raw Markdown is sufficient — use <code>document-extraction-api</code> with\n<code>--output-format markdown</code>.</li>\n<li>Do <strong>not</strong> bundle vector-DB or embedding-provider logic into <code>chunk.py</code> — the boundary is the\nchunk JSONL.</li>\n<li>Do <strong>not</strong> expect key-value or formula chunks under the default <code>structure</code> mode — they require\n<code>--mode understand</code>.</li>\n<li>Do <strong>not</strong> derive <code>doc_id</code> from the filename basename — it breaks cross-document collision\nsafety (R15).</li>\n</ul>\n<h2>Security Hardening Addendum</h2>\n<ul>\n<li>Never store <code>NUTRIENT_EXTRACT_API_KEY</code> in committed files. Use process env injection at runtime\n(shell/export, secrets manager, or host env).</li>\n<li>The output JSONL carries extracted document text (potentially finance/health/legal content) and\nis written with <code>0600</code> permissions. Treat it as sensitive; do not commit it.</li>\n<li><code>source_doc</code> carries the input basename, which may encode PII (e.g. <code>patient-jsmith.pdf</code>). For\nsensitive corpora, supply a sanitized <code>--doc-id</code> and be deliberate about what reaches the index.</li>\n<li>The script prints credit usage (the numeric cost only) to stderr and never logs the API key.</li>\n</ul>\n<h2>Rules</h2>\n<ul>\n<li>Always require spatial output — Markdown output loses provenance and is rejected.</li>\n<li>Preserve the printed credit-usage summary so the operator can observe per-call cost.</li>\n<li>Reuse <code>document-extraction-api</code>'s <code>create_client()</code> and <code>client.parse()</code>; do not re-implement\nthe API call or mode-selection logic.</li>\n</ul>\n<h2>Reference map</h2>\n<ul>\n<li><code>references/provenance-chunk-schema.md</code> — authoritative chunk schema, <code>chunk_id</code> derivation,\nchunking strategies, table span-expansion, key-value mapping.</li>\n<li><code>examples/embed-chunks-illustrative.py</code> — illustrative embedding snippet (not a supported script).</li>\n<li>Sibling <code>document-extraction-api/SKILL.md</code> — mode selection, credit costs, key setup.</li>\n</ul>\n","files":[{"path":"examples/embed-chunks-illustrative.py","sizeBytes":1950,"isText":true},{"path":".gitignore","sizeBytes":19,"isText":false},{"path":"references/provenance-chunk-schema.md","sizeBytes":6355,"isText":true},{"path":"scripts/chunk.py","sizeBytes":26096,"isText":true},{"path":"scripts/test_chunk.py","sizeBytes":14322,"isText":true},{"path":"SKILL.md","sizeBytes":11665,"isText":true},{"path":"tests/fixtures/make_sample.py","sizeBytes":1804,"isText":true},{"path":"tests/fixtures/sample.pdf","sizeBytes":2021,"isText":false}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"notes-only","suspicious":0,"notes":2,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-11-29T00:45:09.119026Z","sha256":"BCE85F27B08170BF43751F986CED68516AB0109846B7582F7DE9DD047F5AE480","sizeBytes":24305},"review":null,"source":{"repositoryUrl":"https://github.com/PSPDFKit-labs/nutrient-skills","path":"plugins/nutrient-dws/skills/grounded-rag-ingestion","license":null,"commit":"83aea52a003a4ebb69fcf78ea724b48cbe950835","subtreeSha":"DAC4A8585593A2998732C622B7F1FE5A7985F586025428A7B4382C174EEAFBAC","lastSyncedAt":"2026-11-29T00:42:56.729498Z"},"reviewedAt":"2026-11-29T00:50:35.724208Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/PSPDFKit-labs/nutrient-skills/tree/main/plugins/nutrient-dws/skills/grounded-rag-ingestion"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install pspdfkit-labs-nutrient-skills@llmmart"},{"target":"git","command":"git clone https://github.com/PSPDFKit-labs/nutrient-skills.git"}]}