1. Project Goal
Build a small local document question-answering system that retrieves evidence before generating an answer, displays source labels and explicitly says when the corpus does not support a response.
2. What You Will Build
3. Skills / Prerequisites
Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.
4. Dataset or Inputs
The runnable corpus uses three short local strings so every retrieved sentence is visible. A production system would extract text from approved files, preserve page/section metadata and reject unsupported formats before indexing.
Understand every project input
5. Architecture / Workflow
Indexing path: extract → clean → chunk → embed → store vectors and metadata.
Question path: embed query → retrieve top-k → optionally rerank → build context.
Generation path: answer only from context → attach citations → abstain when evidence is insufficient.
Evaluation path: score retrieval separately from answer faithfulness and usefulness.
Project figure
Document Q&A has an indexing path and an answering path
Which work happens once, and which work happens for every question?
6. Environment / Dependencies
- Python 3.10+
- NumPy and scikit-learn
- No paid vector database
- Optional local or hosted generator behind a provider adapter
7. Data or Input Understanding
Chunk size balances context and precision. Very large chunks contain extra noise; very small chunks can split a complete fact. Overlap repeats boundary text so one fact is less likely to be cut in half.
top-k is the maximum number of candidates returned. Larger k can improve recall but adds context tokens, latency and distraction. Reranking spends more compute to improve the order of retrieved candidates.
8. Baseline / Simplest Working Approach
First return the best matching chunk and its source without an LLM. This retrieval-only baseline proves whether the evidence can be found.
Then add a generator that receives only labelled evidence. If the highest score is below the validated threshold, return 'I do not have enough evidence' rather than asking the model to guess.
Project figure
Chunk, retrieve, rank and build a bounded context
How do chunk size, overlap and top-k change the evidence packet?
Worked Example: Calculate one cosine similarity
Given: Use query q = [1, 1, 0] and chunk c = [1, 0.8, 0]. These numbers are feature weights produced by the same vectorizer.
- 1Dot product q·c = 1×1 + 1×0.8 + 0×0 = 1.8.
- 2||q|| = √(1² + 1²) = √2 = 1.414.
- 3||c|| = √(1² + 0.8²) = √1.64 = 1.281.
- 4Cosine similarity = 1.8 / (1.414 × 1.281) = 1.8 / 1.811 ≈ 0.994.
Interpretation: The vectors point in almost the same direction, so this chunk is a strong lexical match. Similarity still does not prove the chunk answers the question.
9. Step-by-Step Implementation
Step 1: Index and retrieve the local corpus
fit_transform learns the vocabulary and inverse-document-frequency weights from chunks. transform maps the query into that exact same vector space.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
documents = {
"returns.txt": "Returns are accepted within 30 days with the receipt.",
"shipping.txt": "Standard shipping takes three to five business days.",
"warranty.txt": "The device warranty covers manufacturing defects for one year.",
}
def chunk_text(source: str, text: str, chunk_size: int = 12, overlap: int = 3):
words, chunks = text.split(), []
step = chunk_size - overlap
for start in range(0, len(words), step):
part = words[start:start + chunk_size]
if part:
chunks.append({"source": source, "start_word": start, "text": " ".join(part)})
return chunks
chunks = [chunk for name, text in documents.items() for chunk in chunk_text(name, text)]
vectorizer = TfidfVectorizer()
chunk_vectors = vectorizer.fit_transform([c["text"] for c in chunks])
def retrieve(question: str, top_k: int = 2):
query_vector = vectorizer.transform([question])
scores = (chunk_vectors @ query_vector.T).toarray().ravel()
order = np.argsort(scores)[::-1][:top_k]
return [{**chunks[i], "score": float(scores[i])} for i in order]Step 2: Build context with citations and abstention
The score threshold is a validation choice, not a universal constant. The returned prompt preserves source names beside evidence.
def answer(question: str):
hits = [hit for hit in retrieve(question, top_k=2) if hit["score"] >= 0.10]
if not hits:
return {"answer": "I do not have enough evidence.", "sources": []}
context = "
".join(f"[{h['source']}] {h['text']}" for h in hits)
# A real generator receives this bounded context and must cite its labels.
return {"prompt": f"Use only this evidence:
{context}
Question: {question}",
"sources": [h["source"] for h in hits]}Step 3: Add a generator behind the boundary
The provider receives a bounded evidence packet and must cite bracketed source labels. Keep the local retrieval test runnable without it.
raw = generator(
system="Answer only from evidence. Cite [source]. If absent, say insufficient evidence.",
user=payload["prompt"],
)
validated = check_citations(raw, allowed_sources=payload["sources"])10. Expected Results / Outputs
Read the output as evidence, not decoration
11. Evaluation
Retrieval recall@k asks whether a known relevant chunk appears in the top k. Mean reciprocal rank rewards putting it earlier. Answer faithfulness checks whether claims are supported by retrieved text; answer usefulness checks whether the supported response resolves the question.
Test four cases: direct fact, paraphrase, fact split near a chunk boundary and unsupported question. Record retrieved IDs and scores before judging answer wording.
Project figure
Retrieval quality and answer quality are separate axes
Why can a fluent answer still be a failed RAG result?
12. Failure Analysis
Failure mode → diagnosis → response
13. Improve the Project
14. Production Considerations
What changes beyond the notebook
15. Summary / Key Takeaways
- RAG first retrieves evidence and then generates from a bounded, labelled context.
- Indexing and question answering are separate paths with different failure modes.
- Chunk size and overlap control whether facts stay intact and how much repeated text is stored.
- Query and chunk vectors must come from the same representation model before similarity is meaningful.
- top-k and reranking trade retrieval recall against latency, tokens and context noise.
- Retrieval success and answer faithfulness must be evaluated separately, including unsupported questions.
- A trustworthy document Q&A system preserves permissions and citations and responds with insufficient evidence instead of guessing.