The Problem: Can You Trust the Answer?
If an AI answers a question about your documents, how do you know it actually read them and didn’t make something up? That question is one of the biggest blockers to using AI at work, especially for things like legal research, medical analysis or any document-heavy job.
I built the XAI Document Research Assistant to answer it: every step of the retrieval-augmented generation (RAG) pipeline is visible and checkable.
Hybrid Retrieval
No single retrieval method works for every kind of question, so the system uses a hybrid search that combines two.
Semantic Search: Finding Concepts
all-MiniLM-L6-v2 embeddings stored in ChromaDB handle meaning. Questions like “What are the key themes in this document?” or “Explain the methodology” get matched to relevant passages by vector similarity.
Keyword Search: Finding Specifics
Semantic search is bad at exact matches: specific IDs, part numbers, rare acronyms. BM25 (Best Matching 25) covers that. It treats the documents like a search engine index, so a query for “model X-17” or “section 4.2(b)” finds the exact passage.
Reranking: Quality Control
Hybrid search can still return 20 or so candidate chunks. FlashRank, a cross-encoder reranker, scores each one against the specific question so only the best context reaches the language model.
The Trust Layer: Faithfulness Scoring
Instead of just trusting the output, every answer gets scored automatically with Ragas:
# The system automatically scores each answer on faithfulness
# High faithfulness (0.95+) means the answer is derived solely from retrieved documents
# Low faithfulness indicates potential hallucination
evaluation = evaluator.evaluate_faithfulness(question, answer, retrieved_chunks)
A score on its own isn’t enough, so I paired it with LangSmith tracing. Every interaction gets a trace URL showing which documents were retrieved, how they were reranked, and what the final answer was. No “trust me, it works.” The evidence is in the trace.
Engineering Challenges
Keeping the Database in Sync
One of the hardest problems was keeping the Streamlit UI and the ChromaDB backend consistent. When a user removed a file from the uploader, its embeddings stayed in the database.
Fix: On every script rerun, compare processed_files with the current uploaded_files and purge anything that was removed:
# Detect deletions and sync database
current_uploaded_names = [f.name for f in uploaded_files] if uploaded_files else []
files_to_remove = [f for f in st.session_state.processed_files if f not in current_uploaded_names]
for file_name in files_to_remove:
st.session_state.rag_app.db.delete_file(file_name)
st.session_state.processed_files.remove(file_name)
The BM25 Index Bug
The sneakiest bug was a “documents don’t match index corpus!” error. After a file was deleted, the chunks cache was updated but the BM25 index still pointed at the old corpus.
Fix: Rebuild the chunks cache and the BM25 index together after every deletion:
# Rebuild both cache and index from remaining documents
leftovers = self.collection.get(include=["documents"], limit=self.collection.count())
self.chunks_cache = leftovers["documents"]
tokenized_chunks = [simple_tokenizer(chunk) for chunk in self.chunks_cache]
self.bm25 = BM25Okapi(tokenized_chunks) if self.chunks_cache else None
Performance
Batch Encoding for Large Documents
Embedding a big document all at once eats memory, so chunks are encoded in batches with a progress bar:
batch_size = 10
total_batches = (len(chunks) + batch_size - 1) // batch_size
for i in range(0, len(chunks), batch_size):
batch_chunks = chunks[i:i+batch_size]
batch_embeddings = np.array(self.model.encode(batch_chunks, normalize_embeddings=True)).tolist()
# Update progress bar for user feedback
update_progress(i // batch_size + 1, total_batches)
One Shared Instance
Multiple RAG instances meant memory bloat and inconsistent state. With @st.cache_resource, the heavy models load once, globally, and are shared across every session and user. Anything per-user (like the list of processed files) lives in st.session_state instead:
@st.cache_resource
def get_rag_app(persist_dir='./db'):
"""Singleton pattern to ensure only one RAGApp instance."""
return RAGApp(persist_dir)
The Audit Trail: LangSmith
Each trace records:
- the HyDE-generated search query
- how many chunks were found and which search method found them
- FlashRank scores and the final selection
- token usage and latency
- the faithfulness score
That’s a full audit trail you can review for compliance, accuracy or performance.
Lessons Learned
State management is where the bugs live. The hard bugs weren’t in the algorithms. They were in keeping UI state, database state and cache state in sync, especially with multiple users.
Make errors specific. “Database error” helps nobody. Tell users what went wrong and what to try.
Show what’s happening. Progress bars, status messages and debug logs aren’t extras. They’re a big part of why people trust a system.
Test the messy workflows. Everything worked with one document. Adding, removing and switching between several documents is where the critical bugs showed up.
From Black Box to Glass Box
With all of this in place, users can check every answer against the source, admins can audit every interaction, and developers can debug from a complete trace. If you’re building RAG for anything high-stakes, I’d treat faithfulness scoring and tracing as part of the core pipeline, not something to add later.
Try the live demo: XAI Document Research Assistant