Module 1 of 6 · 40 minutes

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.

By · Last updated

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
Running the code — and practice mode

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

ApproachHow it worksGood forLimits
Put it in the promptPaste the relevant documents into the contextOne-off questions; small, stable document setsCost 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 promptLarge, changing knowledge bases; answers with citations; different users seeing different documentsOnly as good as the retrieval step
Fine-tuningFurther train the model on your examplesStyle, format, specialised behaviourPoor 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.

ApproachBest forPut it in the promptone document, one-offRAGlarge, changing knowledge + citationsFine-tuningstyle, format, behaviour
Three ways to give a model your knowledge. For 'answer from our documents', RAG is usually the starting point.

1.3 The RAG pipeline

Every RAG system has two halves:

  1. Indexing (done ahead of time): load documents → split them into chunks → turn each chunk into an embedding → store chunks and embeddings in an index.
  2. 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.
Indexing — done ahead of timeDocumentsClean &chunkEmbedVector indexQuery time — every questionQuestionEmbedRetrievetop-k chunksPrompt =chunks + questionLLMAnswer +citationssearched
The two halves of RAG. Documents are indexed once; each question is embedded, matched against the index, and the best chunks are handed to the LLM with the question.

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:

FailureSymptomModule
Poor embeddings or similarity searchIrrelevant passages come back2
Bad chunkingThe answer is split across chunks, or chunks lack context3
Weak retrievalExact terms (product codes, names) are missed4
Ungrounded generationThe model ignores the passages or adds facts5
No evaluationYou can't tell if a change helped6
Try it: is RAG the right tool?

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 changethe collection is large, or grows every week
every user may see every documentdifferent 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 mattersvolume is high, or answers must be fast
you don't need to show which passage an answer came fromyou 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.

Exercise: return the two best documents

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 Run
Show 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.
Exercise: where is the break-even?

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 Run
Show 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.