Generative AIby Dhruv Narang

The RAG App: Two Parts

A RAG app has two parts. The first builds the knowledge base, once. The second answers a question, every time.

Build the knowledge base, once
Load
The loader
The PDF becomes Documents
Split
The text splitter
The Documents become chunks
Embed
The embedding model
Each chunk becomes a vector
Store
Chroma
The chunks and their vectors are saved
Answer a question, every time
Embed
The question
The same embedding model makes its vector
Retrieve
The closest chunks
The store returns the most similar chunks
Augment
The prompt
The chunks and the question go into it
Generate
The LLM
It answers from the chunks

Packages and Install

This app needs a few packages and two keys. Install them first.

Install everything once. The app uses a few packages. Each one does a different job.
JobPackageNote
Load the PDFlangchain-community and pypdfthe loader class, and the package that reads PDFs
Split the textlangchain-text-splittersthe splitter classes
Embed (make vectors)langchain-google-genaiGemini embeddings. Free tier, with a free key from Google AI Studio
Store the vectorslangchain-chromaChroma, saved in a local folder
Chat modellangchain-groqfor init_chat_model with a Groq model. Free key from Groq
Read the keyspython-dotenvloads the keys from the .env file
pip install langchain langchain-community langchain-text-splitters langchain-google-genai langchain-chroma langchain-groq pypdf python-dotenv
The keys go in .env. Use your own keys. Never put them in the code, and never upload this file.
GOOGLE_API_KEY=your-google-key-here
GROQ_API_KEY=your-groq-key-here
Another provider? Only the provider package and the model name change. For example, langchain-mistralai for Mistral. The rest of the code stays the same.

Load and Split

The first two steps. You have seen both: the document loaders and the text splitters.

loader = PyPDFLoader("location of the PDF")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=500,chunk_overlap=50)
doc_chunks = splitter.split_documents(docs)
The loader reads the PDF and gives one Document for each page.
The splitter cuts the Documents into chunks of up to 500 characters, with an overlap of 50.

Embed and Store

Each chunk becomes a vector, and the vectors are saved in a vector store. This app uses Chroma.

DB_DIR = "./chroma_db"
COLLECTION_NAME = "rag_knowledge"

embeddingModel = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")

vector_store = Chroma.from_documents(
    documents=doc_chunks,
    embedding=embeddingModel,
    persist_directory=DB_DIR,
    collection_name=COLLECTION_NAME,
)
embeddingModel turns text into a vector. This is the model that embeds every chunk.
Chroma.from_documents embeds all the chunks and saves them with their vectors.
persist_directory is the folder where the database is saved. collection_name is the name of this collection inside Chroma.
The same embedding model is used later to embed the question. Only then can the question and the chunks be compared.

First Run and Next Run

Building the knowledge base takes time and costs embedding calls. So the app does it only once.

if not os.path.exists(DB_DIR):
    # first run: load, split, embed and store
    ...
else:
    vector_store = Chroma(
        persist_directory=DB_DIR,
        embedding_function=embeddingModel,
        collection_name=COLLECTION_NAME,
    )
First run
No saved database yet
The app loads, splits, embeds and stores. The database is saved in the folder.
Next runs
The folder exists
The app only opens the saved database. No embedding calls, so it starts fast.
To build the database again, delete the folder.

Retrieve the Closest Chunks

The question is turned into a vector, and the store returns the chunks that are closest to it.

user_question = "what is main advantage of Retrieval-Augmented Generation?"
retrieved_docs= vector_store.similarity_search(query=user_question,k=3)
context_text = "\n\n".join([doc.page_content for doc in retrieved_docs])
similarity_search embeds the question and compares it with the stored vectors. It returns the k closest chunks. Here k=3, so three chunks come back.
context_text joins the text of those chunks into one block.

Augment and Generate

The chunks and the question go into a prompt, and the LLM answers from them.

System message
The rule for the LLM
You are a helpful AI assistant. Answer the user's question ONLY based on the provided context. If the answer cannot be found in the context, say 'I cannot find the answer in the provided documents.'
Human message
The chunks and the question
Context: the chunks
Question: the user's question
model = init_chat_model("groq:openai/gpt-oss-20b")
rag_chain = rag_prompt | model | StrOutputParser()
response = rag_chain.invoke({"context":context_text , "question":user_question})
print(response)
The system message is the key. It tells the LLM to answer only from the context. If the answer is not there, the LLM says so, and does not guess.
The chain is the prompt, then the model, then the parser. You built chains like this in the LCEL lessons.

Things to Try

Run the app and change one thing at a time.

Change k
How many chunks
Try a smaller and a bigger k. Too few chunks and the answer may be missing. Too many add noise and cost.
Change the question
Ask something else
Ask about another part of the document and see which chunks come back.
Ask what is not there
A question the document does not answer
The LLM replies: I cannot find the answer in the provided documents.

Other Embedding Models and Vector Stores

Chroma and Gemini are one choice. These are others.

Embedding modelPackageNote
gemini-embedding-001langchain-google-genaifree tier, with a free key from Google AI Studio. Makes vectors of 3072 numbers.
mistral-embedlangchain-mistralaiworks only if your plan includes API use. On the free plan, the API can give an error (402). Check your plan on the Mistral site. Makes vectors of 1024 numbers.
sentence-transformers/all-MiniLM-L6-v2langchain-huggingfacefree, runs on your own computer
Vector storePackageNote
Chromalangchain-chromasaves to a local folder
FAISSfaiss-cpufast, in memory
Pinecone, Qdrant, Weaviatetheir own packagesin the cloud, for production

Code
Simple RAG with Chroma and Gemini01_simple_rag.py · 63 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from dotenv import load_dotenv
load_dotenv()
import os
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_chroma import Chroma
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

DB_DIR = "./chroma_db"
COLLECTION_NAME = "rag_knowledge"

# print(f"Step 1: Loaded {len(docs)} pages from PDF.")
# print(f"Step 2: Created {len(doc_chunks)} chunks.")


"""Embedding model: text -> a list of numbers (vector)"""
embeddingModel = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")

"""First run: load -> split -> embed -> store in Chroma (saved in ./chroma_db). Next runs: open the saved DB"""
if not os.path.exists(DB_DIR):
    loader = PyPDFLoader("data/iitd_ug_rules.pdf")
    docs = loader.load()
    splitter = RecursiveCharacterTextSplitter(chunk_size=500,chunk_overlap=50)
    doc_chunks = splitter.split_documents(docs)
    
    vector_store = Chroma.from_documents(documents=doc_chunks,
                                     embedding=embeddingModel,
                                     persist_directory=DB_DIR,
                                     collection_name=COLLECTION_NAME
                                     )
else:
     vector_store = Chroma(
        persist_directory=DB_DIR,
        embedding_function=embeddingModel,
        collection_name=COLLECTION_NAME
     )
    
user_question = "How much attendance is needed to request an I grade?"

"""Retrieve: find the 3 chunks closest in meaning to the question"""
retrieved_docs= vector_store.similarity_search(query=user_question,k=3)
context_text = "\n\n".join([doc.page_content for doc in retrieved_docs])

"""Augment + Generate: put the chunks in the prompt, the LLM answers from them"""
rag_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI assistant. Answer the user's question ONLY based on the provided context. If the answer cannot be found in the context, say 'I cannot find the answer in the provided documents.'"),
    ("human", "Context:\n{context}\n\nQuestion: {question}")
])

model = init_chat_model("groq:openai/gpt-oss-20b")

rag_chain = rag_prompt | model | StrOutputParser()

response = rag_chain.invoke({"context":context_text , "question":user_question})

print(response)


#