Skip to main content

Retrieve-Augmented Generation Workflow

RAG, or Retrieval-Augmented Generation, combines two capabilities:
  1. Retrieval: Find relevant information from a knowledge source.
  2. Generation: Use an LLM to generate an answer based on the retrieved information.
Instead of relying only on the knowledge stored inside the LLM, RAG provides external context at query time.

1. What is RAG?

A traditional LLM workflow is:
The problem is that the LLM may:
  • Not know recent information.
  • Not know private or company-specific data.
  • Generate incorrect information.
  • Hallucinate an answer.
RAG improves this by retrieving relevant information before generating the response.

2. Important Components of a RAG System

A complete RAG pipeline usually contains the following components:

3. Document Loading

The first step is collecting data. RAG can retrieve information from:
  • PDF files
  • Text files
  • CSV files
  • Databases
  • Websites
  • APIs
  • Documentation
  • Knowledge bases
  • Company documents
Example:
The documents are loaded and converted into text.

4. Document Preprocessing

Raw documents may contain unnecessary information. Preprocessing can include:
  • Removing unwanted spaces.
  • Removing duplicate content.
  • Cleaning HTML.
  • Removing irrelevant sections.
  • Fixing encoding issues.
  • Normalizing text.
Example:
Good preprocessing improves retrieval quality.

5. Text Chunking

Large documents are usually divided into smaller pieces called chunks. Example:
Instead of embedding an entire 100-page document as one vector, smaller chunks are embedded separately.

Why Chunking is Important

Large chunks may:
  • Contain too much unrelated information.
  • Reduce retrieval precision.
  • Use more LLM context.
Very small chunks may:
  • Lose important context.
  • Split related information.
Example:

6. Chunk Size and Chunk Overlap

Two important RAG parameters are:

Chunk Size

The amount of text stored in each chunk. Example:
or:

Chunk Overlap

Some text is shared between consecutive chunks. Example:
Overlap helps preserve context when important information appears near chunk boundaries.

7. Embeddings

Embeddings convert text into numerical vectors.
Similar meanings should produce vectors that are close together. Example:
Common embedding models include:
  • Sentence Transformers
  • BGE models
  • E5 models
  • OpenAI embedding models

8. Vector Store

A vector store stores embeddings and allows similarity search.
Examples include:
  • FAISS
  • Chroma
  • Pinecone
  • Qdrant
  • Weaviate
  • Milvus
The vector store typically connects each vector with its original content and metadata. Example:

9. Vector Indexing

The vector index organizes embeddings for efficient retrieval.
Different index types involve trade-offs between:
  • Search speed
  • Memory usage
  • Accuracy
  • Scalability
For example, FAISS provides index types such as:
For learning and small datasets:
is a simple starting point.

10. Metadata

Metadata is additional information stored with a chunk. Example:
Metadata allows you to:
  • Show document sources.
  • Filter search results.
  • Retrieve specific document types.
  • Apply access controls.
  • Improve traceability.
A production RAG system should generally store both:

11. Query Processing

When a user asks a question:
The query may be processed before retrieval. Possible query processing techniques include:
  • Query cleaning
  • Query rewriting
  • Query expansion
  • Multi-query retrieval
  • HyDE
  • Intent detection
Example:
This can improve retrieval when the user’s wording differs from the wording in the documents.

12. Query Embedding

The processed query is converted into an embedding using the embedding model.
Example:
The query vector is then compared with vectors stored in the index.

13. Similarity Search

The vector store searches for the closest vectors.
Example:
k=3 means:
Common similarity approaches include:
  • Cosine similarity
  • Dot product / inner product
  • Euclidean distance

14. Dense Retrieval

Dense retrieval uses embeddings to search based on semantic meaning. Example:
Even though the exact words are different, embeddings can identify that they have similar meanings. This is one of the major advantages of vector search.

15. Sparse Retrieval

