LESSON 52 Β· RAG

RAG Pipeline

Understand the complete Retrieval-Augmented Generation pipelineβ€”from preparing knowledge and creating embeddings to retrieval, reranking, context construction, and LLM generation.

35 min readβ€’Beginnerβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain the major stages of a production RAG pipeline.
  • Distinguish ingestion-time work from query-time work.
  • Understand how chunking, embeddings, vector search, filtering, and reranking connect.
  • Explain how retrieved chunks become LLM context.
  • Trace a user question from retrieval through generation.
  • Identify common failure points in a RAG system.
  • Understand how to evaluate retrieval and generation separately.
1

The RAG Pipeline at a Glance

A Retrieval-Augmented Generation pipeline connects a user's question to a knowledge source before an LLM generates the final answer.

QuestionUser asks something
β†’
RetrieveFind relevant chunks
β†’
AugmentBuild useful context
β†’
GenerateLLM answers
Core idea:RAG separates finding information from generating an answer.
2

Stage 1: Collect the Knowledge

Before users ask questions, the system needs a reliable knowledge source. Sources can include PDFs, web pages, product documentation, databases, support articles, or internal documents.

SOURCE

Documents

Policies, manuals, guides, FAQs, and reports.

SOURCE

Database

Structured records that the application can expose safely.

SOURCE

KNOWLEDGE BASE

Maintained articles or internal support content.

GOAL

Trusted information

Use content that is relevant, current, and approved for retrieval.

3

Stage 2: Load and Clean Documents

Raw files are rarely ready for retrieval. An ingestion process extracts text, removes unnecessary noise, and preserves useful structure and metadata.

RAW

Messy source

Headers, navigation, repeated text, formatting noise, and irrelevant content may be present.

β†’
PREPARED

Searchable content

Clean text is retained with useful metadata such as title, source, section, date, or access scope.

4

Stage 3: Chunk the Content

Large documents are divided into smaller retrieval units called chunks. Chunking makes it easier to retrieve only the part that matters to a question.

EXAMPLE 1Product manual

A 100-page manual can be split into sections about installation, configuration, troubleshooting, and maintenance.

EXAMPLE 2Company policy

A long policy can be split into meaningful sections so a question about leave retrieves the relevant rule instead of the entire document.

Chunk size and boundaries affect retrieval quality, so chunking is an important part of the pipeline.

5

Stage 4: Create Embeddings

Each chunk can be converted into a numerical vector called an embedding. The vector represents useful semantic information about the text.

Chunkβ€œRefunds are allowed within 30 days.”
β†’
Embedding modelConverts text to numbers
β†’
Vector[0.12, -0.08, …]

The same embedding model or a compatible strategy is normally used for user queries so their vectors can be compared with stored chunk vectors.

6

Stage 5: Store Vectors and Metadata

The vectors are stored in a vector index or vector database along with the information needed to identify and filter the original content.

VECTOR[0.12, -0.08, …]Semantic representation
TEXTRefund policy…Original chunk
METADATApolicy Β· HRFiltering and control
SOURCEhr-policy.pdfTraceability
7

Stage 6: Receive the User Query

When a user asks a question, the online part of the RAG pipeline begins. The application first receives and validates the query.

USER QUERYβ€œWhat is the refund period?”

This is the question the retrieval system must understand.

QUERY PREPARATIONNormalize if needed

The application may apply query rewriting, access checks, or other preprocessing before retrieval.

8

Stage 7: Embed the Query

The query can be converted into an embedding using an embedding model. This creates a vector that can be compared with stored document vectors.

User questionβ€œHow long can I request a refund?”
β†’
Query embeddingVector representation
β†’
Similarity searchCompare with stored chunks
9

Stage 8: Retrieve Candidate Chunks

The retriever searches the vector index and returns a candidate set of relevant chunks. The system often retrieves more candidates than it finally sends to the LLM.

RETRIEVAL

Candidate set

For example, retrieve the top 20 potentially useful chunks.

β†’
FINAL CONTEXT

Smaller set

After filtering or reranking, perhaps 5 strong chunks are selected for generation.

This is where concepts such as Top-K, metadata filtering, hybrid search, and similarity search become useful.

10

Stage 9: Filter and Rerank When Needed

Retrieval can be improved by applying metadata filters or a second-stage reranker. These steps help control which candidates are considered and which evidence is strongest.

FILTER

Who can access it?

Apply tenant, role, region, product, or other authorization rules.

RERANK

Which is most relevant?

Re-score retrieved candidates with a stronger relevance model when needed.

SELECT

What reaches the LLM?

Keep the most useful evidence within the available context budget.

11

Stage 10: Build the Context

The selected chunks are assembled into a context that the LLM can understand. Good context is relevant, clearly separated, and includes useful source information when appropriate.

</> Python
retrieved_chunks = [
    "Refunds are allowed within 30 days of purchase.",
    "Refund requests can be submitted through the support portal."
]

context = "\n\n".join(retrieved_chunks)

print(context)

This example only demonstrates context construction. A production retriever would obtain the chunks from a search system.

12

Stage 11: Augment the Prompt

RAG adds the retrieved context to the model input. The prompt should clearly tell the model how to use the supplied evidence and what to do when the evidence is insufficient.

</> Python
question = "How long do I have to request a refund?"
context = "Refunds are allowed within 30 days of purchase."

prompt = f"""
Answer the question using the context below.
If the context does not contain the answer, say that
there is not enough information.

Context:
{context}

Question:
{question}
"""

print(prompt)
13

Stage 12: Generate the Answer

The LLM receives the question plus the selected context and generates the response. The generator is not responsible for finding the documents; retrieval has already done that job.

