Why LLMs need your data
LLMs are brilliant generalists that know nothing about your organisation. Retrieval-augmented generation fixes that by looking things up first.
Learning objectives
- Explain the knowledge limits of LLMs
- Compare prompt-stuffing, RAG and fine-tuning
- Describe the indexing and query halves of a RAG pipeline
- Identify the common failure points of RAG
- Build the retrieve–augment–generate pattern in plain Python
- Decide between RAG and putting everything in the prompt
Every code block in this course is a live cell: press Run and it runs in your browser, and you can edit it and run it again. Real embedding models and LLMs need a secret API key, and a key must never sit in a web page. So on these pages the cells talk to a small pretend embedding model and a pretend LLM built into the page. The code is what you'd write for the real thing; the results come from simple rules, not real AI, and are weaker than a real model's. To use real models, copy the code into a notebook such as Google Colab and add your own key (see Python for AI, Module 5).
1.1 What an LLM doesn't know
A large language model is trained on a huge snapshot of public text. Out of the box it knows nothing about:
- Your private information — policies, contracts, product specs, tickets, wikis.
- Anything after its training cut-off — new prices, regulations, decisions.
- Exact details it saw rarely — and it may confidently invent them (hallucinate).
Ask a general assistant "What's our refund window for damaged items?" and the best it can do is guess what companies usually do.
1.2 Three ways to give a model your knowledge
| Approach | How it works | Good for | Limits |
|---|---|---|---|
| Put it in the prompt | Paste the relevant documents into the context | One-off questions; small, stable document sets | Cost and delay grow with every token, on every question; no access control per user |
| Retrieval-augmented generation (RAG) | Search your documents for the most relevant passages and put only those into the prompt | Large, changing knowledge bases; answers with citations; different users seeing different documents | Only as good as the retrieval step |
| Fine-tuning | Further train the model on your examples | Style, format, specialised behaviour | Poor at adding facts that change; expensive to update (see the Fine-tuning course) |
For "answer questions from our documents", RAG is usually the right starting point for anything beyond a handful of documents: it's cheaper per question, easier to update (just change the documents) and lets you show sources. Section 1.6 looks at when simply putting everything in the prompt is the better choice.
1.3 The RAG pipeline
Every RAG system has two halves:
- Indexing (done ahead of time): load documents → split them into chunks → turn each chunk into an embedding → store chunks and embeddings in an index.
- Query time (on every question): embed the question → retrieve the most similar chunks → put them into a prompt with the question → the LLM writes an answer grounded in those chunks, ideally with citations.
1.4 Where RAG goes wrong
When a RAG system gives a bad answer, the cause is usually one of these — and each module of this course tackles one:
| Failure | Symptom | Module |
|---|---|---|
| Poor embeddings or similarity search | Irrelevant passages come back | 2 |
| Bad chunking | The answer is split across chunks, or chunks lack context | 3 |
| Weak retrieval | Exact terms (product codes, names) are missed | 4 |
| Ungrounded generation | The model ignores the passages or adds facts | 5 |
| No evaluation | You can't tell if a change helped | 6 |
For each, choose prompt-stuffing, RAG or fine-tuning: (a) an HR assistant answering from 400 policy documents updated monthly; (b) summarising one 20-page contract; (c) making every output follow your house style for product descriptions.
Show answers
(a) RAG — large, changing knowledge base. (b) Put it in the prompt — one document fits easily. (c) Fine-tuning (or a strong prompt with examples) — it's about style, not facts.
1.5 The whole idea in twenty lines
Before any special tools, here is RAG with nothing but plain Python: find the document that shares the most words with the question, and build a prompt around it. No model is called; the cell prints the prompt that would be sent.
Python · retrieval and prompt-building, with no librariesdocs = {
"Returns Policy": "Damaged items can be returned within 30 days for a full refund.",
"Delivery FAQ": "Standard UK delivery takes 3 to 5 working days.",
"Care Guide": "Hand-wash bamboo boards. Never put a bamboo board in the dishwasher.",
}
def words(text):
return set(text.lower().replace("?", "").replace(".", "").replace(",", "").split())
def retrieve_one(question):
overlap = {title: len(words(question) & words(text)) for title, text in docs.items()}
best = max(overlap, key=overlap.get)
return best, overlap
question = "Can I put my board in the dishwasher?"
best, overlap = retrieve_one(question)
print("Words shared with each document:", overlap)
prompt = f"""Answer the question using only this source. If it doesn't contain the answer, say so.
Source ({best}): {docs[best]}
Question: {question}"""
print()
print(prompt)
That is the whole pattern: retrieve, then augment the prompt, then let the model generate. Everything in the rest of the course is about doing each step better. Change the question to "my board arrived cracked, will I get my money back?" and run it again: word matching picks the wrong document, because the question says "cracked" and "money back" where the policy says "damaged" and "refund". Fixing that is the job of Module 2.
1.6 RAG, or just a long prompt?
The models of a few years ago could read only a few pages at a time, so retrieval was the only way to use a large set of documents. Current models accept hundreds of thousands of tokens, some a million — whole handbooks in one prompt. That has changed the advice. For a single contract or a small, stable set of policies, putting everything in the prompt is now a perfectly good design: there is no retrieval step to build, and none to go wrong.
Cost is the first thing that changes with size, because a long prompt is paid for again on every question:
Python · the cost of sending everything, every timePRICE_IN = 1.00 # EXAMPLE price in £ per million input tokens — check your provider
TOKENS_PER_PAGE = 600 # a typical page of text
QUESTIONS_PER_MONTH = 20_000
def monthly_cost(pages_sent_per_question):
return QUESTIONS_PER_MONTH * pages_sent_per_question * TOKENS_PER_PAGE * PRICE_IN / 1_000_000
for pages in [20, 200, 1500]:
print(f"{pages:5} pages of documents: whole set in every prompt £{monthly_cost(pages):9,.2f}"
f" RAG (5 pages retrieved) £{monthly_cost(5):,.2f}")
Providers offer large discounts for prompt text that is repeated exactly (prompt caching), which narrows the gap, so treat these figures as the shape of the problem, not a quote. Cost is also only one of the reasons to retrieve:
| Put everything in the prompt when… | Use RAG when… |
|---|---|
| the documents fit comfortably and rarely change | the collection is large, or grows every week |
| every user may see every document | different users are allowed to see different documents |
| questions need the whole document at once (summarise, compare sections) | questions are answered by one or two passages |
| volume is low, so cost per question hardly matters | volume is high, or answers must be fast |
| you don't need to show which passage an answer came from | you need citations people can check |
A long prompt also doesn't remove the need for good documents. A model handed two versions of a policy will happily answer from the wrong one. Retrieval done well is partly a way of deciding what the model should not see.
Change retrieve_one into retrieve_top(question, k=2), which returns the titles of the k documents sharing the most words with the question, best first. Try it on "how long does delivery take if my board is damaged?"
Your turnkb = {
"Returns Policy": "Damaged items can be returned within 30 days for a full refund.",
"Delivery FAQ": "Standard UK delivery takes 3 to 5 working days.",
"Care Guide": "Hand-wash bamboo boards. Never put a bamboo board in the dishwasher.",
}
def words(text):
return set(text.lower().replace("?", "").replace(".", "").replace(",", "").split())
# Write retrieve_top(question, k=2), then press RunShow a solution
kb = {
"Returns Policy": "Damaged items can be returned within 30 days for a full refund.",
"Delivery FAQ": "Standard UK delivery takes 3 to 5 working days.",
"Care Guide": "Hand-wash bamboo boards. Never put a bamboo board in the dishwasher.",
}
def words(text):
return set(text.lower().replace("?", "").replace(".", "").replace(",", "").split())
def retrieve_top(question, k=2):
overlap = {title: len(words(question) & words(text)) for title, text in kb.items()}
return sorted(overlap, key=overlap.get, reverse=True)[:k]
print(retrieve_top("how long does delivery take if my board is damaged?"))
# Retrieving more than one passage is what lets a system answer questions that touch two documents.A team has 300 pages of documents and expects 2,000 questions a month. Using the example price in the starter code, work out the monthly cost of sending all 300 pages with every question, and of retrieving 5 pages per question. Then find how many questions a month it takes before the whole-prompt approach costs more than £500.
Your turnPRICE_IN = 1.00 # EXAMPLE price in £ per million input tokens
TOKENS_PER_PAGE = 600
# Write cost(questions, pages), then press RunShow a solution
PRICE_IN = 1.00 # EXAMPLE price in £ per million input tokens
TOKENS_PER_PAGE = 600
def cost(questions, pages):
return questions * pages * TOKENS_PER_PAGE * PRICE_IN / 1_000_000
print(f"Everything in the prompt: £{cost(2000, 300):.2f} a month")
print(f"RAG, 5 pages: £{cost(2000, 5):.2f} a month")
per_question = cost(1, 300)
print(f"£500 is reached at about {500 / per_question:,.0f} questions a month")
# At 2,000 questions the simple approach is affordable. The decision depends on volume, not on fashion.Key takeaways
- LLMs don't know your private, recent or rare information.
- RAG retrieves relevant passages and puts only those into the prompt.
- RAG suits large, changing knowledge; fine-tuning suits style and behaviour.
- Indexing happens ahead of time; retrieval and generation happen per question.
- Most RAG failures come from embeddings, chunking, retrieval, grounding or missing evaluation.
- RAG is retrieve, augment, generate; every later technique improves one of the three.
- Long context suits small, stable document sets; RAG wins on scale, cost per question, permissions and citations.