Week 4–5
RAG
Ground LLMs in your data without fine-tuning. Retrieve relevant chunks, add them to the prompt, generate answers.
Pause & reflect
Before you read on, answer this in your head — or on paper:
You have 1,000 PDF documents. The user asks: "What did we decide about the Q3 budget?"
You cannot fit all 1,000 PDFs in the prompt. What are your options? How might you find the right page? What could go wrong?
LLMs don't know your docs, your database, or your internal knowledge. RAG bridges that: you index your data, then at query time retrieve the most relevant pieces and pass them as context. The model answers from your content, not its training cutoff. No retraining, fast iteration when docs change.
Pipeline intuition
Before you read on, answer this in your head — or on paper:
The RAG pipeline has four stages: index, retrieve, augment, generate.
Where do you think most of the "magic" happens? If retrieval returns bad chunks, can the LLM fix it? What's the weakest link?
Index (offline)
Chunk documents → embed each chunk → store vectors in a DB (pgvector, Pinecone, Chroma, Weaviate). Run once or on schedule.
Retrieve (online)
Embed the user query → similarity search (cosine, dot product) → return top-k chunks. Quality of retrieval = quality of RAG.
Augment
Insert retrieved chunks into the prompt as context. Format: 'Answer based on: [chunks]. Question: [query]'.
Generate
Call the LLM. It answers using the augmented context. Instruct it to cite sources and say 'I don't know' when context is insufficient.
Minimal RAG prompt
You are a helpful assistant. Answer ONLY based on the context below. If the answer is not in the context, say "I don't know." Context: --- {retrieved_chunks} --- Question: {user_query}
Test your understanding
Don't reveal yet. Think for ~30 seconds first — what would you try?
Your RAG system sometimes returns irrelevant chunks because the user query uses different words than the documents. What are two strategies to improve retrieval?
Check your understanding
What is the correct order of the RAG pipeline?
When might RAG be preferred over fine-tuning?
Why does chunk size matter in RAG?