All projects
AI2026In Progress

Hybrid RAG

A layout-aware PDF ingestion pipeline that recovers document structure, then serves it over MCP so agents and humans query the same index.

Role

Solo engineer — architecture, implementation, and evaluation

Built with

  • Python
  • FastAPI
  • pdfplumber
  • pypdfium2
  • BGE-M3
  • Qdrant
  • +6 more
Hybrid RAG retrieval interface showing document search results over the ingested PDF index

The Problem

What needed to be solved

PDFs are easy to parse but hard to understand. Naive text extraction destroys the document's structure — headings vanish into body text, multi-column layouts get interleaved, tables become garbage, rotated stamps disappear, and headers and footers pollute every chunk. Any RAG system built on top of that extraction is unreliable, and the failures are invisible because the pipeline has no idea it made a mistake.

Context

Why it was built this way

Retrieval quality is decided upstream of the model. If the chunk that should have been retrieved was never built correctly, no amount of prompt engineering or reranking recovers it. So the work had to happen at the layout layer, explicitly and stage by stage — treating structure as something to be recovered and preserved rather than something to be scraped away. The second half of the problem is access: the same index has to be usable by a person reading a chat answer and by an agent calling tools, without maintaining two systems.

Approach

How I built it

  1. 01

    Split ingestion into a stage plan — load, extract, preprocess, chunk, index, evict — with one runner behind every front door. The HTTP route, the CLI, a background job worker, and an MCP tool all call the same engine, so none of them can drift from what the others do.

  2. 02

    Recover layout rather than flatten it: detect vertical gutters with a sweep-line algorithm to find column separators, then build lines using an open-line pool with cross-axis overlap and column zoning, so a word merges into any open line rather than only the latest one.

  3. 03

    Establish reading order with band segmentation — full-width lines delimit horizontal bands, and inside each band content is emitted column-major. This beats global topological sorting on multi-column pages.

  4. 04

    Learn each document's own typography instead of assuming a size hierarchy. Line roles come from a per-document signature of quantized size and font-family weight, with color carried as metadata only, because on colorful documents the same role appears in many colors and the same color appears in many roles.

  5. 05

    Replace table and image regions with [TABLE:x] and [IMAGE:y] marker lines so entities flow through the rest of the pipeline as first-class lines and can be cited back to their page and region.

  6. 06

    Chunk in two levels: a section per h1/h2 boundary as the retrieval parent, and token-sized chunks as the retrieval unit. A matched chunk hands its section to the model, so an answer is never written from a fragment.

  7. 07

    Embed with BGE-M3, which produces a 1024-dim dense vector and a sparse lexical-weight vector in a single model pass, and index both into one Qdrant collection using named vectors.

  8. 08

    Serve retrieval over MCP with a dense + sparse prefetch fused by RRF, alongside tools to ingest, index, and inspect documents — so an agent can use the index with the same fidelity a person gets.

My role

What I was responsible for

  • Designed the ingestion engine and the artifact contract between stages.

  • Implemented the extraction layer — words with font attributes, char-frame recovery for rotated text, page rotation normalization, table detection with cell geometry, and raster image extraction.

  • Built the preprocessing layer — boilerplate removal, gutter detection, line building, entity reference replacement, typographic role classification, and reading-order reconstruction.

  • Designed the per-document typographic signature classifier that assigns heading tiers, bold, and accent roles without hardcoding anything across documents.

  • Implemented two-level chunking with content-addressed identity, so re-ingesting an unchanged document upserts in place instead of leaving orphaned points behind.

  • Built the indexing layer — BGE-M3 embedding, batched encoding, and Qdrant upsert with named dense and sparse vectors.

  • Built the MCP server and its tools — hybrid search with RRF fusion, document listing, metadata inspection, ingest, and index.

  • Added document metadata persistence with SQLAlchemy and Alembic migrations.

  • Wrote the typed YAML configuration layer validated against pydantic models at startup, with eagerly validated runtime overrides.

  • Wrote the test suite running against Qdrant's in-memory mode with a stubbed embedding model — no Docker daemon, GPU, or GB-scale weights required.

Challenges

The hard parts

Font-size heading classification provably fails

On a real guide, body intro text was set at 14pt — the exact size of a section heading. Run-in labels sat at body size with only weight to distinguish them, and link colors were mixed inside a single line with body ink. Size-ratio heuristics would have silently mislabelled headings, so roles had to be learned from each document's own signature instead.

Content-addressed identity to stop orphaned points

