Document changes per day
Detected at the sources and applied to the index
Project 08 · AI 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.
Detected at the sources and applied to the index
One Pinecone namespace each
Query embedding plus vector search
500 labelled questions, Oct 6
Tokens per chunk; the target is 512
Pinecone index kb-prod
Top result for each question and where the right passage ranked
Ingest → chunk → embed → index → evaluate, incrementally, every hour.
01 · Detect
Airflow + source APIs
Every hour, list documents changed since the last run in each source, by modified time and content hash.
02 · Load
LangChain loaders
Confluence, Zendesk, Markdown docs and PDFs become text plus metadata: source, URL, title, access group, updated date.
03 · Chunk
Recursive splitter
About 512-token chunks with a 64-token overlap, split on headings and paragraphs first so chunks stay coherent.
04 · Embed
Embedding model
1,536-dimension vectors, 256 chunks per request, with retries and a token budget per run.
05 · Index
Pinecone
One namespace per source. Vector ids are doc_id#chunk, so updates overwrite and deletes are exact.
06 · Evaluate
Nightly eval
500 labelled questions measure recall@5 and MRR per namespace; a drop alerts the team.
A manifest in PostgreSQL tracks every document so only changed ones are re-embedded; Pinecone holds the vectors.
kb.documentsPostgreSQL · the manifestdoc_idtextsource / url / titletextcontent_hashchar(64)chunk_countintupdated_at / deleted_attimestamptzlast_indexed_attimestamptzkb-prodPinecone index · 1,536 dims · cosineidstringdoc_id#chunk_novaluesfloat[1536]metadata.doc_id / title / urlstringmetadata.access_groupstringmetadata.updated_atstringmetadata.textstringingestion_dailyRollup · the CSV downloaddatedatedocs_added / docs_updated / docs_deletedintchunks_upserted / embedding_tokensintembedding_cost_usddecimalretrieval_p50_ms / p95_ms / recall_at_5int / doubleIncremental 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)
Hourly Airflow DAG: one mapped task per source finds changes, indexes them and removes deleted documents.
from datetime import datetime, timedelta
from airflow.decorators import dag, task
from kb.index_documents import index_document, remove_document
from kb.manifest import Manifest
from kb.sources import changed_since, deleted_since, load
SOURCES = ["product_docs", "support_tickets", "policies", "eng_wiki", "release_notes", "faqs"]
@dag(
schedule="@hourly",
start_date=datetime(2026, 1, 1),
catchup=False,
max_active_runs=1,
default_args={"retries": 3, "retry_delay": timedelta(minutes=2)},
tags=["rag", "knowledge-base"],
)
def kb_sync():
@task(max_active_tis_per_dag=3)
def sync_source(source: str, data_interval_start=None) -> dict:
manifest = Manifest(source)
written = 0
for ref in changed_since(source, data_interval_start):
written += index_document(load(ref), manifest)
removed = 0
for doc in deleted_since(source, data_interval_start):
remove_document(doc.doc_id, source, doc.chunk_count)
manifest.mark_deleted(doc.doc_id)
removed += 1
return {"source": source, "chunks_written": written, "documents_removed": removed}
@task
def record_metrics(results: list[dict]) -> None:
from kb.metrics import write_run_metrics
write_run_metrics(results)
record_metrics(sync_source.expand(source=SOURCES))
kb_sync()
Nightly evaluation: recall@5 and mean reciprocal rank on 500 labelled questions, per namespace.
from collections import defaultdict
from kb.index_documents import embeddings, index
def evaluate(questions: list[dict], k: int = 5) -> dict:
"""Each question has text, namespace and the doc_ids that contain the answer."""
hits, reciprocal_ranks, counts = defaultdict(int), defaultdict(float), defaultdict(int)
for q in questions:
result = index.query(
vector=embeddings.embed_query(q["text"]),
top_k=k,
namespace=q["namespace"],
include_metadata=True,
)
ranked = [match.metadata["doc_id"] for match in result.matches]
rank = next((i + 1 for i, doc_id in enumerate(ranked) if doc_id in q["relevant"]), None)
ns = q["namespace"]
counts[ns] += 1
if rank is not None:
hits[ns] += 1
reciprocal_ranks[ns] += 1 / rank
return {
ns: {"recall_at_5": hits[ns] / n, "mrr": reciprocal_ranks[ns] / n, "questions": n}
for ns, n in counts.items()
}
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.
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.
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.
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.