Building a RAG Pipeline with LLM Embeddings and Scikit-learn A tutorial published on Machine Learning Mastery details how to build a lightweight, in-memory retrieval augmented generation (RAG) pipeline using scikit-learn's NearestNeighbors with cosine distance for vector retrieval, sentence-transformers for local embeddings, and a lightweight open-source Hugging Face LLM for generation, avoiding paid APIs and managed vector databases. The guide uses a nine-document dataset of Asian country descriptions hosted in a public GitHub repository and recommends running the pipeline on Google Colab's free T4 GPU. In this article, you will learn how to build a lightweight, end-to-end RAG pipeline using scikit-learn for vector retrieval and open-source models for embeddings and text generation, without the use of paid APIs or heavyweight frameworks. Topics we will cover include: - How to download a document dataset, chunk it into semantic pieces, and generate embeddings using a local sentence-transformer model. - How to build a custom retriever class using scikit-learn’s NearestNeighbors with cosine distance as a stand-in for a vector database. - How to wire the retriever together with a lightweight open-source LLM to produce a fully functional, in-memory RAG pipeline. Introduction Modern retrieval augmented generation RAG systems are often thought of as inseparable from an expansive ecosystem of frameworks, including typically expensive, managed vector databases to store document collections for retrieval. At the core, however, RAG systems rely on a fairly simple notion: calculating distances between semantic vectors representing texts. It’s not strictly necessary to navigate the intricacies of a dedicated AI infrastructure when working with a small-to-medium-sized corpus, prototyping a new proof-of-concept, or deploying to environments under cost constraints. Instead, we can use scikit-learn procedures together with open-source LLMs to build transparent, fast RAG pipelines that remain fully functional. This article shows how. Step-by-Step Guide The solution provided below is completely free to use, relying on sentence-transformers to build local embeddings from a text dataset and a lightweight pre-trained LLM from Hugging Face for the generation stage. If you need to brush up on basic RAG concepts, check out this article https://machinelearningmastery.com/understanding-rag-part-ii-how-classic-rag-works/ first. While the pipeline can be implemented and run in a local IDE, for demonstration purposes I recommend running the entire pipeline on Google Colab, using its free T4 GPU for more efficient execution. If you follow this approach, start by installing and importing the required libraries and dependencies: python pip install -q sentence-transformers transformers import os import glob import urllib.request import zipfile import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors from sentence transformers import SentenceTransformer from transformers import pipeline print "Libraries loaded successfully " 12345678910111213 pip install -q sentence-transformers transformers import osimport globimport urllib.requestimport zipfileimport numpy as npimport pandas as pdfrom sklearn.neighbors import NearestNeighborsfrom sentence transformers import SentenceTransformerfrom transformers import pipeline print "Libraries loaded successfully " I made available a small dataset containing nine text files — brief descriptions of Asian countries — in a public GitHub repository. You can download it, extract the files, and save the texts in a simple list as follows: Downloading and extracting the toy dataset, containing 9 documents url = "https://github.com/gakudo-ai/open-datasets/blob/main/asia documents.zip?raw=true" zip path = "asia documents.zip" extract dir = "asia documents" urllib.request.urlretrieve url, zip path with zipfile.ZipFile zip path, 'r' as zip ref: zip ref.extractall extract dir Reading all extracted text files documents = for filepath in glob.glob f"{extract dir}/ / .txt", recursive=True : with open filepath, 'r', encoding='utf-8' as file: documents.append file.read print f"Loaded {len documents } documents." If the zip contained a CSV instead, you'd use pd.read csv here. 1234567891011121314151617 Downloading and extracting the toy dataset, containing 9 documentsurl = "https://github.com/gakudo-ai/open-datasets/blob/main/asia documents.zip?raw=true"zip path = "asia documents.zip"extract dir = "asia documents" urllib.request.urlretrieve url, zip path with zipfile.ZipFile zip path, 'r' as zip ref: zip ref.extractall extract dir Reading all extracted text filesdocuments = for filepath in glob.glob f"{extract dir}/ / .txt", recursive=True : with open filepath, 'r', encoding='utf-8' as file: documents.append file.read print f"Loaded {len documents } documents." If the zip contained a CSV instead, you'd use pd.read csv here. The dataset we just loaded will constitute our miniature document base for RAG. We need to put it in the right format — that is, turn the texts into embedding vectors. Before doing that, it is common practice in RAG to chunk documents into smaller, semantic pieces that the embedding model — responsible for mapping pieces of text into numerical embeddings — can process more effectively. The texts in our dataset don’t really require chunking because they are quite short, but we are simulating this step to illustrate best practices in real-world RAG pipelines. We define a native chunking function, using smaller-than-usual values for chunk size and overlap both measured in words so that we can observe some actual effect on our small documents: python def chunk text text, chunk size=25, overlap=5 : """Splits text into chunks natively, without external frameworks.""" words = text.split chunks = for i in range 0, len words , chunk size - overlap : chunk = " ".join words i:i + chunk size chunks.append chunk return chunks Processing all documents into a flat list of chunks all chunks = for doc in documents: all chunks.extend chunk text doc print f"Created {len all chunks } chunks from the original documents." 123456789101112131415 def chunk text text, chunk size=25, overlap=5 : """Splits text into chunks natively, without external frameworks.""" words = text.split chunks = for i in range 0, len words , chunk size - overlap : chunk = " ".join words i:i + chunk size chunks.append chunk return chunks Processing all documents into a flat list of chunksall chunks = for doc in documents: all chunks.extend chunk text doc print f"Created {len all chunks } chunks from the original documents." Output: Created 31 chunks from the original documents. 1 Created 31 chunks from the original documents. In a real-world application, you will likely use significantly larger values for both arguments in the chunking function. Next, we generate the embeddings using a popular lightweight model for this task: the 'all-MiniLM-L6-v2' sentence-transformer : Initializing the embedding model runs locally on Colab's free CPU/GPU embedding model = SentenceTransformer 'all-MiniLM-L6-v2' Generating embeddings for all text chunks print "Generating embeddings... this is fast on Colab " chunk embeddings = embedding model.encode all chunks, show progress bar=True 123456 Initializing the embedding model runs locally on Colab's free CPU/GPU embedding model = SentenceTransformer 'all-MiniLM-L6-v2' Generating embeddings for all text chunksprint "Generating embeddings... this is fast on Colab " chunk embeddings = embedding model.encode all chunks, show progress bar=True Once we have a collection of embeddings, it’s time to define one of the key components of any RAG pipeline: the retriever . Since we are doing this the scikit-learn way, we will wrap sklearn.neighbors.NearestNeighbors — a simple yet effective distance calculation algorithm — into a clean, reusable class that mimics the functionality of a vector database, all based on cosine distance, which is ideal for embedding vector representations. python class SklearnRetriever: def init self, n neighbors=3 : Using 'cosine' metric because LLM embeddings measure semantic similarity based on angles between vectors self.retriever = NearestNeighbors n neighbors=n neighbors, metric='cosine', algorithm='brute' self.chunks = def fit self, chunks, embeddings : """Indexes the documents.""" self.chunks = chunks self.retriever.fit embeddings print "Vector index built successfully " def retrieve self, query embedding : """Returns the most relevant chunks for a given query.""" distances, indices = self.retriever.kneighbors query embedding Fetching the actual text strings using the retrieved indices results = self.chunks idx for idx in indices 0 return results Instantiating and fitting our custom retriever vector db = SklearnRetriever n neighbors=3 vector db.fit all chunks, chunk embeddings 1234567891011121314151617181920212223 class SklearnRetriever: def init self, n neighbors=3 : Using 'cosine' metric because LLM embeddings measure semantic similarity based on angles between vectors self.retriever = NearestNeighbors n neighbors=n neighbors, metric='cosine', algorithm='brute' self.chunks = def fit self, chunks, embeddings : """Indexes the documents.""" self.chunks = chunks self.retriever.fit embeddings print "Vector index built successfully " def retrieve self, query embedding : """Returns the most relevant chunks for a given query.""" distances, indices = self.retriever.kneighbors query embedding Fetching the actual text strings using the retrieved indices results = self.chunks idx for idx in indices 0 return results Instantiating and fitting our custom retrievervector db = SklearnRetriever n neighbors=3 vector db.fit all chunks, chunk embeddings The other major component of the pipeline is the generator . Here too we keep things lightweight, choosing a small, open-source LLM trained for natural language generation: Qwen/Qwen2.5-0.5B-Instruct . This model is small enough to run smoothly on a Colab notebook without risking a RAM crash. Loading a lightweight causal LLM built for the "text-generation" pipeline llm = pipeline "text-generation", model="Qwen/Qwen2.5-0.5B-Instruct", device map="auto" def generate rag answer query, retrieved context : """Combines the prompt, context, and query for the LLM using chat formatting.""" context str = " --- ".join retrieved context messages = {"role": "system", "content": "You are a helpful assistant. Answer the user's question using ONLY the provided context. If the answer is not in the context, say 'I cannot find the answer in the provided documents.'"}, {"role": "user", "content": f"Context:\n{context str}\n\nQuestion: {query}"} Apply the model's chat template prompt = llm.tokenizer.apply chat template messages, tokenize=False, add generation prompt=True Generating the response response = llm prompt, max new tokens=150, do sample=False, temperature=0.1 Extracting only the newly generated text past the prompt generated text = response 0 'generated text' answer = generated text len prompt : .strip return answer 12345678910111213141516171819202122 Loading a lightweight causal LLM built for the "text-generation" pipelinellm = pipeline "text-generation", model="Qwen/Qwen2.5-0.5B-Instruct", device map="auto" def generate rag answer query, retrieved context : """Combines the prompt, context, and query for the LLM using chat formatting.""" context str = " --- ".join retrieved context messages = {"role": "system", "content": "You are a helpful assistant. Answer the user's question using ONLY the provided context. If the answer is not in the context, say 'I cannot find the answer in the provided documents.'"}, {"role": "user", "content": f"Context:\n{context str}\n\nQuestion: {query}"} Apply the model's chat template prompt = llm.tokenizer.apply chat template messages, tokenize=False, add generation prompt=True Generating the response response = llm prompt, max new tokens=150, do sample=False, temperature=0.1 Extracting only the newly generated text past the prompt generated text = response 0 'generated text' answer = generated text len prompt : .strip return answer All the pieces of the pipeline are now in place. The last step is to wire them together and try it out by asking our system a question about its knowledge base Asian countries : python def ask rag pipeline question : print f"Question: {question}" 1. Embedding the query query vector = embedding model.encode question 2. Retrieving context via Scikit-Learn relevant chunks = vector db.retrieve query vector 3. Generating Answer answer = generate rag answer question, relevant chunks print f"\nRAG Answer: {answer}" print "\n--- Sources used ---" for i, chunk in enumerate relevant chunks : print f"{i+1}. {chunk :100 }..." Truncated for readability Testing it out test question = "Which Asian countries are best known for islands and beaches?" ask rag pipeline test question 1234567891011121314151617181920 def ask rag pipeline question : print f"Question: {question}" 1. Embedding the query query vector = embedding model.encode question 2. Retrieving context via Scikit-Learn relevant chunks = vector db.retrieve query vector 3. Generating Answer answer = generate rag answer question, relevant chunks print f"\nRAG Answer: {answer}" print "\n--- Sources used ---" for i, chunk in enumerate relevant chunks : print f"{i+1}. {chunk :100 }..." Truncated for readability Testing it outtest question = "Which Asian countries are best known for islands and beaches?"ask rag pipeline test question Output: Question: Which Asian countries are best known for islands and beaches? RAG Answer: The Asian countries that are best known for islands and beaches include: 1. Philippines - Known for its over 7,000 islands and vibrant festivals. 2. Thailand - Famous for its tropical beaches and bustling street food culture. These two countries have a significant number of islands and offer both beautiful natural scenery and diverse beach experiences. --- Sources used --- 1. mountainous landscapes and cultural cities like Chiang Mai, while the south offers world-renowned is... 2. The Philippines is an archipelago of over 7,000 islands in Southeast Asia, known for its stunning be... 3. Thailand is a Southeast Asian country famous for its tropical beaches, ornate temples, and bustling ... 12345678910111213 Question: Which Asian countries are best known for islands and beaches? RAG Answer: The Asian countries that are best known for islands and beaches include: 1. Philippines - Known for its over 7,000 islands and vibrant festivals.2. Thailand - Famous for its tropical beaches and bustling street food culture. These two countries have a significant number of islands and offer both beautiful natural scenery and diverse beach experiences. --- Sources used ---1. mountainous landscapes and cultural cities like Chiang Mai, while the south offers world-renowned is...2. The Philippines is an archipelago of over 7,000 islands in Southeast Asia, known for its stunning be...3. Thailand is a Southeast Asian country famous for its tropical beaches, ornate temples, and bustling ... Try asking different questions by replacing the text in test question . The behavior and outputs are reasonable given the small-scale setup we just built — though don’t expect commercial LLM-level results: we are combining a small model with a tiny knowledge base. Final Remarks In this article, we built a lightweight, end-to-end RAG pipeline that avoids the overhead of heavyweight frameworks or paid APIs. It relies solely on scikit-learn vector retrieval and open-source models for both embeddings and generation, producing a transparent, in-memory system. This approach makes a solid starting point for prototyping, experimenting with different retrieval strategies, and validating concepts before scaling up.