Generative AI

Understanding Retrieval-Augmented Generation (RAG)

✍️ Affan Shah•2025-02-18•10 min read
#RAG#LangChain#Ollama#Vector Database#LLM

Retrieval Augmented Generation (RAG)

Author: Affan Shah


Introduction

Large Language Models (LLMs) like GPT, Llama, and Mistral are incredibly powerful. However, they suffer from one major limitation:

They only know what they were trained on.

If you ask them about:

  • Your company's documents
  • Private PDFs
  • Internal knowledge base
  • Research papers
  • Custom datasets

they have absolutely no knowledge of those documents.

This is where Retrieval Augmented Generation (RAG) comes in.

Instead of forcing the model to memorize everything through fine-tuning, we retrieve relevant information at runtime and provide it as context to the language model.

The model then generates an answer using both:

  • Its own knowledge
  • Retrieved documents

What is Retrieval Augmented Generation?

Retrieval Augmented Generation is an AI architecture that combines:

  • Information Retrieval
  • Semantic Search
  • Large Language Models

into one pipeline.

Instead of asking the LLM directly,

User
      │
      ▼
     LLM
      │
      ▼
 Answer

we introduce a retrieval step.

                User Query
                     │
                     ▼
             Query Embedding
                     │
                     ▼
          Vector Database Search
                     │
                     ▼
          Retrieve Relevant Chunks
                     │
                     ▼
              Prompt + Context
                     │
                     ▼
                    LLM
                     │
                     ▼
                  Response

This dramatically improves accuracy.


Why RAG?

Without RAG

❌ Hallucinations

❌ Outdated information

❌ Cannot answer questions about private documents

With RAG

✅ Uses company documents

✅ Retrieves research papers

✅ Answers using your own knowledge base

✅ No expensive fine-tuning


Components of a RAG System

A production RAG pipeline consists of several components.

Documents

↓

Document Loader

↓

Text Splitter

↓

Embedding Model

↓

Vector Database

↓

Retriever

↓

Reranker (Optional)

↓

Prompt Template

↓

Large Language Model

↓

Answer

Let's understand every component.


1. Document Loader

The first step is loading documents.

Documents may include

  • PDF
  • DOCX
  • TXT
  • Markdown
  • HTML
  • CSV
  • Websites

Libraries like LangChain provide dedicated loaders.

Example:

from langchain_community.document_loaders import PyPDFLoader

loader = PyPDFLoader("rag.pdf")

documents = loader.load()

The loader converts files into LangChain Document objects.


2. Text Splitting

LLMs cannot process hundreds of pages at once.

Instead, documents are broken into small chunks.

Example

100-page PDF

↓

500 chunks

This process is called Chunking.

LangChain provides

RecursiveCharacterTextSplitter

Example

from langchain.text_splitter import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50
)

chunks = splitter.split_documents(documents)

Why Overlap?

Suppose one chunk ends here:

Machine Learning is a subset...

The next chunk begins:

...of Artificial Intelligence.

Without overlap,

important context gets lost.

The overlap preserves continuity.


3. Embeddings

Computers cannot understand words.

They understand numbers.

Embeddings convert text into vectors.

Example

"I love AI"

↓

[0.45, -0.91, 0.22, ...]

Every sentence becomes a high-dimensional vector.

Similar meanings produce similar vectors.

Example

Cat

↓

[0.12,0.55...]

Dog

↓

[0.10,0.59...]

Car

↓

[-0.81,0.11...]

Cat and Dog are closer than Car.


Embedding Models

Popular embedding models include

  • BAAI bge-large
  • Nomic Embed
  • all-MiniLM-L6-v2
  • Instructor XL
  • OpenAI text-embedding-3-large

Embedding models are completely different from LLMs.

They only convert text into vectors.


4. Vector Database

After embeddings are generated,

they are stored inside a Vector Database.

Unlike SQL databases,

vector databases search based on meaning rather than exact words.

Popular vector databases

  • ChromaDB
  • Pinecone
  • Weaviate
  • FAISS
  • Milvus
  • Qdrant

Example

"What is Machine Learning?"

↓

Embedding

↓

Nearest vectors

↓

Relevant paragraphs

5. Retrieval

This is the heart of RAG.

When the user asks a question,

the same embedding model converts the query into a vector.

Example

User Question

↓

Embedding

↓

Vector Search

↓

