Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 140/ 160
07. Deep Learning & NLP

Intro to LLMs & RAG for Data Scientists

Use LLMs and retrieval-augmented generation for analytics copilots and document Q&A.

AdvancedLLMs · RAG3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A large language model writes answers by guessing the next word. RAG first looks up the most relevant pieces of your own documents and shows them to the model, so its answer is based on your facts instead of its memory.

Think of it like…

An open-book exam with a research assistant. The LLM is a very well-read writer with no access to your files; RAG is the assistant who pulls the five most relevant pages from your archive and hands them over before the writer answers, with the rule "say you don't know if the pages don't say".

Where you’ve seen it

A 200-page policy report of about 100,000 words is roughly 135,000 tokens. Chunking at 500 tokens with 50 tokens of overlap advances 450 tokens per chunk, producing 135,000 / 450 = 300 chunks. Each chunk is embedded as a 768-dimensional float32 vector (3,072 bytes), so the index holds 300 × 3,072 = 921,600 bytes, under 1 MB, small enough for an in-memory index. At question time the question is embedded, the top 5 chunks by cosine similarity are retrieved and the prompt contains instructions (about 200 tokens), the five chunks (2,500 tokens) and the question (50 tokens), about 2,750 input tokens. At illustrative prices of $2.50 per million input tokens and $10 per million output tokens, a 300-token answer costs 2,750 × 2.5e-6 + 300 × 1e-5 = $0.006875 + $0.003 = $0.0099, about one US cent per question. The team measures quality on 50 labelled questions: the correct chunk is in the top 5 for 42 of them, a recall@5 of 84%, so at least 16% of failures come from retrieval before the model is even involved; they then read answers for faithfulness (does every claim appear in the retrieved text?) and require citations. A second prototype, an analytics copilot, puts the table schema in the prompt and generates SQL; they run the SQL through a read-only database role with a row limit, validate it, show it to the analyst and evaluate execution accuracy on a set of known questions. Confidential rows are never sent to an external model without approval from the data owner.

Words you’ll hear

Context window
The maximum number of tokens an LLM can read and write in one request.
Chunk and embedding
A slice of a document and its vector representation used for similarity search.
Retrieval recall@k
The share of questions whose relevant chunk appears in the top k results.
Faithfulness / grounding
Whether every claim in the answer is supported by the retrieved text.

Visual diagram

Loading interactive diagram

Theory & deep dive

How LLMs and RAG fit together

