Repository navigation
Text Analysis Tutorial: RAG Basics (indexing, retrieval, prompt construction; small corpus) #255
Description
Title & Overview
Template: RAG Basics: An Intermediate, End-to-End Analysis Tutorial
Overview (≤2 sentences): Learners will implement a Retrieval-Augmented Generation (RAG) pipeline with indexing, retrieval, and prompt construction over a small corpus. It is intermediate because it emphasizes reproducibility, retrieval–generation trade-offs, and structured evaluation of retrieval quality and answer correctness.
Purpose
The value-add is teaching learners how to combine retrieval with generation in a defensible way. They will explore indexing strategies, prompt design, and evaluation of RAG systems, while stressing reproducibility and guardrails for small-scale deployment.
Prerequisites
- Skills: Python, Git, pandas, ML basics.
- NLP: embeddings, retrieval, generation models, evaluation metrics.
- Tooling: pandas, scikit-learn, Hugging Face Transformers, Sentence-Transformers, FAISS, Haystack, MLflow, FastAPI.
Setup Instructions
-
Environment: Conda/Poetry (Python 3.11), deterministic seeds.
-
Install: pandas, scikit-learn, Hugging Face Transformers + Datasets, Sentence-Transformers, FAISS, Haystack, MLflow, FastAPI.
-
Datasets:
- Small: WikiMovies (QA corpus).
- Medium: HotpotQA (subset for multi-hop retrieval).
-
Repo layout:
tutorials/t11-rag-basics/ ├─ notebooks/ ├─ src/ │ ├─ indexer.py │ ├─ retriever.py │ ├─ generator.py │ ├─ pipeline.py │ └─ config.yaml ├─ data/README.md ├─ reports/ └─ tests/
Core Concepts
- RAG workflow: corpus indexing → document retrieval → prompt construction → generation.
- Indexing choices: exact vs approximate nearest neighbors (FAISS).
- Prompt construction: retrieved docs + query → model input; guardrails to prevent overflow.
- Evaluation: retrieval precision@k, generation accuracy/F1, calibration of confidence.
- Error slicing: by query type, document length, retrieval difficulty.
Step-by-Step Walkthrough
- Data intake & preprocessing: load WikiMovies/HotpotQA subsets; reproducible splits.
- Indexing: build FAISS index on sentence/document embeddings (Sentence-Transformers).
- Retrieval baseline: BM25 vs dense ANN embeddings; compare retrieval quality.
- Generation baseline: DistilBART/T5-small with retrieved docs as context.
- Evaluation: retrieval precision@k, MRR; generation EM/F1; slice performance by query type.
- Error analysis: missed retrievals, hallucinations, overly long prompts.
- Reporting: metrics tables, retrieval/generation error cases →
reports/t11-rag-basics.md. - (Optional) Serve: FastAPI endpoint with retrieval + generation pipeline, schema validation, max token guardrails.
Hands-On Exercises
- Ablations: BM25 vs FAISS; top-k=1 vs top-k=5 retrieved docs.
- Robustness: add distractor documents; measure retrieval/generation accuracy.
- Slice analysis: compare single-hop vs multi-hop queries.
- Stretch: hybrid retrieval (BM25 + embeddings reranker).
Common Pitfalls & Troubleshooting
- Retriever failure cascades: poor retrieval → bad generation.
- Long prompts: exceeding model max tokens; must truncate or window.
- Metrics misuse: only reporting generation accuracy; retrieval must be evaluated separately.
- Index drift: embeddings change → FAISS index rebuild required.
- OOM issues: dense embeddings on large corpus; mitigate with batching.
Best Practices
- Log both retrieval and generation configs in MLflow.
- Keep reproducibility: fixed seeds, dataset fingerprints, tokenizer artifacts.
- Unit tests: deterministic retrieval results under fixed embeddings.
- Guardrails in serving: enforce schema, max context length, reject empty queries.
- Baseline → Retriever Comparison → RAG pipeline narrative.
Reflection & Discussion Prompts
- Why does retrieval improve generation robustness?
- How does index choice (BM25 vs FAISS) affect performance and scalability?
- What risks come from hallucinations in RAG pipelines?
Next Steps / Advanced Extensions
- Integrate cross-encoder rerankers for retrieval.
- Multi-hop retrieval pipelines.
- Domain adaptation: civic datasets (public documents, meeting notes).
- Lightweight monitoring: retrieval recall drift over time.
Glossary / Key Terms
RAG, retrieval, generation, ANN, FAISS, BM25, precision@k, MRR, hallucination.
Additional
- [Sentence-Transformers](https://www.sbert.net/)
- [Haystack](https://docs.haystack.deepset.ai/)
- [Hugging Face Transformers](https://huggingface.co/docs/transformers)
- [Hugging Face Datasets](https://huggingface.co/datasets)
- [FAISS](https://faiss.ai/)
- [MLflow](https://mlflow.org/)
- [FastAPI](https://fastapi.tiangolo.com/)
Contributors
Author(s): TBD
Reviewer(s): TBD
Maintainer(s): TBD
Date updated: 2025-09-20
Dataset licenses: WikiMovies (open), HotpotQA (CC BY-SA).
Issues Referenced
Epic: HfLA Text Analysis Tutorials (T0–T14).
This sub-issue: T11: RAG Basics.
Resources
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsIn progress (actively working)
Activity
D4rb0ux commentedon Aug 17, 2026
Progress: Set up a local Jupyter Notebook environment with necessary dependecies and completed steps 1 - 3.
Blockers: Encountered some RAM difficulties and Kernel crashes because of that, but got it resolved by saving embedding into .npy files
Availability: 8-10 hours
ETA: need another ~2 weeks
Pictures (if necessary): Comparison of BM25 index search and FAISS index search - what percentage of validation questions had all required supporting articles retrieved within the top-k (k=2 / k=5 / k=10)?
chinaexpert1 commentedon Aug 25, 2026
Please provide update @D4rb0ux
Instructions
You can use this template
D4rb0ux commentedon Aug 31, 2026
Progress: Completed steps 4 and 5.

Blockers: Run into a problem of code never finishing executing when trying to generate an answer to a question from the dataset. Solved by transfering the notebook from the local Jupyter environment to a Google Colab and using a free Tesla T4 GPU there (Runtime -> Change runtime type -> T4 GPU).
Availability: 8 - 10 hours
ETA: needs another ~2 weeks
Pictures (if necessary):
Screenshot 1 - Precision@k (of the first k documents we retrieved, how many were actually relevant) and mean reciprocal rank (how high in the results was the first relevant document)
Screenshot 2 - EM (Exact Match: 1 -> prediction matches the gold answer, 0 -> it doesn't) and F1 (compares the individual words/tokens in the prediction and gold answer) metrics

Screenshot 3 - Some examples of the generated and expected answers to validation questions

Screenshot 4 - Generation performance by query type.

Example of a bridge question: What government position was held by the woman who portrayed Corliss Archer in the film Kiss and Tell? Example of a comparison question: Were Scott Derrickson and Ed Wood of the same nationality?
Screenshot 5 - Retrieval performance by query type. Comparison questions actually have better retrieval performance, but dramatically worse generation performance.

D4rb0ux commentedon Sep 14, 2026
Progress: Created a google doc for the tutorial, where went through the steps from data processing and creating a corpus to building a search index (FAISS) with some examples from my notebook and explanations of the core concepts used (RAG, embedding, cosine similarity) with pictures where they'd be useful to visualize the concept better
Blockers: -
Availability: ~6 hours
ETA: a month?
D4rb0ux commentedon Sep 18, 2026
Progress: Added the doc link to Resources section here. In the tutorial added the steps from how to retrieve documents to how to generate an answer.
Blockers: -
Availability: won't be available for the next 2 weeks
ETA: a month?
D4rb0ux commentedon Oct 13, 2026
Progress: Added the steps to the tutorial about evaluation: how to evaluate the retrieval of documents and how to evaluate the answers generated from the retrieved documents.
Blockers: -
Availability: ~6 hours
ETA: a month
D4rb0ux commentedon Oct 20, 2026
Progress: Added a part about evaluation of the results by question type; added chapters on error analysis and reporting of my own results
Blockers: -
Availability: ~6 hours
ETA: a month
D4rb0ux commentedon Oct 26, 2026
Progress: Created a presentation and the tutorial page: https://github.com/hackforla/data-science/wiki/RAG-Basics
Blockers: -
Availability: ~6 hours
ETA: done!