What is RAG in AI? Simple Explanation + Build Your First RAG App for Free

What is RAG in AI – Daily Dose Of AI

Quick answer: RAG (Retrieval-Augmented Generation) means the AI looks up relevant information first, then writes its answer using what it found. Instead of answering only from memory, it answers from your documents (PDFs, policies, notes), so it’s more accurate, more current, and can cite sources. Below: a simple explanation, how RAG works in 4 steps, and a tiny RAG app in Python you can run for free.

Quick recap first: a Large Language Model (LLM) is a model trained on huge amounts of text to predict the next words. If that’s new, read What is a Large Language Model.

RAG explained with an open-book exam

Remember exams in school? In a closed-book exam you answer from memory. You might remember wrongly, or the syllabus might have changed. In an open-book exam you first flip to the right page, then write the answer using the book.

  • A plain LLM = closed-book student. Smart, but it can confidently invent answers (“hallucination”) and doesn’t know your private or latest data.
  • An LLM with RAG = open-book student. It first retrieves the right pages from your documents, then generates an answer based on them.

Why do LLMs need RAG?

  1. Private data: the model never saw your company’s HR policy or your college syllabus.
  2. Fresh data: models have a training cutoff; RAG can use documents updated this morning.
  3. Fewer hallucinations: grounding the answer in retrieved text makes it more reliable, though it doesn’t make it perfect.
  4. Citations: you can show which document the answer came from, and users trust that.

How RAG works in 4 steps

  1. Chunk: split documents into small pieces (for example, 300–800 words), like cutting a book into index cards.
  2. Embed: convert each chunk into an embedding, a list of numbers that captures its meaning. Similar meanings get similar numbers.
  3. Retrieve: when a question comes in, embed the question too, and find the chunks whose numbers are closest. That’s the “search”.
  4. Generate: send the question plus the top chunks to the LLM with an instruction like “Answer only from this context and cite the source.”

In real apps, step 2’s numbers are stored in a vector database (like pgvector, Chroma or Qdrant) so searching millions of chunks stays fast. For learning, a simple Python list is enough.

RAG vs fine-tuning vs long context

ApproachWhat it doesBest when
RAGLooks up documents at question timeData changes often, you need citations, data is large
Fine-tuningRe-trains the model on examplesYou need a fixed style/format or a specialised skill
Long contextPastes the whole document into the promptSmall number of documents, one-off questions

Rule of thumb: start with RAG. It’s cheaper, easier to update and easier to debug than fine-tuning.

Build your first RAG app in Python (free)

We’ll use Google’s Gemini API, which has a free tier (see our free LLM API guide for getting a key). Model names change over time; if one errors, check the current names in Google’s docs.

1. Install and set your key

pip install -U google-genai numpy

# macOS/Linux
export GEMINI_API_KEY="your-key-here"
# Windows PowerShell
$env:GEMINI_API_KEY="your-key-here"

2. Save this as tiny_rag.py

import numpy as np
from google import genai

client = genai.Client()  # reads GEMINI_API_KEY

# Our "documents" (in real life: chunks from PDFs)
docs = [
    "Leave policy: employees get 24 paid leaves per year. Unused leaves up to 10 carry forward.",
    "Work from home: allowed 2 days a week with manager approval.",
    "Reimbursement: travel claims must be submitted within 30 days with bills.",
    "Laptop policy: report damage to IT within 48 hours.",
]

def embed(text):
    r = client.models.embed_content(model="gemini-embedding-2", contents=text)
    return np.array(r.embeddings[0].values)

# Step 1+2: embed every chunk once
doc_vecs = [embed(d) for d in docs]

def retrieve(question, k=2):
    q = embed(question)
    scores = [float(np.dot(q, v) / (np.linalg.norm(q) * np.linalg.norm(v))) for v in doc_vecs]
    top = np.argsort(scores)[::-1][:k]
    return [docs[i] for i in top]

def answer(question):
    context = "\n".join(f"- {c}" for c in retrieve(question))
    prompt = f"""Answer the question using ONLY the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""
    result = client.interactions.create(model="gemini-3.8-flash", input=prompt)
    return result.output_text, context

reply, used = answer("How many leaves can I carry forward?")
print("Answer:", reply)
print("\nSources used:\n", used)

3. Run it

python tiny_rag.py

You should see an answer about carrying forward up to 10 leaves, plus the policy line it came from. Now try a question that’s not in the documents (“What is the dress code?”). A good RAG app should say “I don’t know” instead of inventing an answer.

Common RAG mistakes (and fixes)

  • Chunks too big or too small: huge chunks dilute meaning, tiny ones lose context. Start with about 500 words with a little overlap.
  • No “I don’t know” rule: always tell the model to refuse when the context doesn’t contain the answer.
  • Never testing: write 20 real questions with expected answers and check them after every change.
  • Ignoring permissions: in companies, make sure users can only retrieve documents they’re allowed to see.
  • Stale index: re-embed documents when they change.

Where RAG is used in India today

  • Bank and fintech support bots answering from product FAQs and policy documents
  • HR assistants answering leave, payroll and policy questions
  • EdTech “ask your textbook” tutors for school and competitive-exam syllabi
  • Legal and compliance teams searching circulars and contracts
  • Developer assistants answering from internal code and docs

FAQ

Is RAG an AI model? No. It’s a technique that combines a search step with any LLM.

Does RAG stop hallucinations completely? No, but it reduces them a lot when combined with good retrieval, an “I don’t know” rule and testing.

Do I need a vector database? Not for learning or a few hundred chunks. For thousands or millions, yes.

RAG vs agents? RAG retrieves information; agents also take actions with tools. Many agents use RAG as one of their tools. See LLM, RAG, and Agents.

Your next step

Run the tiny RAG script above, then replace the four policy lines with text from a PDF you care about (your syllabus or a product manual). That one project already shows the core skill AI engineer interviews ask about.

Leave a Reply

Your email address will not be published. Required fields are marked *