This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /guides/dws-data-extraction/examples/build-rag-ingestion-pipeline.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. Build a RAG ingestion pipeline with the Data Extraction API

Build a Python pipeline for retrieval-augmented generation (RAG) that answers questions about your PDFs using a large language model (LLM).

The Data Extraction API converts PDFs to Markdown. For conversion examples, refer to the PDF-to-Markdown API overview page. The pipeline splits the Markdown into chunks, generates embeddings, and stores them for retrieval.

What you’ll build

The Python command-line interface (CLI) performs these tasks:

  1. Extracts Markdown from PDFs with the Data Extraction API.
  2. Splits the Markdown at heading boundaries.
  3. Generates embeddings with OpenAI.
  4. Stores embeddings in Chroma.
  5. Answers questions with Claude using retrieved sections as context.

Why use the Data Extraction API for RAG

The Data Extraction API returns Markdown for chunking and retrieval. Choose a processing mode based on the document’s layout.

This tutorial uses text mode for born-digital PDFs. Use understand mode for complex layouts, tables, and formulas.

The pipeline uses document structure to:

  • Split content at heading boundaries.
  • Store each chunk with its source filename and section title.
  • Retrieve sections as context for the LLM.

Prerequisites

Prepare the following tools and credentials:

  • Python 3.10 or later.
  • A Nutrient DWS account and Data Extraction API key. Sign up through the Nutrient account dashboard(opens in a new tab).
  • An OpenAI API key for embeddings.
  • An Anthropic API key for Claude.

To use Voyage, Cohere, or a local embedding model, replace the OpenAI integration. To use OpenAI for answers, replace the Anthropic integration.

Project setup

Run these commands to create the project directory, activate a virtual environment, and install dependencies:

Terminal window
mkdir pdf-rag-data-extraction && cd pdf-rag-data-extraction
python -m venv .venv && source .venv/bin/activate
pip install requests chromadb openai anthropic python-dotenv tqdm

Create a .env file:

Terminal window
NUTRIENT_API_KEY=your_data_extraction_api_key_here
OPENAI_API_KEY=your_openai_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here

Create the files and directories shown in this layout:

pdf-rag-data-extraction/
├─ .env
├─ pdfs/ # Drop your PDFs here
├─ ingestion/
│ ├─ extract.py # PDF → Markdown via Data Extraction API
│ ├─ chunk.py # Markdown → chunks
│ ├─ embed.py # Chunks → vectors
│ └─ store.py # Vectors → Chroma
├─ retrieval/
│ └─ ask.py # Query → top-k context → LLM answer
└─ run.py # End-to-end CLI

Step one — Extract Markdown from PDFs

The Data Extraction API accepts a file upload and returns Markdown when output.format is "markdown":

ingestion/extract.py
import os
import pathlib
import requests
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["NUTRIENT_API_KEY"]
ENDPOINT = "https://api.nutrient.io/extraction/parse"
def pdf_to_markdown(pdf_path: pathlib.Path) -> str:
"""Convert a single PDF to Markdown via the Data Extraction API."""
with open(pdf_path, "rb") as f:
response = requests.post(
ENDPOINT,
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": f},
data={
"instructions": '{"mode":"text","output":{"format":"markdown"}}'
},
)
response.raise_for_status()
result = response.json()
return result["output"]["markdown"]
if __name__ == "__main__":
pdf = pathlib.Path("pdfs/sample.pdf")
md = pdf_to_markdown(pdf)
print(md[:500])

The function reads the Markdown string from output.markdown in the JSON response.

The same request handles .xlsx files. Each visible sheet becomes a level-one heading. The chunking function in step two uses these headings to separate sheets.

Step two — Chunk by heading

The chunking function splits Markdown at heading boundaries. It divides sections longer than 1,800 characters into smaller chunks. Each chunk holds at most 1,800 characters, or about 450 tokens:

ingestion/chunk.py
import re
HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$", re.MULTILINE)
def split_by_heading(md: str, max_chars: int = 1800) -> list[dict]:
"""Split Markdown into chunks at heading boundaries."""
headings = list(HEADING_RE.finditer(md))
if not headings:
return [
{"title": "(untitled)", "text": md[i : i + max_chars]}
for i in range(0, len(md), max_chars)
]
sections = []
for i, h in enumerate(headings):
end = headings[i + 1].start() if i + 1 < len(headings) else len(md)
title = h.group(2).strip()
body = md[h.end() : end].strip()
sections.append({"title": title, "body": body})
chunks = []
for s in sections:
text = f"# {s['title']}\n\n{s['body']}"
for i in range(0, len(text), max_chars):
chunks.append({"title": s["title"], "text": text[i : i + max_chars]})
return chunks

