RAG Pipeline
Understand the complete Retrieval-Augmented Generation pipelineβfrom preparing knowledge and creating embeddings to retrieval, reranking, context construction, and LLM generation.
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.
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.
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.
Documents
Policies, manuals, guides, FAQs, and reports.
Database
Structured records that the application can expose safely.
KNOWLEDGE BASE
Maintained articles or internal support content.
Trusted information
Use content that is relevant, current, and approved for retrieval.
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.
Messy source
Headers, navigation, repeated text, formatting noise, and irrelevant content may be present.
Searchable content
Clean text is retained with useful metadata such as title, source, section, date, or access scope.
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.
A 100-page manual can be split into sections about installation, configuration, troubleshooting, and maintenance.
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.
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.
The same embedding model or a compatible strategy is normally used for user queries so their vectors can be compared with stored chunk vectors.
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.
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.
This is the question the retrieval system must understand.
The application may apply query rewriting, access checks, or other preprocessing before retrieval.
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.
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.
Candidate set
For example, retrieve the top 20 potentially useful chunks.
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.
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.
Who can access it?
Apply tenant, role, region, product, or other authorization rules.
Which is most relevant?
Re-score retrieved candidates with a stronger relevance model when needed.
What reaches the LLM?
Keep the most useful evidence within the available context budget.
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.
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.
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.
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)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.
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.
Document title
Show which knowledge source contributed to the answer.
Section or page
Point users toward the relevant part of the source when available.
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.
Offline vs Online Parts of RAG
It is useful to divide the architecture into ingestion time and query time.
- Collect documents
- Clean and parse text
- Chunk content
- Create embeddings
- Store vectors and metadata
- Receive the question
- Create query embedding
- Retrieve candidates
- Filter or rerank
- Build context and generate
Complete RAG Pipeline
Simple End-to-End Python Mental Model
The following code models the flow without connecting to a real vector database or LLM API.
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.
Where the Pipeline Can Fail
If the source is wrong or outdated, retrieval can return misleading evidence.
Important information can be split across chunks or mixed with unrelated content.
The correct evidence may never enter the candidate set.
Useful evidence may be buried below weaker candidates.
Too much retrieved text can increase cost and reduce focus.
The model may still misunderstand or misuse the supplied evidence.
How to Improve a RAG Pipeline
Improve sources
Keep documents accurate, current, and well structured.
Improve chunking
Use boundaries and sizes that preserve useful meaning.
Improve retrieval
Tune embeddings, Top-K, filters, and search strategy.
Improve ranking
Add reranking when the candidate ordering needs improvement.
Improve context
Send concise, relevant evidence rather than everything retrieved.
Evaluate end to end
Measure retrieval and answer quality separately and together.
RAG Evaluation: Measure Every Stage
Evaluating only the final answer can hide retrieval problems. A useful RAG evaluation strategy measures multiple stages.
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.
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
Collect, clean, and chunk knowledge.
Create embeddings and store vectors with metadata.
Search for relevant candidates for the user's query.
Improve candidate ordering when needed.
Build concise context from selected evidence.
Give the context and question to the LLM.
Return useful source information when supported.
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.