Project 08 · AI data pipeline

RAG Data Pipeline

An assistant can only answer from what it can find. This pipeline keeps a vector index in step with six document sources: product docs, support tickets, policies, the engineering wiki, release notes and FAQs. Every hour Airflow finds new, changed and deleted documents, LangChain loaders and splitters turn them into overlapping chunks with metadata, an embedding model turns the chunks into vectors, and Pinecone stores them in one namespace per source. Each night 500 labelled questions check that the right passage still comes back.

  • Python
  • Apache Airflow
  • LangChain
  • Pinecone
  • PostgreSQL
Sample data Last 30 days · Sep 7 – Oct 6, 2026 Download data (CSV)

Document changes per day

Detected at the sources and applied to the index

Documents by source

One Pinecone namespace each

Retrieval latency

Query embedding plus vector search

Retrieval quality by namespace

500 labelled questions, Oct 6

Chunk sizes

Tokens per chunk; the target is 512

Index namespaces

Pinecone index kb-prod

Sample retrievals from the eval set

Top result for each question and where the right passage ranked

How it works

Ingest → chunk → embed → index → evaluate, incrementally, every hour.

  1. 01 · Detect

    Airflow + source APIs

    Every hour, list documents changed since the last run in each source, by modified time and content hash.

  2. 02 · Load

    LangChain loaders

    Confluence, Zendesk, Markdown docs and PDFs become text plus metadata: source, URL, title, access group, updated date.

  3. 03 · Chunk

    Recursive splitter

    About 512-token chunks with a 64-token overlap, split on headings and paragraphs first so chunks stay coherent.

  4. 04 · Embed

    Embedding model

    1,536-dimension vectors, 256 chunks per request, with retries and a token budget per run.

  5. 05 · Index

    Pinecone

    One namespace per source. Vector ids are doc_id#chunk, so updates overwrite and deletes are exact.

  6. 06 · Evaluate

    Nightly eval

    500 labelled questions measure recall@5 and MRR per namespace; a drop alerts the team.

  • Only changed documents are re-embedded. A content hash per document skips unchanged ones, which keeps embedding cost under a dollar a day.
  • Deletes are first-class. When a document is deleted or archived at the source, its chunk ids are removed from Pinecone in the same run, so the assistant never cites a retired policy.
  • Metadata does the filtering. Every vector carries its source, access group and updated date, so search can be limited to what a user is allowed to see before ranking.
  • Quality is measured, not assumed. Retrieval is scored every night against labelled questions. A chunking or model change ships only if recall@5 does not drop.

Data model

A manifest in PostgreSQL tracks every document so only changed ones are re-embedded; Pinecone holds the vectors.

kb.documentsPostgreSQL · the manifest
doc_idtext
Stable id from the source system
source / url / titletext
Where it lives
content_hashchar(64)
SHA-256 of the text; unchanged means skip
chunk_countint
How many vectors the document has
updated_at / deleted_attimestamptz
From the source
last_indexed_attimestamptz
When the index last matched this version
kb-prodPinecone index · 1,536 dims · cosine
idstring
doc_id#chunk_no
valuesfloat[1536]
The embedding
metadata.doc_id / title / urlstring
Used for citations
metadata.access_groupstring
Filter so users only see what they may read
metadata.updated_atstring
Lets the assistant prefer recent content
metadata.textstring
The chunk itself, returned with matches
ingestion_dailyRollup · the CSV download
datedate
Day
docs_added / docs_updated / docs_deletedint
Changes found at the sources
chunks_upserted / embedding_tokensint
Work done
embedding_cost_usddecimal
Tokens × price
retrieval_p50_ms / p95_ms / recall_at_5int / double
Search speed and quality

Key code

Incremental indexing, the hourly DAG, and the nightly retrieval evaluation.

Incremental indexing: skip unchanged documents, upsert new chunks, and delete chunks a shorter version no longer has.

import hashlib

from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from pinecone import Pinecone

splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
    encoding_name="cl100k_base",
    chunk_size=512,
    chunk_overlap=64,
    separators=["\n## ", "\n### ", "\n\n", "\n", ". ", " "],
)
embeddings = OpenAIEmbeddings(model="text-embedding-3-large", dimensions=1536, chunk_size=256)
index = Pinecone().Index("kb-prod")  # reads PINECONE_API_KEY


def index_document(doc, manifest) -> int:
    """Index one document if it changed. Returns the number of chunks written."""
    meta = doc.metadata
    digest = hashlib.sha256(doc.page_content.encode("utf-8")).hexdigest()
    previous = manifest.get(meta["doc_id"])
    if previous and previous.content_hash == digest:
        return 0  # unchanged: no embedding cost

    chunks = splitter.split_documents([doc])
    vectors = embeddings.embed_documents([c.page_content for c in chunks])
    records = [
        {
            "id": f"{meta['doc_id']}#{n}",
            "values": vector,
            "metadata": {
                "doc_id": meta["doc_id"],
                "title": meta["title"],
                "url": meta["url"],
                "access_group": meta["access_group"],
                "updated_at": meta["updated_at"],
                "chunk_no": n,
                "text": chunk.page_content,
            },
        }
        for n, (chunk, vector) in enumerate(zip(chunks, vectors))
    ]
    for start in range(0, len(records), 100):
        index.upsert(vectors=records[start:start + 100], namespace=meta["source"])

    # A shorter new version leaves old chunks behind; remove them.
    if previous and previous.chunk_count > len(chunks):
        stale = [f"{meta['doc_id']}#{n}" for n in range(len(chunks), previous.chunk_count)]
        index.delete(ids=stale, namespace=meta["source"])

    manifest.save(meta["doc_id"], content_hash=digest, chunk_count=len(chunks))
    return len(chunks)


def remove_document(doc_id: str, source: str, chunk_count: int) -> None:
    index.delete(ids=[f"{doc_id}#{n}" for n in range(chunk_count)], namespace=source)

Engineering notes

The policy reorganisation

On Sep 15 HR restructured the policy handbook and about 2,100 documents changed in one afternoon. Only those were re-embedded, about 54K chunks for roughly three dollars, and the old chunks were deleted in the same run.

Smaller chunks, better answers

Moving from 1,000-token chunks to 512 tokens with heading-aware splitting raised recall@5 on the eval set from 0.86 to 0.91.

Fast enough to feel instant

Retrieval takes about 170 ms at p95, including embedding the question, inside the assistant's 250 ms budget. Sep 22 came close during an index scale-up.

Support tickets need more

The support namespace has the lowest recall, 0.84, because tickets are short and repetitive. The next step is hybrid search that also matches product names and error codes as keywords.

About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as ingestion_daily.csv or read data.json.