Skip to main content
LearnMLAcademy
Intermediate10 min read

Build a Document Q&A System with RAG

Construct an enterprise PDF question-answering system using RAG retrieval, with reproducible setup, model evaluation, and an end-to-end project task.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

A three-document local corpus and transparent text extraction
Chunking, vectorization, query embedding and top-k similarity search
A bounded context packet with source labels
Separate retrieval and grounded-answer evaluation

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

Understand every project input
ObjectTeaching valueProduction counterpart
documents3 named policy stringsApproved PDFs, HTML or knowledge-base records
chunkOne short document per chunkBounded token windows with overlap and metadata
chunk vectorTF-IDF sparse vectorNeural embedding from a versioned model
query vectorSame fitted vector spaceSame embedding model and preprocessing
citationSource filenameDocument, page, section and stable URL

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?

Index once

Docs
Chunks
Embeddings
Local index

Answer each question

Query
Retrieve
Context
Answer + citations
Documents are extracted, chunked, embedded and indexed ahead of time. Each question is embedded, retrieved, assembled with sources and passed to the generator.

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?

600-token chunks
80-token overlap
Similarity search
top-k = 5
Rerank
keep strongest 3
Context
source labels retained
Grounded answer
or insufficient evidence
Overlapping chunks protect facts near boundaries. Similarity retrieves candidates; optional reranking improves order; the context builder keeps only the strongest evidence that fits the token budget.

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.

  1. 1Dot product q·c = 1×1 + 1×0.8 + 0×0 = 1.8.
  2. 2||q|| = √(1² + 1²) = √2 = 1.414.
  3. 3||c|| = √(1² + 0.8²) = √1.64 = 1.281.
  4. 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.

Index and retrieve the local corpusRUNNABLE CODE
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]
Representative expected output: Question 'How long does shipping take?' ranks shipping.txt first.

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.

Build context with citations and abstentionRUNNABLE CODE
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.

Add a generator behind the boundaryPROVIDER-DEPENDENT CODE
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

Read the output as evidence, not decoration
QuestionTop sourceRetrieval successAnswer behavior
How long is standard shipping?shipping.txtyes3–5 business days [shipping.txt]
What does the warranty cover?warranty.txtyesManufacturing defects for one year [warranty.txt]
Do you ship to Mars?none above thresholdnoInsufficient evidence

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?

Answer faithful
Answer unfaithful
Evidence found
Grounded success
Generation failure
Evidence missed
Helpful abstention
Hallucination risk
Good generation cannot repair missing evidence reliably. Evaluate whether the right chunk was retrieved and whether the answer stayed faithful to that chunk.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
Right document, wrong chunkChunk boundaries or sizeTune size/overlap; preserve headings
No relevant hitVocabulary mismatch or missing corpusNeural embeddings, query rewrite, corpus coverage
Good hit, invented claimGenerator ignored evidenceCitation validation and faithfulness checks
Too much contexttop-k too highRerank and enforce token budget

13. Improve the Project

Replace TF-IDF with a versioned local neural embedding model.
Add metadata filters and a small reranker for ambiguous queries.
Preserve page/section offsets for precise citation display.
Create a labelled evaluation set before tuning chunk size, overlap, k or threshold.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
IngestionMalware/type checks, extraction quality, deduplication and ACLs
Index lifecycleVersion embeddings; re-index changed documents
ServingAccess-filter before retrieval; cache carefully; cap context
MonitoringNo-hit rate, recall sample, citation validity, latency and token cost

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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Build a Document Q&A System with RAG"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Which RAG work normally happens before a user asks a question?
Question 2 of 5interpretation
What is the main purpose of chunk overlap?
Question 3 of 5numerical/formula
For q=[1,1,0] and c=[1,0.8,0], the cosine similarity is approximately what?
Question 4 of 5debugging/diagnostic
The correct chunk is never in the top five, but answers sound fluent. What should be fixed first?
Question 5 of 5practical selection
What should the system do when no retrieved chunk clears the validated relevance threshold?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which RAG work normally happens before a user asks a question?▼

Correct Answer: Document extraction, chunking, embedding and indexing

The corpus is prepared and indexed ahead of time; query embedding and retrieval occur for each question.

2What is the main purpose of chunk overlap?▼

Correct Answer: To reduce the chance that a fact split at a boundary becomes unretrievable

Overlap repeats some boundary text so related words and facts remain together in at least one chunk.

3For q=[1,1,0] and c=[1,0.8,0], the cosine similarity is approximately what?▼

Correct Answer: 0.994

The dot product is 1.8 and the norm product is about 1.811, so 1.8/1.811 ≈ 0.994.

4The correct chunk is never in the top five, but answers sound fluent. What should be fixed first?▼

Correct Answer: Retrieval or corpus coverage

Generation cannot reliably repair absent evidence. Diagnose chunking, representations, query matching and corpus coverage first.

5What should the system do when no retrieved chunk clears the validated relevance threshold?▼

Correct Answer: Return insufficient evidence and no unsupported citation

A grounded system abstains when evidence is missing instead of converting low-confidence retrieval into a hallucination.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next