Sparse retrieval is based mainly on keywords. A common algorithm is:
Example:
Sparse retrieval can perform well for:
  • Exact keywords
  • Product names
  • IDs
  • Error codes
  • Technical terms

16. Hybrid Search

Hybrid search combines:
Work flow:
Hybrid search can improve retrieval because semantic and keyword search have different strengths.

17. Reranking

Initial vector search may return relevant but poorly ordered results. A reranker takes the retrieved chunks and reorders them.
The first stage retrieves candidates quickly. The reranker performs a more detailed relevance check. This is often called:

18. Context Construction

The retrieved chunks are combined before sending them to the LLM. Example:
The LLM receives both the context and the user question.

19. Prompt Construction

A typical RAG prompt looks like:
A stronger instruction can be:
This helps reduce hallucination.

20. Generation

The LLM receives:
Then it generates the answer.
The LLM can be:
  • GPT models
  • Llama models
  • Mistral models
  • Gemma models
  • Other language models

21. Grounded Generation

A good RAG answer should be grounded in the retrieved documents. Example:
The answer should be based on retrieved evidence rather than unsupported model knowledge.

22. Citations and Source Attribution

A production RAG system should ideally provide sources. Example:
This improves:
  • Trust
  • Transparency
  • Debugging
  • Verification
This is why metadata is important.

23. Context Window Management

LLMs have a limited context window. You cannot always send every retrieved document. Therefore, a RAG system must select:
instead of:
Common strategies include:
  • Top-K retrieval
  • Reranking
  • Context compression
  • Summarization
  • Token limits

24. Context Compression

Sometimes retrieved chunks contain too much irrelevant information. Context compression reduces them to only the important information.
Benefits:
  • Lower token usage
  • Faster generation
  • More focused context

25. Parent-Child Retrieval

A useful advanced technique is parent-child retrieval. Example:
The smaller child chunks are used for precise retrieval. After finding a matching child chunk:
This improves the balance between:
  • Retrieval precision
  • Context completeness

26. Multi-Query Retrieval

A single user query may not retrieve all relevant information. Example:
The system can generate multiple search queries:
Each query retrieves documents. The results are then combined.

27. HyDE

HyDE stands for Hypothetical Document Embeddings. The workflow is:
The hypothetical answer can sometimes produce a better search representation than the original short query.

28. Retrieval Failure

Sometimes the retriever does not find relevant information. Example:
The system should not blindly send irrelevant chunks to the LLM. Possible strategies:
  • Similarity score thresholds
  • Reranking
  • Query rewriting
  • Fallback search
  • Asking the user for clarification
  • Returning “I could not find relevant information”
This is important for reducing hallucinations.

29. RAG Evaluation

A RAG system should be evaluated at multiple levels.

Retrieval Evaluation

Ask:
Common measures include:
  • Precision@K
  • Recall@K
  • MRR
  • NDCG

Generation Evaluation

Ask:
Evaluate:
  • Correctness
  • Relevance
  • Faithfulness
  • Completeness

End-to-End Evaluation

Ask:

30. Important RAG Problems

Hallucination

The LLM generates unsupported information. Solution:
  • Ground answers in retrieved context.
  • Use clear prompts.
  • Use source citations.
  • Add refusal behavior when evidence is missing.

Poor Retrieval

Relevant documents are not retrieved. Solution:
  • Improve chunking.
  • Use better embedding models.
  • Add hybrid search.
  • Add reranking.
  • Improve queries.

Lost Context

Important information is split between chunks. Solution:
  • Use chunk overlap.
  • Adjust chunk size.
  • Use parent-child retrieval.

Too Much Context

Too many chunks may confuse the LLM. Solution:
  • Use Top-K retrieval.
  • Add reranking.
  • Use context compression.

31. Basic RAG Pipeline

The complete basic pipeline can be divided into two stages.

Indexing Stage

Retrieval and Generation Stage


32. Combining Embeddings + FAISS + LLM

This connects directly to the topics that already learned.

33. Minimal RAG Pseudocode


Order