Lesson 5.1: The RAG pipeline
Learn how RAG works end to end: ingesting documents, retrieving chunks, building a grounded prompt, answering with sources, and budgeting cost and delay.
A language model knows a great deal in general and nothing in particular about your company. It has never read your refund policy, your product manuals or last week's pricing change. Ask it a question about them and it may answer fluently and wrongly. Retrieval-augmented generation, usually shortened to RAG, is the most common fix. Instead of hoping the model remembers, the application looks up the relevant passages from your own documents at the moment a question arrives, places them in the prompt and asks the model to answer from them. The model supplies the language and the reasoning. Your documents supply the facts. This lesson puts together the parts you met in Module 4, embeddings, similarity search, chunking and vector stores, into a working whole. By the end you will be able to explain what RAG is and when it is the right choice compared with fine-tuning or a long prompt, draw the pipeline in its two halves, one that runs ahead of time and one that runs for every question, write a prompt that makes the model answer from the retrieved text and say so when it cannot, estimate the tokens, cost and delay for one question and for a month of traffic, see why the overall quality is the product of several stage-by-stage rates, and plan the first version of a RAG system you could build and test. You should have read Lessons 4.1 to 4.4 and the earlier lessons on tokens, context windows and the parts of an LLM application. No programming is needed, and the arithmetic is simple.
The problem RAG solves
A model's knowledge comes from the data it was trained on, and it has a cut-off. Three things follow.
It does not know your private information. Internal policies, customer records and unpublished documents were never in its training data.
It does not know recent facts. Anything that changed after training is missing or out of date.
It sometimes makes things up. When a model lacks the facts, it may produce a plausible answer anyway. This is often called hallucination. It is not lying, because the model has no intention, but the effect on a user is the same.
You could try to fix this in other ways. Fine-tuning adjusts the model's weights on your data. It can teach style, format and domain vocabulary, but it is a poor way to store facts: it is costly, hard to update when a document changes and offers no way to show where an answer came from. Pasting everything into the prompt works for a small amount of text, but a company's documents will not fit in the context window, and paying to process them on every question would be wasteful. RAG sits between: keep the documents outside the model, find the few passages that matter and give only those.
RAG has real strengths. You can update knowledge by changing a document, without touching the model. You can show sources, so that users can check. You can restrict what each user can see by filtering retrieval. And you can usually run it with a smaller, cheaper model, because the model needs to read and reason, not to remember.
It also has limits. If retrieval fails to find the right passage, the model has nothing to work with. The model may ignore the passages or misread them. And the system is more complicated than a single call. Lesson 5.4 covers how RAG fails.
Predict first: a retailer wants a chatbot that answers questions about its returns policy, which changes twice a year. Would you fine-tune a model on the policy, or use RAG? Think about what happens when the policy changes before you read on.
RAG is the better fit. When the policy changes, you update the document and re-embed the changed chunks, and the bot is current within minutes. A fine-tuned model would need retraining, and could keep answering from the old policy. RAG also lets the bot quote the policy and link to it.
The pipeline in two halves
A RAG system has two parts that run at different times.
Part 1: ingestion, done ahead of time. This prepares your documents so they can be searched. It runs when you first load a collection and again whenever documents change.
1. Collect the documents from their sources: files, a website, a help centre, a database.
2. Clean the text: extract it from the file format, remove navigation, headers, footers and duplicate content, and fix broken characters.
3. Chunk it into pieces, as Lesson 4.3 described, adding titles and metadata.
4. Embed each chunk with an embedding model, as in Lesson 4.1.
5. Store the vectors, the text and the metadata in a vector store with an index, as in Lesson 4.4.
Part 2: answering, done for every question. This runs each time a user asks something.
1. Receive the question, and optionally rewrite it. A follow-up such as "and for digital goods?" makes no sense alone, so the system may rewrite it using the conversation so far into "What is the refund period for digital goods?".
2. Embed the question with the same embedding model used in ingestion.
3. Retrieve the top k chunks, using vector search, perhaps hybrid search, with any filters for the user's permissions.
4. Rerank, optionally. A second, more careful model re-orders a larger set of candidates to pick the best few. Lesson 5.2 covers this.
5. Build the prompt: instructions, the retrieved chunks, the conversation and the question.
6. Generate the answer with a language model.
7. Post-process: add citations, check the answer, filter unsafe content and format the result for the user.
8. Log what happened: the question, the chunks, the answer and the delays, so that you can find and fix problems.
Look at the figure. In this example, about 80 per cent of the prompt is retrieved text. That is typical, and it is why the choices from Module 4 matter so much for cost and speed.
The prompt: telling the model to use the sources
The prompt for the generation step does a lot of work. A good one has five parts.
1. A role and a rule of grounding. "You answer questions about Acme's policies. Use only the information in the context below. If the context does not contain the answer, say that you do not know and suggest contacting support. Do not use outside knowledge."
2. The retrieved context, clearly marked, with each chunk labelled by a number or source so that the model can refer to it. "[1] Refund policy, section 2: ..."
3. Format instructions. "Answer in two or three sentences. Cite the sources you used as [1], [2]."
4. The conversation so far, if it is a chat.
5. The question.
The grounding rule is the most important. Without it, the model blends the context with whatever it remembers and may state things that are not in your documents. With it, the model is told to stay within the text, and to admit ignorance. The "say you do not know" instruction is vital, because the retrieval step will sometimes bring back chunks that do not contain the answer. The model needs permission to say so, and a better answer is "I could not find that in our policy" than a guess.
It also helps to place the retrieved context in a clearly delimited block, and to tell the model that anything inside it is reference material and not an instruction. Documents can contain text that looks like instructions, and a careful design treats the context as data. Lesson 8.3 comes back to this.
A simple template looks like this, in outline.
Instructions: answer only from the context. Say "I don't know" if the context lacks the answer. Cite sources by number.
Context: [1] title and text. [2] title and text. [3] title and text.
Question: the user's question.
The wording matters less than the structure, and you should test it. Small changes to the instruction can change how often the model refuses, hedges or over-answers.
Citations and showing sources
A strength of RAG is that answers can point to their sources. Because you know which chunks you put in the prompt, you can ask the model to cite them, and your application can turn "[2]" into a link to the right document and section. Users can then check the answer, which builds trust and catches errors.
Two cautions. A model can cite a source that does not support its claim, so a citation is a pointer and not proof. And the model can cite a chunk that was in the prompt but misread it. Lesson 5.3 covers grounding and checking citations. For now, design the chunk metadata, title, section and link, so that citations are possible from the start.
Tokens, cost and delay for one question
Every question costs money and time, and RAG makes both larger than a plain call, because of the retrieved text. The arithmetic is straightforward. Count the tokens that go in and the tokens that come out, and multiply by the prices. Model providers usually charge separately for input and output tokens, and output tokens usually cost more per token. The prices below are examples only; read your provider's current price list.
For the imagined call above, the input is the instructions (400), the conversation (300), six chunks of 500 tokens (3,000) and the question (40), a total of 3,740 tokens. The output is the answer, 300 tokens. If an example price is ₹30 per million input tokens and ₹120 per million output tokens, the cost of one question is 3,740 × 30 ÷ 1,000,000 + 300 × 120 ÷ 1,000,000 = ₹0.112 + ₹0.036 = ₹0.148, about 15 paise. There is also a small cost to embed the question and, if you use one, to rerank. At 100,000 questions a month, the generation cost is about ₹14,800, a figure worth knowing before you launch.
Delay also adds up. A user waits for each stage in sequence. The typical pieces are: embedding the question (tens of milliseconds), the vector search (tens of milliseconds), an optional reranker (tens to a few hundred milliseconds), then the language model, which is usually the largest part. The model has a delay before the first word appears and then writes at some rate, so a longer answer takes longer to finish. Lesson 3.3 explained streaming, which shows words as they are produced so that the user feels the answer starting sooner. For planning, add up estimates and then measure.
Why quality is the product of stages
When a RAG system gives a wrong answer, the fault can be in any stage. It helps to think of each stage as having a success rate and to see that the overall rate is the product of them.
Suppose that, on your test questions, the right chunk is retrieved in the top 6 on 85 per cent of questions. Given that it is retrieved, the model uses it correctly and stays faithful on 92 per cent. And given a correct and faithful answer, the answer is complete and clearly written on 94 per cent. The overall success rate is 0.85 × 0.92 × 0.94 = 0.735, about 74 per cent. No stage is terrible, yet one answer in four is flawed.
This view tells you where to work. If you improve retrieval from 85 to 95 per cent, the overall rate rises to 0.95 × 0.92 × 0.94 = 0.82. If you improve generation from 92 to 97 per cent, it rises to 0.85 × 0.97 × 0.94 = 0.775. Retrieval is the larger gain in this example. Measuring each stage separately, rather than only the final answer, shows you which fix pays. Module 6 covers how to build such tests.
Keeping it fresh and safe
Two practical matters shape a real system.
Freshness. Documents change. Decide how updates reach the index: re-run ingestion on a schedule, or re-embed a document when its source changes. Store a last-updated date with each chunk, and consider showing it to users or preferring newer content. Remove documents that have been retired, so that the bot does not quote an old policy.
Permissions. If different users may see different documents, retrieval must respect that, as Lesson 4.2 showed, by filtering during the search. Never rely on the model to hide what it was shown. If a chunk is in the prompt, assume the user could see it.
Privacy. Questions and documents may contain personal data. Know where they are sent: a hosted embedding service and a hosted model both receive them. Check your data rules, and log carefully.
Untrusted text. Retrieved documents can contain text that tries to steer the model, whether by accident or on purpose. Treat retrieved text as data, keep instructions separate and limit what the model can do. Module 8 returns to this.
A first version, and what to test
A good first RAG system is small and measurable. Here is a plan.
1. Choose a narrow scope. One collection, such as the returns policy or the help centre for one product.
2. Collect 30 to 50 real questions and the passages that answer them. Include a few that the documents cannot answer, to test the "I don't know" behaviour.
3. Build the simplest pipeline: clean, chunk by structure at about 300 tokens, embed, flat or simple index, retrieve the top 5, a grounded prompt, answer with citations.
4. Measure the retrieval hit rate at 5, and read every wrong answer. Sort the failures into: not retrieved, retrieved but ignored, answered wrongly from the right text, not answerable and handled badly.
5. Fix the largest group first, one change at a time, and re-measure.
6. Only then add reranking, hybrid search, query rewriting, caching and so on, each of which should earn its place by improving the measure.
The temptation is to add every technique at once. Resist it. Each addition is more to run and more to break, and without measurement you cannot tell whether it helped.
Three worked examples
Example 1: a help-centre assistant. An online bank has 900 help articles. The team ingests them with structure-aware chunks of about 250 tokens, with article and section titles prepended, and a hybrid search. The prompt tells the model to answer only from the context, cite the source and, if unsure, to direct the user to the contact page. On 60 test questions, the right chunk appears in the top 5 for 51, a hit rate of 85 per cent. Reading the nine misses, the team finds that six are questions in a different wording from the article, and three are about topics not covered at all. They add a query-rewriting step, and for the uncovered topics rely on the "I don't know" answer. The hit rate rises to 92 per cent.
Example 2: an internal policy bot. A company's HR documents sit in many folders, with differing permissions. The team's first version retrieves across everything, and an employee sees a snippet from a document they should not have access to. The fix is to add each document's access group as metadata and to filter during retrieval by the user's groups. The incident leads the team to treat permission filtering as a requirement of the first release, and not as a later improvement.
Example 3: contract questions. A legal team wants answers from long contracts. Small chunks lose clause context, so the team retrieves small chunks but passes the whole clause and its definitions to the model, using parent-child retrieval from Lesson 4.3. They also ask for the exact clause number in every answer, and have a lawyer review a sample each week. The pipeline is the same shape, but each stage is tuned to the documents, and a human checks the results, because the cost of an error is high.
Common mistakes
Starting with every advanced technique. Build the simple version, measure, then add.
Skipping the "I don't know" instruction, so the model guesses when retrieval fails.
Measuring only the final answer. Measure retrieval separately, or you will not know where to fix.
Ignoring permissions until after launch.
Letting the index go stale, so that the bot quotes outdated documents.
Forgetting cost and delay, and finding that the prompt is mostly retrieved text.
Treating citations as proof. Check that the cited chunk supports the claim.
Never reading the failures. The wrong answers tell you more than the average.
Key takeaways
RAG looks up relevant passages from your own documents at question time, puts them in the prompt and asks the model to answer from them. It keeps knowledge outside the model, so it can be updated, cited and permissioned.
The pipeline has two halves. Ingestion, done ahead of time, collects, cleans, chunks, embeds and stores documents. Answering, done per question, embeds the question, retrieves, optionally reranks, builds a grounded prompt, generates and logs.
The prompt should tell the model to use only the context, to cite sources and to say it does not know when the context lacks the answer.
Retrieved text is usually most of the input, so chunk size and the number of chunks drive cost and delay. Estimate both before you launch.
Overall quality is the product of the stage rates, so measure each stage and fix the weakest.
Build a small, measurable first version, then add techniques one at a time. Treat freshness, permissions and privacy as requirements.
Check yourself
1. Why is RAG usually a better way than fine-tuning to give a model facts that change twice a year?
You can update the documents and re-embed the changed chunks without retraining, and the model can cite the source. Fine-tuning would need retraining and offers no sources.
2. Name the five steps of ingestion.
Collect, clean, chunk, embed and store.
3. A prompt has 300 instruction tokens, 5 chunks of 400 tokens and a 30-token question. How many input tokens is that?
300 + 2,000 + 30 = 2,330 tokens.
4. Retrieval finds the right chunk 90 per cent of the time, the model uses it faithfully 90 per cent of the time and the answer is clear 95 per cent of the time. What share of answers is good?
0.90 × 0.90 × 0.95 = 0.77, about 77 per cent.
5. Why should the prompt say what to do when the context does not contain the answer?
Retrieval sometimes brings back chunks without the answer, and without permission to say so the model may guess or use outside knowledge.
6. Why should permission filtering happen in retrieval and not in the model?
Anything placed in the prompt may be shown to the user, so the safe approach is to never retrieve what they may not see.
Try this
Set aside 30 to 45 minutes. You need a spreadsheet and a few real documents; no code is needed.
1. Choose a small collection you know, such as a returns policy, a product manual or a set of meeting notes. Write what a user would ask of it.
2. Write 15 realistic questions. For each, note the passage that answers it, and mark two or three that the documents cannot answer.
3. Draw your pipeline on one page: the ingestion steps and the answering steps, with the choices you would make at each, such as chunk size, number of chunks and whether to rewrite questions.
4. Write the grounding instruction for the prompt, including what the model should say when the context lacks the answer, and the format for citations.
5. Use the cost simulator with your choices and a price from your provider. Write the cost of one question and of a month at a volume you expect, and the share of the input that is retrieved text.
6. Use the delay simulator with your own estimates and write when the user would see the first words and the whole answer.
7. Estimate the three stage rates for your first version, using the quality simulator, and name the stage you would test first. Write how you would measure each rate with your 15 questions.
A good result is a one-page pipeline diagram, a grounding instruction, a cost and delay estimate with its assumptions, a list of test questions including unanswerable ones and a note on which stage you will measure and improve first.
Tags: AI Engineering RAG Retrieval-augmented generation LLM applications Pipelines