Diligence Lens
Local multi-contract quality-gated RAG pipeline
A locally run Streamlit app that indexes a controlled slice of real commercial contracts, retrieves with hybrid search and a cross-encoder cut, then generates a structured finding only when the evidence pack is strong enough. Citation quotes are checked against retrieved text before they count.
Stack · Python · Streamlit · LangGraph · Qdrant · Ollama · nomic-embed-text · sentence-transformers · rank-bm25 · Google Gemini · Pydantic
The brief
Diligence Lens is a local Streamlit app for multi-contract due diligence style RAG. I am building it as a solo project to deepen my understanding of Retrieval-Augmented Generation.
Current stack uses Python, locally run Ollama for embeddings, Qdrant for the search engine, and Gemini for generation.
Concepts I Explored
The project started as a self-correcting RAG loop: retrieve, grade whether the context is usable, rewrite a failed query once, then answer or abstain. That teaching graph is still present, but I wanted to explore something different after that.
I steered the product toward retrieval quality instead, and focused on exploring concepts like evals, hybrid retrieval and re-ranking. Some concepts explored are as follows:
- Data set : Contract Understanding Atticus Dataset (CUAD) started with first eighty contracts (~eight thousand chunks after a clean rebuild) so scale work stays separate from quality work.
- Chunking: clause and paragraph-aware splits, about 800 characters with 120 overlap, then sentence windows for oversized blocks
- Embedding and store: Ollama
nomic-embed-textinto Qdrant. - Candidate retrieve: dense vector search beside BM25 (
rank-bm25), merged with reciprocal rank fusion (RRF). - Rerank:
cross-encoder/ms-marco-MiniLM-L-6-v2(sentence-transformers) with a hard score threshold. - Pack policy: keep passages with MiniLM
rerank_score≥ 4.0, final evidence limit 8, diversify to at most two chunks per source. An empty pack results ininsufficient_evidenceand skips the generator to reduce token usage. - Augment and generate: LangGraph review graph using
Google Gemini(defaultgemini-3.5-flash-lite) and Pydantic schema for the structured finding - Validate: citation quotes must be exact substrings of retrieved text or they drop. Weak support can force the decision down
- Diagnose failures by where they break (chunking, candidates, rank, pack policy, generation) instead of rewriting the prompt first
- Exact match & Semantic-Caching : Added a caching layer before generation to return hits for semantically similar queries, or direct matches.
The live app emphasizes the gate-and-validate path. Query retry could be added later on.
How it works
Point the app at a data room of contract text. Using the sidebar, build a vector index with batched local embeddings. You can probe dense search for calibration, or run a diligence review.
A review checks caches first. On a miss it runs hybrid retrieval - dense vectors and BM25, fused, then a MiniLM cross-encoder rerank with a hard score threshold and a per-source diversity cap. If nothing clears the cut, the app returns insufficient evidence and skips Gemini.
If a pack remains, Gemini returns a structured finding. Quotes must appear verbatim in the evidence text or they are dropped, and the decision can be forced down when citations cannot support it.
While a review runs, the pipeline stages are visible so you can see which layer is currently running - retrieve, generate, or a cache restore. Exploring the idea of integrating a Human-In-The-Loop (HITL) approval feature, which is present in the code but not integrated yet.
For the frozen eighty-contract dataroom, the evaluation set questions include a hyper-specific questions that should easily return matches, semantically-vague questions to test semantic caching and general retreival cases, irrelevant / insufficient evidence cases and prompt-injection style questions.
Architecture choices
Stack: Python and Streamlit for the portal, LangGraph for the review graph, Qdrant for vectors, Ollama with nomic-embed-text for embeddings, rank-bm25 and sentence-transformers for hybrid retrieve and rerank, Pydantic for the finding schema, Google Gemini for structured generation.
Retrieval quality and evidence policy come before prompt polish. I preferred returning insufficient evidence over false positives.
Dataset: CUAD Atticus Project, CC BY 4.0. Started with a set of 80 documents for testing and development as the full set was a bit too heavy to work with initially.
Weak retrieval: dense-only search struggled when many contracts share the same boilerplate. Hybrid fusion, a cross-encoder cut, and source diversity became the review path.
Generator trust: structured output into a fixed finding schema, then local citation checks. Failed quotes or unsupported conflict shapes get downgraded instead of shipping the raw model claim.
Demo friction: stage-visible review status, session and semantic caches for repeats, and a GEMINI_MODEL env setting so swapping the generator does not need a code edit.
Current state
- Portal with index rebuild, dense evidence search, diligence review, audit trail, and a small quality lab to evaluate behaviour.
- Hybrid retrieve with MiniLM rerank, source diversity, and empty-pack abstention
- Citation validation on structured Gemini findings
- README path for clone, eighty-doc export, index, and smoke questions
- Live stage board during reviews (cache, retrieve, generate, finalize)
Current search after clause-aware chunking metrics:
Recall @ 10 0.90andMean Reciprocal Rank @ 10 0.82on a 10-case set.- Adding BM25 and reciprocal rank fusion brought
MRR@10to about0.73. - MiniLM rerank held
Recall@10 at 0.90andMRR@10 ~ 0.74.
On a larger 30-case probe with rerank score threshold ≥4 and final limit of 8: 17 of 30 questions abstained, 13 of 21 expect-hit packs still held at least one expected source, and all 9 boundary cases abstained properly.
On the portal gemini-3.5-flash-lite lands easy passes in roughly 1–4s retrieve and 3–4s generate. Queries with Lack of evidence skip Gemini calls all-together.
Known limitations
- The eighty-doc slice is great for iteration, but it is not the full dataset, so scale behaviour (embed time, index size, review latency) is still unproven.
- A few hard questions still miss the expected sources entirely or rank it too low in the final sources list.
- The rerank ≥4 cut is deliberately strict- abstains cleanly on surely wrong answers but this risks mid-match true positives.
- Cross-document conflict identification not proven as this iteration does not actually contain paired conflicting instruments yet. Full dataset index not explored yet due to compute limitations.
Future work
Mostly the solutions to those limits, in the same order:
- Grow the dataroom toward the full CUAD set and re-measure embed time, index size, and review latency with the same quality gates.
- For v2 retrieval, dig into the hard misses and late ranks (query rewrite, deeper candidates, or a domain-tuned reranker), measuring before changing global knobs.
- Soften false abstains without dumping it on external models.
- Conflicting documents identification.
- cloud-hosted demo.