Step three — Generate and store embeddings

Use OpenAI’s text-embedding-3-small for embeddings and Chroma for local vector storage:

ingestion/embed.py
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
def embed(texts: list[str]) -> list[list[float]]:
response = client.embeddings.create(
model="text-embedding-3-small", input=texts
)
return [d.embedding for d in response.data]
ingestion/store.py
import chromadb
client = chromadb.PersistentClient(path=".chroma")
collection = client.get_or_create_collection("pdf-rag")
def upsert(ids, docs, metas, embeddings):
collection.upsert(
ids=ids, documents=docs, metadatas=metas, embeddings=embeddings
)

To use Pinecone, pgvector, Weaviate, or Qdrant, replace the storage implementation in store.py. Keep the upsert interface unchanged.

Step four — Connect the pipeline

Create run.py to process PDFs and spreadsheets through extraction, chunking, embedding, and storage:

run.py
import hashlib
import pathlib
from tqdm import tqdm
from ingestion.chunk import split_by_heading
from ingestion.embed import embed
from ingestion.extract import pdf_to_markdown
from ingestion.store import upsert
def ingest(folder: str = "pdfs") -> None:
for input_doc in [
*pathlib.Path(folder).glob("*.pdf"),
*pathlib.Path(folder).glob("*.xlsx"),
]:
md = pdf_to_markdown(input_doc)
chunks = split_by_heading(md)
ids = [
hashlib.sha1(f"{input_doc.name}-{i}".encode()).hexdigest()
for i in range(len(chunks))
]
docs = [c["text"] for c in chunks]
metas = [
{"source": input_doc.name, "section": c["title"]} for c in chunks
]
for i in tqdm(range(0, len(docs), 64), desc=input_doc.name):
batch = slice(i, i + 64)
upsert(
ids=ids[batch],
docs=docs[batch],
metas=metas[batch],
embeddings=embed(docs[batch]),
)
if __name__ == "__main__":
ingest()

Step five — Retrieve sections and generate answers

The retrieval function selects the closest matching chunks from Chroma. It sends those chunks to Claude with instructions to cite source sections:

retrieval/ask.py
import os
import sys
import anthropic
import chromadb
from ingestion.embed import embed
llm = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
collection = chromadb.PersistentClient(path=".chroma").get_or_create_collection(
"pdf-rag"
)
def ask(question: str, k: int = 6) -> str:
q_embedding = embed([question])[0]
res = collection.query(query_embeddings=[q_embedding], n_results=k)
docs = res["documents"][0]
sources = [
f"{m['source']} — {m['section']}" for m in res["metadatas"][0]
]
context = "\n\n---\n\n".join(docs)
msg = llm.messages.create(
model="claude-sonnet-4-6",
max_tokens=800,
messages=[
{
"role": "user",
"content": (
"Answer the question using only the context. "
"Cite sources by section name when relevant.\n\n"
f"CONTEXT:\n{context}\n\nQUESTION: {question}"
),
}
],
)
return msg.content[0].text + "\n\nSources:\n" + "\n".join(sources)
if __name__ == "__main__":
print(ask(sys.argv[1]))

Run the pipeline

Run ingestion before asking a question about the stored documents:

Terminal window
python run.py
python -m retrieval.ask "What does this document say about termination?"

Production considerations

Review these changes before using the pipeline in production:

  • Cache extraction — Hash PDF bytes to detect unchanged files. Skip extraction when the hash hasn’t changed.
  • Choose a processing mode — Use text mode for born-digital PDFs. Use understand mode to extract formatting, tables, and formulas from complex layouts.
  • Extract spatial data — Use output.format: "spatial" for bounding boxes or table cells. For an example, refer to the document extraction pipeline guide.
  • Evaluate results — Track retrieval hit rate and answer correctness after each pipeline change.
  • Handle multilingual documents — Set options.language for non-English PDFs. Refer to the multilingual extraction guide.

Compare the Data Extraction API and DWS Processor for RAG

Both APIs return Markdown. The Data Extraction API also provides spatial elements and layout analysis for complex documents:

FeatureData Extraction APIDWS Processor
EndpointPOST /extraction/parsePOST /build
Markdown outputYes (output.format: "markdown")Yes (output.type: "markdown")
Structured spatial elementsYes (output.format: "spatial")No
Layout analysisFull segmentation + AI augmentation (understand)Born-digital extraction
Best forComplex documents, mixed workflows (Markdown + spatial)Born-digital PDFs, Markdown-only pipelines