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.
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
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:
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).
- 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
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.
| Variant | Recall@10 | nDCG@10 | Context Prec. | Faithfulness |
|---|---|---|---|---|
| BM25 only | 0.63 | 0.55 | 0.60 | - |
| Dense only | 0.71 | 0.62 | 0.68 | - |
| Hybrid + RRF | 0.88 | 0.79 | 0.81 | 0.86 |
| Hybrid + rerank + CRAG | 0.94 | 0.86 | 0.90 | 0.91 |
50 hand-labeled queries over Indian Kanoon judgments · RAGAS framework for faithfulness · same generator (Bedrock Opus 4.7) across variants.
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.