An LLM predicts the next token given the context, so quality depends heavily on what is in the prompt. It cannot know your private documents, may be out of date and sometimes states falsehoods fluently. RAG addresses this: chunk documents (200 to 800 tokens, with overlap so sentences aren't cut off), embed each chunk with an embedding model, store vectors in an index (a library such as FAISS or a vector database), and at question time embed the query, retrieve the top-k by cosine similarity and build a prompt of instructions, retrieved chunks and the question. A good instruction says to answer only from the context, cite chunk IDs and reply "not found" otherwise.

Worked sizing: 100,000 words ≈ 135,000 tokens; with chunks of 500 tokens advancing by 450 there are 135,000 / 450 = 300 chunks; at 768 dimensions in float32 each vector is 3,072 bytes, so the index is 921,600 bytes. The per-question prompt has about 200 instruction tokens, 5 × 500 = 2,500 context tokens and 50 question tokens, 2,750 in total; at illustrative prices of $2.50 per million input and $10 per million output tokens, with a 300-token answer, one query costs about $0.0099. Cost scales with k and chunk size, so retrieving fewer, better chunks is cheaper and often more accurate.

Cost per question

Input 2,750 tokens × $2.50/M = $0.006875. Output 300 tokens × $10/M = $0.003. Total ≈ $0.0099. At 5,000 questions a month that is about $49, against 8 analyst-minutes saved per question if answers are trusted.

Key takeaway: RAG supplies private, current facts through retrieval; size the index and the prompt, and cost per question follows from tokens.

Evaluation, analytics copilots and risks

Evaluate retrieval and generation separately. For retrieval, build a labelled set of questions with the chunk or page that answers each and measure recall@k and MRR: 42 of 50 questions with the right chunk in the top 5 is 84%, so the other 16% cannot be answered correctly however good the model is. Improve it with better chunking, hybrid search (keywords plus embeddings), reranking and metadata filters. For generation, measure faithfulness (claims supported by the retrieved text), answer correctness against reference answers and refusal behaviour when the answer is absent, using human review on a sample and, carefully, an LLM judge calibrated against human labels.

An analytics copilot places the schema (tables, columns, descriptions, sample values and a few example queries) in the prompt and asks the model to write SQL. Reduce risk with a read-only role, row and time limits, SQL validation (allow-list of tables, no writes), showing the query to the user and measuring execution accuracy on known questions. General risks: hallucination, prompt injection through retrieved documents, privacy (do not send confidential or personal data to external services without approval; consider self-hosted models), cost drift and version changes that alter outputs, so keep a regression set. Choose the simplest tool that works: a classifier or a dashboard query is cheaper and more reliable than an LLM for a fixed question.

Retrieval metric

50 questions, correct chunk in the top 5 for 42: recall@5 = 0.84. If the generator answers correctly 95% of the time when the right chunk is present, end-to-end accuracy is at most about 0.84 × 0.95 = 0.80.

Key takeaway: Measure retrieval and faithfulness separately, restrict what generated SQL can do and keep private data under control.

How it works, step by step

Step 1 of 4
Data scientist

1. Decide whether an LLM is needed

Check whether a classifier, rule or SQL query solves the problem more cheaply and reliably.

fixed question → no LLM
Key numbers at this step
Estimate
volume and cost

When to use it & trade-offs

What it is

A large language model (LLM) is a transformer trained to predict the next token, which lets it follow instructions, summarise, extract and write code or SQL when prompted. It has a fixed context window, a temperature that controls randomness and no knowledge of your private data. Retrieval-augmented generation (RAG) supplies that knowledge at question time: split documents into chunks, convert each to an embedding, store them in a vector index, retrieve the top-k chunks most similar to the question, place them in the prompt and ask the model to answer only from that context, with citations. For data scientists, typical uses are document Q&A, analytics copilots that turn questions into SQL against a known schema, text extraction and classification at scale, and evaluation of all of these with labelled question sets.

Why it matters: LLMs let a small team build features that once needed large labelled datasets, but they invent plausible facts, cost money per token and change behaviour between versions. RAG grounds answers in your documents, keeps them current without retraining and makes it possible to cite sources. The data scientist's job is to design the retrieval, measure quality (retrieval recall and answer faithfulness), control cost and risk and decide when a simpler tool, such as a classifier or a SQL query, is the better answer.

When to reach for it

  • Question answering over policies, manuals and reports
  • Analytics copilots that draft SQL for review
  • Bulk extraction and classification where labels are scarce

When to avoid or be careful

  • Sending confidential data to an external model without approval
  • Letting generated SQL run with write permissions
  • Shipping without a labelled evaluation set

Ways to give an LLM your knowledge

Prompting with a small amount of context
Best for: Short documents that fit the context window

Strengths: Simplest; no index.

Watch out: Doesn't scale to large corpora.

RAG
Best for: Large, changing document collections

Strengths: Current, citable and cheap to update.

Watch out: Quality depends on retrieval; more moving parts.

Fine-tuning
Best for: Stable style, format or task behaviour

Strengths: Consistent outputs; shorter prompts.

Watch out: Poor for fast-changing facts; training cost.

Interview signals & numbers to know

When this topic comes up

  • “How does RAG reduce hallucination?”
  • Chunk size and overlap trade-offs
  • Measuring retrieval separately from generation
  • Text-to-SQL safety
  • When not to use an LLM

Benchmarks & rules of thumb

300 chunks -
135,000 tokens at 500-token chunks with 50 overlap
≈ $0.0099 -
illustrative cost of one 2,750-token-in, 300-token-out query
84% -
recall@5 in the example, capping answer quality

Common mistakes & follow-ups

Common interview mistakes

  • Blaming the model for answers that retrieval never found.
  • Using chunks so large that the prompt becomes expensive and noisy.
  • Trusting an LLM judge without calibrating it against human labels.

Likely interviewer follow-ups

  • How would you improve retrieval recall?
  • How would you evaluate an analytics copilot?
  • How do you prevent prompt injection from retrieved documents?
Interview tip: Quote recall@k and a cost per question; they show you evaluate and budget an LLM system like any other model.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Intro to LLMs & RAG for Data Scientists with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Fine-Tuning Pre-trained Hugging Face Models
Next topic
Project Structuring & Cookiecutter Data Science