Top K Documents

Usually,

Top 3–10 documents are retrieved.

Those documents become context for the LLM.


Cosine Similarity

How does the vector database know which document is relevant?

It compares vectors.

The most common technique is Cosine Similarity.

Formula

Similarity(A,B)

=

A·B

────────────

||A|| ||B||

Instead of comparing values,

it compares the angle between vectors.

Example

Sentence A

"I love AI"

Sentence B

"I enjoy Artificial Intelligence"

These vectors point in nearly the same direction.

Cosine Similarity

0.98

Very similar.

Example

"I love AI"

"I like Pizza"

Similarity

0.12

Very different.

Cosine Similarity ranges from

1.0

Perfect Match

↓

0

Unrelated

↓

-1

Opposite Direction

6. Reranking

Vector search retrieves relevant documents.

But the best result is not always first.

Example

Retrieved

Document 3

Document 9

Document 1

Document 15

A reranker examines these retrieved documents more carefully.

It reorders them.

Result

Document 9

Document 3

Document 15

Document 1

Now,

the LLM receives much higher-quality context.

Popular rerankers include

  • BAAI BGE Reranker
  • Cohere Rerank
  • Cross Encoder

Reranking significantly improves answer quality.


Prompt Construction

After retrieval,

the prompt is built.

Example

You are an AI assistant.

Use ONLY the context below.

Context:

...

Question:

What is Retrieval Augmented Generation?

The LLM now has the information it needs.


Large Language Model

Finally,

the prompt reaches the language model.

Popular models

  • Llama 3
  • Mistral
  • Gemma
  • DeepSeek
  • Qwen

The LLM generates an answer based only on the retrieved documents.


Ollama

Ollama is an open-source framework that allows developers to run Large Language Models locally.

Instead of sending prompts to cloud APIs,

the model runs directly on your computer.

Benefits

  • Privacy
  • Offline inference
  • No API costs
  • Fast local development

Example

ollama run llama3

Download a model

ollama pull llama3

Run Mistral

ollama run mistral

Run DeepSeek

ollama run deepseek-r1

Ollama supports dozens of open-source models with a simple command-line interface.


Common Libraries Used in RAG

LangChain

Provides building blocks for AI applications.

It includes

  • Document Loaders
  • Prompt Templates
  • Retrievers
  • Chains
  • Memory
  • Agents

ChromaDB

An open-source vector database used to store embeddings.

Useful for small to medium-sized RAG applications.


FAISS

Facebook AI Similarity Search.

A high-performance vector search library developed by Meta.

Very popular for local semantic search.


Sentence Transformers

Used to generate embeddings.

Provides hundreds of pretrained embedding models.


Ollama

Runs open-source language models locally.

Supports

  • Llama
  • Mistral
  • Gemma
  • DeepSeek
  • Phi
  • Qwen

Transformers

Developed by Hugging Face.

Provides thousands of pretrained models including

  • BERT
  • GPT
  • T5
  • Llama
  • Mistral

Advantages of RAG

✅ Reduced hallucinations

✅ Private knowledge support

✅ No expensive fine-tuning

✅ Works with constantly changing documents

✅ Better factual accuracy


Limitations

❌ Retrieval quality determines answer quality.

❌ Poor embeddings lead to poor search.

❌ Large vector databases require optimization.

❌ Bad chunking reduces context quality.


Real-World Applications

RAG is widely used in:

  • AI Chatbots
  • Customer Support
  • Legal Document Search
  • Medical Assistants
  • Enterprise Knowledge Bases
  • Research Assistants
  • PDF Question Answering
  • Coding Assistants

Conclusion

Retrieval Augmented Generation has become one of the most important architectures in modern AI systems. Instead of relying solely on a language model's internal knowledge, RAG combines semantic search with powerful LLMs to produce responses that are accurate, grounded, and context-aware.

By understanding document ingestion, chunking, embeddings, vector databases, cosine similarity, retrieval, reranking, and local inference with Ollama, you now have a solid foundation for building production-ready AI applications.

As an aspiring AI Systems Engineer, mastering these concepts will enable you to build scalable chatbots, document assistants, enterprise search systems, and intelligent agents that leverage custom knowledge effectively.


Author

Affan Shah

Aspiring AI Systems Engineer passionate about Machine Learning, Deep Learning, Large Language Models, RAG systems, AI Infrastructure, and MLOps.