Positional chunk ids (c0, c1, c2) meant a document that shrank between runs kept its trailing points forever, with no delete path anywhere in the codebase. Ids are now derived from content, so the index upserts in place and a changed entity gets a new id — which makes staleness detectable rather than silently served.

Best-effort enrichment burning 42 seconds per document

Vision enrichment was attempted whenever AI credentials happened to be present, so a document with images spent 42,374ms producing nothing when the endpoint was unreachable. Making it opt-in and logging skipping distinctly from unconfigured brought extraction of the same file down to 230ms — and made a slow run explainable after the fact.

Runtime config overrides that never worked

set_many drilled to the config root and merged leaf overrides there, then validated the whole tree against the section's leaf model — so every override raised a ValidationError and runtime configuration was entirely dead. Overrides now merge into the addressed section and validate against the assembled config, which rejects the same typos and bad types.

One pipeline, many ways to call it

The HTTP route, the CLI, a job worker, and MCP tools each wanted to chain the stages their own way. Left alone they would have drifted, and an agent-facing tool that behaves differently from the CLI is worse than no tool at all. The engine is now the only place the stages are chained.

Concurrent stage writes clobbering metadata

Every stage writes a summary into the same meta.json. update_meta on the storage backend is now the single sanctioned read-modify-write path, so concurrent stage summaries never overwrite each other.

Decisions

Key technical calls I made

One engine behind every front door

The stages are chained in exactly one place. An HTTP route, a CLI command, a background worker, and an MCP tool are thin wrappers that cannot diverge from each other.

Per-document typography, not global rules

Nothing about a document's hierarchy is assumed. Each document's own size and weight signatures define its body text, and everything else is classified relative to that — which is what lets the same pipeline handle a textbook, a legal statute, and a slide deck.

Color as decoration, not as a role signal

On colorful documents the same role appears in many colors and the same color appears in many roles. Treating color as role evidence produced wrong answers; it is now metadata, and a separate accent role is assigned by dominance instead.

Sections as the retrieval parent

A matched chunk hands its section to the model, so an answer is never written from a fragment. The hierarchy is also the shape a graph store would need later, which makes the move additive rather than a rewrite.

Content-addressed ids

Same document plus same content always yields the same id, so upserts overwrite rather than duplicate and a shrink in chunk count cannot leave orphans behind.

MCP for agent access rather than a bespoke API

Agents get tools with the same fidelity the chat UI will have, and the tool surface is defined once instead of twice. Retrieval runs as a dense and sparse prefetch fused by RRF, so exact identifiers and paraphrase both surface.

JobRunner as a port with an in-process adapter

The engine has no opinion about whether ingestion happens inside an HTTP request or hours later in a worker. Swapping the in-process worker for a durable-execution platform is an adapter change and nothing else.

Enrichment opt-in and degradable

Vision descriptions for tables and images cost a call per unique entity. The pipeline is complete without them, so they are off by default and every failure path falls back to plain reference markers.

Typed config that fails fast

Unknown keys and wrong types raise at startup instead of silently falling back to defaults and producing subtly wrong output.

Gallery

Project in practice

Outcome

Where it landed

The ingestion side is feature-complete: layout recovery works on multi-column, rotated, stamped, and table-heavy pages, chunking is two-level and content-addressed, and indexing produces a hybrid dense + sparse collection. Retrieval works end to end over MCP with RRF fusion, and document metadata persists through SQLAlchemy migrations. The architectural goal — one index, one retrieval path, reachable by both a person and an agent — is in place. What remains is the part a person actually sees.

Roadmap

What comes next

  1. 01

    A chat UI where answers cite the exact region they came from, expanding a citation back to the page and the highlighted lines, with an explicit "cannot ground this" answer path when retrieval does not support a claim.

  2. 02

    Cross-encoder reranking as a layer over hybrid retrieval, applied only where the fused candidates are close enough for reranking to change the answer.

  3. 03

    A retrieval evaluation set over the sample corpus, so changes to chunking and embedding can be measured rather than argued about.

  4. 04

    Graceful degradation for the known hard cases still tracked in the project — table rowspans, code blocks, and cover-page furniture.

The source for this project is private. I'm happy to walk you through the architecture, the decisions behind it, and what I would do differently — get in touch and we'll set something up.

Stack

Built with

PythonFastAPIpdfplumberpypdfium2BGE-M3QdrantMCPSQLAlchemyAlembicPydanticDockerpytest

Keep reading