Retrieved evidenceRelevant chunks
+
User questionWhat the user wants
β†’
LLMGenerates response
β†’
AnswerUseful response
Important:A strong generator cannot fully compensate for missing or irrelevant retrieval results. RAG quality depends on the whole pipeline.
14

Stage 13: Return Sources and Citations

Many RAG applications return source references along with the answer. This can help users inspect the evidence and can make the system easier to audit.

SOURCE

Document title

Show which knowledge source contributed to the answer.

LOCATION

Section or page

Point users toward the relevant part of the source when available.

TRACE

Chunk metadata

Keep enough information to connect retrieved text to its source.

Citations do not automatically prove that an answer is correct. They are useful only when they accurately correspond to the evidence used.

15

Offline vs Online Parts of RAG

It is useful to divide the architecture into ingestion time and query time.

Ingestion time
  • Collect documents
  • Clean and parse text
  • Chunk content
  • Create embeddings
  • Store vectors and metadata
Query time
  • Receive the question
  • Create query embedding
  • Retrieve candidates
  • Filter or rerank
  • Build context and generate
16

Complete RAG Pipeline

DocumentsSource knowledge
β†’
ChunkingRetrieval units
β†’
EmbeddingsVectors
β†’
Vector DBSearchable index
User queryQuestion
β†’
RetrieveFind candidates
β†’
RerankImprove ordering
β†’
ContextSelected evidence
ContextEvidence
+
QuestionUser intent
β†’
LLMGeneration
β†’
AnswerResponse + sources
17

Simple End-to-End Python Mental Model

The following code models the flow without connecting to a real vector database or LLM API.

</> Python
documents = [
    "Refunds are allowed within 30 days.",
    "Standard shipping takes 3 to 5 business days.",
    "Premium support is available on business plans."
]

question = "How long is the refund period?"

# Simplified retrieval for learning purposes.
retrieved = [documents[0]]

context = "\n".join(retrieved)
answer = f"Using the retrieved context: {context}"

print(answer)

The real pipeline replaces the simplified retrieval step with embeddings, vector search, filtering, reranking, and an actual LLM call.

18

Where the Pipeline Can Fail

01Bad source data

If the source is wrong or outdated, retrieval can return misleading evidence.

02Poor chunking

Important information can be split across chunks or mixed with unrelated content.

03Weak retrieval

The correct evidence may never enter the candidate set.

04Bad ranking

Useful evidence may be buried below weaker candidates.

05Context overload

Too much retrieved text can increase cost and reduce focus.

06Generation errors

The model may still misunderstand or misuse the supplied evidence.

19

How to Improve a RAG Pipeline

STEP 1

Improve sources

Keep documents accurate, current, and well structured.

STEP 2

Improve chunking

Use boundaries and sizes that preserve useful meaning.

STEP 3

Improve retrieval

Tune embeddings, Top-K, filters, and search strategy.

STEP 4

Improve ranking

Add reranking when the candidate ordering needs improvement.

STEP 5

Improve context

Send concise, relevant evidence rather than everything retrieved.

STEP 6

Evaluate end to end

Measure retrieval and answer quality separately and together.

20

RAG Evaluation: Measure Every Stage

RETRIEVAL RECALLWas the relevant evidence retrieved?
PRECISION@KHow much of the retrieved set is useful?
RANKINGAre the strongest chunks near the top?
GROUNDEDNESSDoes the answer stay supported by context?
ANSWER QUALITYDoes the response solve the user's task?
LATENCY & COSTIs the quality improvement worth the added system work?

Evaluating only the final answer can hide retrieval problems. A useful RAG evaluation strategy measures multiple stages.

21

Practice: Trace the Pipeline

For the question β€œWhat is the refund period?”, describe what should happen at each stage: document source β†’ chunk β†’ embedding β†’ query embedding β†’ retrieval β†’ reranking β†’ context β†’ LLM β†’ answer.

TASK

Explain each transition

Identify what data enters and leaves each stage. Then decide where you would store the source title and access-control metadata.

Quick Quiz

1. What are the two major phases of a RAG system?

Knowledge ingestion/preparation and query-time retrieval plus generation.

2. Why are documents chunked?

To create smaller retrieval units so the system can find and pass only relevant parts of a larger source.

3. What happens after candidate retrieval?

The system can apply metadata filters, rerank candidates, and select useful chunks for the final context.

4. Does the vector database generate the final answer?

No. It supports retrieval. The selected context is then supplied to an LLM for generation.

5. Why evaluate retrieval separately?

Because a poor final answer may originate from missing evidence, weak ranking, bad context construction, or generation rather than one single component.

6. What is the augmentation step?

Adding selected retrieved context to the model input so the LLM can use that evidence when generating the answer.

30-Second Recap

1. Prepare

Collect, clean, and chunk knowledge.

2. Index

Create embeddings and store vectors with metadata.

3. Retrieve

Search for relevant candidates for the user's query.

4. Rerank

Improve candidate ordering when needed.

5. Augment

Build concise context from selected evidence.

6. Generate

Give the context and question to the LLM.

7. Cite

Return useful source information when supported.

8. Evaluate

Measure retrieval, grounding, answer quality, cost, and latency.

Key Takeaways

  • A RAG pipeline combines knowledge preparation, retrieval, context construction, and generation.
  • Documents are commonly cleaned, chunked, embedded, and stored before users ask questions.
  • At query time, the system creates a query representation and retrieves relevant candidates.
  • Metadata filtering and reranking can improve relevance and control.
  • Augmentation means adding selected retrieved evidence to the model input.
  • The LLM generates the final response, but it depends heavily on the quality of the supplied context.
  • RAG should be evaluated at both retrieval and answer-generation levels.
  • A production RAG system also needs security, source freshness, monitoring, cost controls, and reliable update processes.