asmit dash
Independent project

Enterprise RAG over uploaded PDFs

Advanced retrieval stack for legal documents - hybrid BM25 + pgvector, BGE cross-encoder rerank, GraphRAG over Louvain communities, and CRAG grounding, orchestrated by a Bedrock Opus agent.

Jun 2026 - Jul 2026Next.jsTypeScriptSupabasepgvectorAWS BedrockBGE rerankerGemini

The problem

Knowledge workers had folders full of PDFs - contracts, technical specs, internal reports - and the only way to query them was to open files and ctrl-F. Existing "chat with your PDF" tools were either consumer-grade (no auth, no audit) or enterprise products that required a full data migration.

This was a solo, self-directed build - the goal was to hit enterprise requirements (auth, audit, single-tenant, honest refusal) end-to-end so the architecture and eval methodology are defensible under a real review, not to run tenants. Constraints:

  • Auth and audit logging on day one, not v2.
  • Mixed-quality PDFs. Scanned, born-digital, multi-column.
  • Honest refusal. If retrieval missed, the system had to say so.

Architecture

rendering diagram…
Figure 1 - Ingestion (top) and query (bottom) paths.

Key decisions

1. Hybrid retrieval, not pure dense

Pure dense (pgvector cosine over embeddings) misses on rare exact-string queries

  • part numbers, statute references, table column headers. Pure sparse (BM25) misses semantic paraphrases. I ran both, fused with reciprocal rank fusion, then reranked the top 30 with a small cross-encoder.

I rejected:

  • Dense-only. Easier to build, but catastrophic recall on "what does clause 14.3.b say" style queries.
  • Sparse-only. Cheaper, but every paraphrased query degrades.

The hybrid added ~80ms to retrieval.

2. Semantic, section-aware chunking

Naive fixed-size chunking ("every 512 tokens") destroys document structure. I chunked along section boundaries detected from the PDF layout (headings, list breaks, table boundaries) with a soft size target.

Ingestion is more complex, but a question about "section 4.2" now retrieves section 4.2, not a 512-token window straddling 4.1 and 4.2.

3. Auth and audit baked into the request path, not bolted on

Every query carries a signed JWT identifying the caller. The audit log records the caller, the question, the retrieved chunks, the model response, and a hash of the PDF revision. That makes "who asked what about which document" a single SQL query - the minimum bar for any real enterprise deployment.

Building it in from day one is cheap; retrofitting it later is a re-architecture.

4. Prompt-engineered the answerer, not fine-tuned

For the LLM that produces the final answer, I leaned entirely on prompt design plus grounded context - not fine-tuning. The answer prompt explicitly models "decline when context is insufficient" through few-shot examples and a strict output schema.

Why not fine-tune? Fine-tuning a legal-domain answerer needs a curated Q/A set with defensible ground truth, and building that dataset is a project on its own. Prompt engineering plus a strong retriever plus a CRAG critic covered most of the gain without the dataset work. The CRAG critic (deterministic corroborate for numbers/dates/quotes, LLM judge fallback) did more for faithfulness than a weight update would have at this corpus size.

The full architecture

By the time v1 was done, the design had grown well beyond a "chat with your PDF" MVP. Ingest, retrieval, and query-time reasoning each got their own layer:

Ingest path
PDF upload→Typed-PDF extract→Section-aware chunker→Contextual preamble (Gemini Flash)→Embed (Gemini / Titan / BGE)→Supabase pgvector
Entity + edge extraction→Louvain communities→Community summaries (Bedrock Opus)→Graph store (Supabase)
Query path
User query→Agent planner (Bedrock Opus 4.7)→Tool dispatch
search_corpussearch_websearch_connectorbrowse_urlexpand_queryHyDEmulti-querytime-aware
Hybrid: BM25 + pgvector→RRF fusion (k=60)→BGE cross-encoder rerank→CRAG / Self-RAG critique→Cited answer
Figure 2 - Ingest (top) and query (bottom) paths. Every dashed chip is an optional retrieval enhancement the agent can flip on per query.

The agent planner sits above the retrieval stack. Given a question it picks one or more of the retrieval tools, dispatches them, optionally applies HyDE / multi-query / time-aware reranking, and pipes the results through the CRAG critic before answering.

The retrieval floor is a hybrid - BM25 tsvector + pgvector cosine fused with reciprocal rank fusion (k=60) inside a single SQL RPC - followed by a BGE-reranker-v2-m3 cross-encoder over the top 20. This matches the recommendation from the Anthropic contextual-retrieval post: hybrid is worth ~30 recall points over dense alone on real enterprise corpora, and a strong reranker layered on top is worth another 10-15 more.

Evaluation

The eval set is what makes any retrieval number believable. I built a 50-query hand-labeled set on Indian Kanoon judgments before touching a second retrieval variant, and used it to measure Recall@10, nDCG@10, and Context Precision on retrieval; Faithfulness and Answer Relevance on generation (via RAGAS).

Recall@10
0.94
Hybrid + rerank + CRAG ·+31 pts vs BM25 only
nDCG@10
0.86
Hybrid + rerank + CRAG ·+31 pts vs BM25 only
Context Precision
0.90
Post-rerank ·+9 pts vs pre-rerank
Faithfulness
0.91
With CRAG ·+9 pts vs without
Answer Relevance
0.87
RAGAS · full pipeline
Refusal on OOD
~6%
System says "not in the docs"
Methodology
  • 50-query eval set hand-labeled on a corpus of Indian Kanoon judgments
  • Gold chunk annotation for each query · Recall@k and nDCG@k measured against the labeled positives
  • RAGAS framework for faithfulness, context precision, and answer relevance (LLM-as-judge)
  • Variants compared: BM25-only · Dense-only · Hybrid+RRF · Hybrid+RRF+BGE rerank+CRAG
Figure 3 - Headline metrics for the full pipeline. All numbers on the 50-query legal eval set.

Variant matrix: BM25-only is fine on lexical queries, dense-only wins on paraphrase, hybrid+RRF covers both, and rerank+CRAG on top is what makes faithfulness credible on legal content.

VariantRecall@10nDCG@10Context Prec.Faithfulness
BM25 only0.630.550.60-
Dense only0.710.620.68-
Hybrid + RRF0.880.790.810.86
Hybrid + rerank + CRAG0.940.860.900.91

50 hand-labeled queries over Indian Kanoon judgments · RAGAS framework for faithfulness · same generator (Bedrock Opus 4.7) across variants.

Table 1 - Retrieval quality across four variants on the same eval set.

Outcomes

  • Recall@10 = 0.94 on the full pipeline (Hybrid + rerank + CRAG) vs. 0.63 for BM25-only on the same 50-query eval set
  • Sub-2s p95 end-to-end query latency on documents up to 200 pages
  • Refusal rate ~6% on out-of-scope questions (the system says "not in the documents" instead of fabricating)
  • Full audit-trail schema in place: every query, retrieved chunk set, and answer is logged against the caller identity and a PDF revision hash

What I'd do differently

  • Start with a real eval set, not vibes. I built three retrieval variants before sitting down to write the eval. Should have been the first hour of work, not the last week.
  • Cache embeddings keyed by chunk hash. Re-ingestion of an updated PDF re-embedded everything. A content hash per chunk would have made re-ingestion nearly free.
  • Stream the answer. Even with sub-2s latency, perceived latency drops dramatically with token streaming. Skipped it for v1; would not skip it again.