Chapter 39
simple rag
🎬 Watch this notebook explained
RAG Explained: Why AI Gets Your Own Documents Wrong — the intuition behind every cell below, in 7 minutes: why documents get cut into overlapping chunks, what "meaning space" actually is, how a search by meaning finds a passage that shares almost no words with your question, and where simple RAG starts to break.
Simple RAG (Retrieval-Augmented Generation) System
Overview
This code implements a basic Retrieval-Augmented Generation (RAG) system for processing and querying PDF documents. The system encodes the document content into a vector store, which can then be queried to retrieve relevant information.
Key Components
- PDF processing and text extraction
- Text chunking for manageable processing
- Vector store creation using FAISS and OpenAI embeddings
- Retriever setup for querying the processed documents
- Evaluation of the RAG system
Method Details
Document Preprocessing
- The PDF is loaded using PyPDFLoader.
- The text is split into chunks using RecursiveCharacterTextSplitter with specified chunk size and overlap.
Text Cleaning
A custom function replace_t_with_space is applied to clean the text chunks. This likely addresses specific formatting issues in the PDF.
Vector Store Creation
- OpenAI embeddings are used to create vector representations of the text chunks.
- A FAISS vector store is created from these embeddings for efficient similarity search.
Retriever Setup
- A retriever is configured to fetch the top 2 most relevant chunks for a given query.
Encoding Function
The encode_pdf function encapsulates the entire process of loading, chunking, cleaning, and encoding the PDF into a vector store.
Key Features
- Modular Design: The encoding process is encapsulated in a single function for easy reuse.
- Configurable Chunking: Allows adjustment of chunk size and overlap.
- Efficient Retrieval: Uses FAISS for fast similarity search.
- Evaluation: Includes a function to evaluate the RAG system's performance.
Usage Example
The code includes a test query: "What is the main cause of climate change?". This demonstrates how to use the retriever to fetch relevant context from the processed document.
Evaluation
The system includes an evaluate_rag function to assess the performance of the retriever, though the specific metrics used are not detailed in the provided code.
Benefits of this Approach
- Scalability: Can handle large documents by processing them in chunks.
- Flexibility: Easy to adjust parameters like chunk size and number of retrieved results.
- Efficiency: Utilizes FAISS for fast similarity search in high-dimensional spaces.
- Integration with Advanced NLP: Uses OpenAI embeddings for state-of-the-art text representation.
Conclusion
This simple RAG system provides a solid foundation for building more complex information retrieval and question-answering systems. By encoding document content into a searchable vector store, it enables efficient retrieval of relevant information in response to queries. This approach is particularly useful for applications requiring quick access to specific information within large documents or document collections.
Package Installation and Imports
The cell below installs all necessary packages required to run this notebook.
# Install required packages
!pip install pypdf==5.6.0
!pip install PyMuPDF==1.26.1
!pip install python-dotenv==1.1.0
!pip install langchain-community==0.3.25
!pip install langchain_openai==0.3.23
!pip install rank_bm25==0.2.2
!pip install faiss-cpu==1.11.0
!pip install deepeval==3.1.0# Clone the repository to access helper functions and evaluation modules
!git clone https://github.com/NirDiamant/RAG_TECHNIQUES.git
import sys
sys.path.append('RAG_TECHNIQUES')
# If you need to run with the latest data
# !cp -r RAG_TECHNIQUES/data .Output
Cloning into 'RAG_TECHNIQUES'... remote: Enumerating objects: 1531, done.[K remote: Counting objects: 100% (808/808), done.[K remote: Compressing objects: 100% (359/359), done.[K remote: Total 1531 (delta 549), reused 458 (delta 449), pack-reused 723 (from 2)[K Receiving objects: 100% (1531/1531), 34.20 MiB | 25.58 MiB/s, done. Resolving deltas: 100% (962/962), done.
import os
import sys
from dotenv import load_dotenv
from google.colab import userdata
# Load environment variables from a .env file
load_dotenv()
# Set the OpenAI API key environment variable (comment out if not using OpenAI)
if not userdata.get('OPENAI_API_KEY'):
os.environ["OPENAI_API_KEY"] = input("Please enter your OpenAI API key: ")
else:
os.environ["OPENAI_API_KEY"] = userdata.get('OPENAI_API_KEY')
# Original path append replaced for Colab compatibility
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from helper_functions import (EmbeddingProvider,
retrieve_context_per_question,
replace_t_with_space,
get_langchain_embedding_provider,
show_context)
from evaluation.evalute_rag import evaluate_rag
from langchain.vectorstores import FAISSOutput
<ipython-input-2-622825101>:26: LangChainDeprecationWarning: As of langchain-core 0.3.0, LangChain uses pydantic v2 internally. The langchain_core.pydantic_v1 module was a compatibility shim for pydantic v1, and should no longer be used. Please update the code to import from Pydantic directly. For example, replace imports like: `from langchain_core.pydantic_v1 import BaseModel` with: `from pydantic import BaseModel` or the v1 compatibility namespace if you are working in a code base that has not been fully upgraded to pydantic 2 yet. from pydantic.v1 import BaseModel from helper_functions import (EmbeddingProvider,
Read Docs
# Download required data files
import os
os.makedirs('data', exist_ok=True)
# Download the PDF document used in this notebook
!wget -O data/Understanding_Climate_Change.pdf https://raw.githubusercontent.com/NirDiamant/RAG_TECHNIQUES/main/data/Understanding_Climate_Change.pdf
!wget -O data/Understanding_Climate_Change.pdf https://raw.githubusercontent.com/NirDiamant/RAG_TECHNIQUES/main/data/Understanding_Climate_Change.pdfOutput
--2025-06-14 07:31:48-- https://raw.githubusercontent.com/NirDiamant/RAG_TECHNIQUES/main/data/Understanding_Climate_Change.pdf Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 206372 (202K) [application/octet-stream] Saving to: ‘data/Understanding_Climate_Change.pdf’ data/Unde 0%[ ] 0 --.-KB/s data/Understanding_ 100%[===================>] 201.54K --.-KB/s in 0.03s 2025-06-14 07:31:48 (5.89 MB/s) - ‘data/Understanding_Climate_Change.pdf’ saved [206372/206372] --2025-06-14 07:31:48-- https://raw.githubusercontent.com/NirDiamant/RAG_TECHNIQUES/main/data/Understanding_Climate_Change.pdf Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.111.133, 185.199.108.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 206372 (202K) [application/octet-stream] Saving to: ‘data/Understanding_Climate_Change.pdf’ data/Understanding_ 100%[===================>] 201.54K --.-KB/s in 0.03s 2025-06-14 07:31:48 (5.77 MB/s) - ‘data/Understanding_Climate_Change.pdf’ saved [206372/206372]
path = "data/Understanding_Climate_Change.pdf"Encode document
def encode_pdf(path, chunk_size=1000, chunk_overlap=200):
"""
Encodes a PDF book into a vector store using OpenAI embeddings.
Args:
path: The path to the PDF file.
chunk_size: The desired size of each text chunk.
chunk_overlap: The amount of overlap between consecutive chunks.
Returns:
A FAISS vector store containing the encoded book content.
"""
# Load PDF documents
loader = PyPDFLoader(path)
documents = loader.load()
# Split documents into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size, chunk_overlap=chunk_overlap, length_function=len
)
texts = text_splitter.split_documents(documents)
cleaned_texts = replace_t_with_space(texts)
# Create embeddings (Tested with OpenAI and Amazon Bedrock)
embeddings = get_langchain_embedding_provider(EmbeddingProvider.OPENAI)
#embeddings = get_langchain_embedding_provider(EmbeddingProvider.AMAZON_BEDROCK)
# Create vector store
vectorstore = FAISS.from_documents(cleaned_texts, embeddings)
return vectorstorechunks_vector_store = encode_pdf(path, chunk_size=1000, chunk_overlap=200)Create retriever
chunks_query_retriever = chunks_vector_store.as_retriever(search_kwargs={"k": 2})Test retriever
test_query = "What is the main cause of climate change?"
context = retrieve_context_per_question(test_query, chunks_query_retriever)
show_context(context)Output
Context 1: Chapter 2: Causes of Climate Change Greenhouse Gases The primary cause of recent climate change is the increase in greenhouse gases in the atmosphere. Greenhouse gases, such as carbon dioxide (CO2), methane (CH4), and nitrous oxide (N2O), trap heat from the sun, creating a "greenhouse effect." This effect is essential for life on Earth, as it keeps the planet warm enough to support life. However, human activities have intensified this natural process, leading to a warmer climate. Fossil Fuels Burning fossil fuels for energy releases large amounts of CO2. This includes coal, oil, and natural gas used for electricity, heating, and transportation. The industrial revolution marked the beginning of a significant increase in fossil fuel consumption, which continues to rise today. Coal Context 2: Most of these climate changes are attributed to very small variations in Earth's orbit that change the amount of solar energy our planet receives. During the Holocene epoch, which began at the end of the last ice age, human societies flourished, but the industrial era has seen unprecedented changes. Modern Observations Modern scientific observations indicate a rapid increase in global temperatures, sea levels, and extreme weather events. The Intergovernmental Panel on Climate Change (IPCC) has documented these changes extensively. Ice core samples, tree rings, and ocean sediments provide a historical record that scientists use to understand past climate conditions and predict future trends. The evidence overwhelmingly shows that recent changes are primarily driven by human activities, particularly the emission of greenhouse gases. Chapter 2: Causes of Climate Change Greenhouse Gases The primary cause of recent climate change is the increase in greenhouse gases in the
/content/RAG_TECHNIQUES/helper_functions.py:143: LangChainDeprecationWarning: The method `BaseRetriever.get_relevant_documents` was deprecated in langchain-core 0.1.46 and will be removed in 1.0. Use :meth:`~invoke` instead. docs = chunks_query_retriever.get_relevant_documents(question)
Evaluate results
#Note - this currently works with OPENAI only
evaluate_rag(chunks_query_retriever)Output
{'questions': ['1. **Multiple Choice: Causes of Climate Change**',
' - What is the primary cause of the current climate change trend?',
' A) Solar radiation variations',
' B) Natural cycles of the Earth',
' C) Human activities, such as burning fossil fuels',
' D) Volcanic eruptions',
'',
'2. **True or False: Climate Change Impacts**',
' - True or False: Climate change only affects the temperature of the planet, not weather patterns, sea levels, or ecosystems.',
'',
'3. **Short Answer: Mitigation Strategies**',
' - Describe two effective strategies that could be implemented to mitigate the effects of climate change.',
'',
'4. **Matching: Climate Change Terminology**',
' - Match the following terms with their correct definitions:',
' A) Greenhouse Gases',
' B) Carbon Footprint',
' C) Renewable Energy',
' D) Adaptation',
' - Definitions:',
' 1. The total amount of greenhouse gases produced to directly and indirectly support human activities, usually expressed in equivalent tons of carbon dioxide (CO2).',
" 2. Gases in Earth's atmosphere that trap heat, such as CO2, methane, and nitrous oxide.",
' 3. Adjusting practices, processes, and capital in response to the risks posed by climate change.',
' 4. Energy from sources that are not depleted when used, such as wind or solar power.',
'',
'5. **Essay: International Cooperation**',
' - Discuss the importance of international cooperation in combating climate change. Include examples of international agreements or policies that have been implemented to address the issue.'],
'results': ['```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 5,\n "Conciseness": 4\n}\n```',
'```json\n{\n "Relevance": 2,\n "Completeness": 1,\n "Conciseness": 2\n}\n```',
'```json\n{\n "Relevance": 3,\n "Completeness": 2,\n "Conciseness": 2\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 1,\n "Completeness": 1,\n "Conciseness": 2\n}\n```',
'```json\n{\n "Relevance": 1,\n "Completeness": 1,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 5,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 1,\n "Completeness": 1,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 2,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 3,\n "Conciseness": 2\n}\n```',
'```json\n{\n "Relevance": 1,\n "Completeness": 1,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 2,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 3,\n "Completeness": 2,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 3,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 3,\n "Conciseness": 2\n}\n```',
'```json\n{\n "Relevance": 1,\n "Completeness": 1,\n "Conciseness": 2\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 3,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 5,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 3,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 1,\n "Completeness": 1,\n "Conciseness": 3\n}\n```',
'```json\n{\n "Relevance": 5,\n "Completeness": 4,\n "Conciseness": 4\n}\n```',
'```json\n{\n "Relevance": 4,\n "Completeness": 3,\n "Conciseness": 4\n}\n```'],
'average_scores': None}🎬 Now the part the code doesn't show
You just ran a retriever that answers from your own document. The 7-minute explainer covers why it works: why chunks overlap, what "meaning space" actually is, and the chunk-boundary failure that quietly breaks retrieval setups that look perfectly healthy from the outside.
