Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training
AI & ML⏱️ 11 min readπŸ“… Nov 24

What Is RAG? Retrieval-Augmented Generation Explained, With a Python Pipeline (2026)

RM
Rahul Menonβ€’GenAI Engineer
πŸ“‘ Contents (18 sections)

πŸ“ŒWhat RAG Means

Retrieval-augmented generation (RAG) is a pattern where, before the model answers, your application retrieves the most relevant pieces of your own data and puts them into the prompt. The model then generates an answer grounded in that retrieved text, ideally with citations.

RAG exists because a large language model only knows what was in its training data. It does not know your company policies, last week's tickets or the contract your customer signed. You could paste every document into the prompt, but that is slow, expensive and usually less accurate. RAG fetches only what is needed for each question.

It is the single most common pattern in production generative AI, which is why it shows up in almost every Generative AI interview.

πŸ“ŒThe Two Halves of a RAG System

Indexing (done ahead of time)

  • 1Load documents: PDFs, web pages, Confluence, tickets, database rows.
  • 2Clean them: remove headers, footers, navigation and duplicates.
  • 3Chunk them into passages small enough to retrieve precisely.
  • 4Embed each chunk into a vector with an embedding model.
  • 5Store the vectors plus the original text and metadata in a vector database.
  • Querying (done per question)

  • 1Embed the user question with the same embedding model.
  • 2Retrieve the nearest chunks, often combined with keyword search.
  • 3Rerank the candidates and keep the best few.
  • 4Build the prompt with instructions, the retrieved chunks and the question.
  • 5Generate the answer and attach citations to the chunks used.
  • πŸ“ŒChunking: Where Most Quality Is Won or Lost

    Chunks that are too large dilute the relevant sentence with noise. Chunks that are too small lose the context needed to answer. Practical starting points:

  • Split on document structure first: headings, sections, paragraphs.
  • Aim for a few hundred tokens per chunk with a small overlap between neighbours.
  • Keep metadata on every chunk: source, title, section, date, access level.
  • Prepend the document and section title to the chunk text so it makes sense on its own.
  • Tune chunk size against an evaluation set, not by intuition.

    πŸ“ŒEmbeddings and Vector Databases

    An embedding turns text into a list of numbers so that texts with similar meaning sit close together. A vector database stores these vectors and finds the nearest ones quickly. Common choices:

  • pgvector if you already run PostgreSQL. Often the simplest production option.
  • Chroma for local prototypes.
  • Pinecone, Qdrant, Weaviate or Milvus for managed or large-scale deployments.
  • Always store the raw text and metadata alongside the vector, and filter by metadata (for example tenant or permission) before or during the search, never after.

    πŸ“ŒHybrid Search and Reranking

    Pure vector search misses exact terms such as product codes, error IDs and names. Hybrid search combines vector similarity with keyword search (BM25) and merges the results. A reranker then scores each candidate against the question more carefully and keeps the top few. Together these two steps fix a large share of "the answer was in the documents but the bot missed it" complaints.

    πŸ“ŒA Minimal RAG Pipeline in Python

    The shape of the code matters more than the library. A stripped-down version:

    def answer(question: str) -> dict:
    q_vec = embed(question)
    candidates = vector_db.search(q_vec, top_k=20, filter={"tenant": user.tenant})
    candidates += keyword_index.search(question, top_k=20)
    top = rerank(question, dedupe(candidates))[:5]
    context = "\n\n".join(f"[{i+1}] {c.text}" for i, c in enumerate(top))
    prompt = (
    "Answer only from the sources below. Cite sources like [1]. "
    "If the answer is not in the sources, say you do not know.\n\n"
    f"Sources:\n{context}\n\nQuestion: {question}"
    )
    reply = llm.generate(prompt, temperature=0)
    return {"answer": reply, "sources": [c.source for c in top]}

    Frameworks such as LangChain and LlamaIndex provide loaders, splitters and retrievers for each of these steps. Use them where they save time, but understand each step so you can debug it.

    πŸ“ŒEvaluating a RAG System

    You cannot improve what you do not measure. Build a test set of 50 to 200 real questions with expected answers and the documents that contain them, then track:

  • Retrieval recall: did the right chunk appear in the top results?
  • Faithfulness: is every claim in the answer supported by the retrieved text?
  • Answer relevance: does the answer address the question?
  • Refusal behaviour: does it say "I do not know" when the answer is not in the data?
  • Latency and cost per question.
  • LLM-as-judge scoring, spot-checked by humans, makes this affordable to run on every change.

    πŸ“ŒCommon RAG Failures and Fixes

  • Right document, wrong chunk: improve chunking, add titles to chunks, add a reranker.
  • Exact terms missed: add keyword search, making it hybrid.
  • Confident wrong answers: instruct the model to answer only from sources, require citations, lower temperature, test refusals.
  • Stale answers: re-index on document change and store dates as metadata.
  • Data leaking across users: enforce access filters inside retrieval.
  • Slow responses: cache embeddings and frequent answers, retrieve fewer but better chunks, stream the output.
  • πŸ“ŒRAG vs Fine-Tuning

    Use RAG when the model needs knowledge that changes or must be cited: policies, documentation, product data. Use fine-tuning when you need a consistent behaviour or format that prompting cannot reliably produce, such as a specific style or a narrow classification task. Many production systems use both: a fine-tuned or well-prompted model on top of a RAG pipeline.

    πŸ“ŒRAG and Agents

    In agentic systems, retrieval becomes a tool the agent can call when it decides it needs information, sometimes several times with refined queries. This is often called agentic RAG, and it is covered in the Agentic AI roadmap.

    πŸ“ŒFrequently Asked Questions

    Is RAG still needed now that models have very long context windows?

    Yes for most production systems. Long context helps, but sending large document sets on every request is slow and expensive, and accuracy tends to drop when the relevant passage is buried in a long prompt. Retrieval also lets you enforce permissions and cite sources.

    Which vector database should I start with?

    If you already use PostgreSQL, start with pgvector. It keeps your data, metadata and permissions in one place. Move to a dedicated vector database when scale or features demand it.

    Do I need LangChain to build RAG?

    No. A RAG pipeline is a handful of functions. LangChain and LlamaIndex can speed things up, but you should be able to build and debug the pipeline without them.

    What is a good first RAG project for a resume?

    A document question-answering assistant over a real public document set, with hybrid search, citations, an evaluation set with reported scores, and a deployed API. That single project demonstrates most of what GenAI interviews test.

    πŸ“ŒBuild It Live

    Our Generative AI course builds a production RAG assistant end to end, live online with an optional 1-on-1 track. WhatsApp or call +91 9180377502 for a free demo.

    RM

    Written by

    Rahul Menon

    GenAI Engineer

    πŸš€ Master AI & ML

    Live online + 1-on-1 Generative AI & Prompt Engineering training Β· Join 5000+ developers

    Not sure what to do? Book career counselling (β‚Ή200 / 30 min)

    Not sure what to learn next?

    A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

    1. 1Discuss your goals
    2. 2Get a personal plan
    3. 3Start learning
    Book for β‚Ή200/ 30 min