Skip to content

Text Analysis Tutorial: RAG Basics (indexing, retrieval, prompt construction; small corpus) #255

Open

Description

@chinaexpert1

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

  1. Data intake & preprocessing: load WikiMovies/HotpotQA subsets; reproducible splits.
  2. Indexing: build FAISS index on sentence/document embeddings (Sentence-Transformers).
  3. Retrieval baseline: BM25 vs dense ANN embeddings; compare retrieval quality.
  4. Generation baseline: DistilBART/T5-small with retrieved docs as context.
  5. Evaluation: retrieval precision@k, MRR; generation EM/F1; slice performance by query type.
  6. Error analysis: missed retrievals, hallucinations, overly long prompts.
  7. Reporting: metrics tables, retrieval/generation error cases → reports/t11-rag-basics.md.
  8. (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

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

The Google doc

Activity

  1. moved this from New Issue Approval to In progress (actively working) in CoP: Data Science: Project Boardon Aug 11, 2026
  2. D4rb0ux commented on Aug 17, 2026

    @D4rb0ux
    Member

    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)?

    Image
  3. chinaexpert1 commented on Aug 25, 2026

    @chinaexpert1
    MemberAuthor

    Please provide update @D4rb0ux

    Instructions
    1. Progress: "What is the current status of your project? What have you completed and what is left to do?"
    2. Blockers: "Difficulties or errors encountered."
    3. Availability: "How much time will you have this week to work on this issue?"
    4. ETA: "When do you expect this issue to be completed?"
    5. Pictures (if necessary): "Add any pictures that will help illustrate what you are working on."

    You can use this template

    1. Progress: 
    2. Blockers: 
    3. Availability:
    4. ETA:
    5. Pictures (if necessary): 
    
  4. D4rb0ux commented on Aug 31, 2026

    @D4rb0ux
    Member

    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)
    Image

    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
    Image

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

    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?
    Image

    Screenshot 5 - Retrieval performance by query type. Comparison questions actually have better retrieval performance, but dramatically worse generation performance.
    Image

  5. D4rb0ux commented on Sep 14, 2026

    @D4rb0ux
    Member

    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?

  6. D4rb0ux commented on Sep 18, 2026

    @D4rb0ux
    Member

    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?

  7. D4rb0ux commented on Oct 13, 2026

    @D4rb0ux
    Member

    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

  8. D4rb0ux commented on Oct 20, 2026

    @D4rb0ux
    Member

    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

  9. D4rb0ux commented on Oct 26, 2026

    @D4rb0ux
    Member

    Progress: Created a presentation and the tutorial page: https://github.com/hackforla/data-science/wiki/RAG-Basics
    Blockers: -
    Availability: ~6 hours
    ETA: done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions