Skip to content
RankCore.AI
← All posts

What Is RAG? Retrieval-Augmented Generation Explained

· ai, rag, llm

A language model can write a fluent answer to almost any question. Fluency is not the same as being right, or as knowing your facts. The short video above walks through 15 concepts that make Retrieval-Augmented Generation, or RAG, work. The idea is simple: before the model answers, it searches your documents, then answers using what it found.

This article is the full professional version of that walkthrough: why RAG exists, how the 2020 paper defined it, and how a production pipeline is built. The video's closing line is a good map: chunk, embed, store, retrieve, re-rank, generate, and measure.

Why RAG exists

Three problems show up as soon as you put a large language model in front of real users.

Hallucination. A model is trained to continue text in a way that looks likely. When it does not know something, it often invents a confident sentence anyway: a fake citation, a policy that does not exist, a number that was never in the source.

Stale knowledge. The facts inside a model's weights are frozen at training time. They do not include last week's pricing page or a document you uploaded an hour ago.

Private data. Most of the text that matters to a business never appeared in the public training set: contracts, runbooks, tickets, and design docs. You often cannot send the entire corpus in the prompt.

RAG changes the job of the model. It is no longer asked to be the database. It is asked to read a small set of retrieved passages and write an answer that is faithful to them. If the right passage is missing, that is a retrieval failure you can measure and fix.

The original paper

The name comes from a 2020 paper by Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, and Douwe Kiela: "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks", published at NeurIPS 2020.

The authors combined a pre-trained sequence-to-sequence generator (BART) with a dense retriever over a Wikipedia index, in the line of Dense Passage Retrieval (DPR). RAG treated a large external document collection as a non-parametric memory, rather than relying only on the model's parameters. They described two variants. In RAG-Sequence, the same retrieved documents condition the entire generated sequence. In RAG-Token, different documents can influence different tokens. The paper showed gains on knowledge-intensive tasks and made it possible to update the system's knowledge by updating the index, without retraining the generator.

That last point is why the idea entered almost every serious LLM product. Today's architecture is broader than BART plus Wikipedia, but the contract is the same. Retrieval supplies the evidence. Generation writes the answer.

The pipeline at a glance

The video organizes the work into 15 concepts. In production they sit on two timelines: an offline or continuous indexing path that prepares documents, and an online query path that answers a question.

StageWhen it runsWhat it does
Ingestion and parsingIndexingCollect sources, extract clean text, attach document IDs and access metadata
ChunkingIndexingSplit documents into retrievable passages
EmbeddingIndexing and queryTurn chunks, and later the question, into vectors
Vector store and metadata indexIndexingPersist embeddings, keywords, and filters for millisecond search
Query understandingQueryRewrite, decompose, or expand the question
RetrievalQueryDense, sparse, or hybrid search, with metadata filters
Reranking and compressionQueryKeep the best passages and drop noise
AugmentationQueryPack evidence into a prompt the model can use
GenerationQueryWrite the answer, with citations, from that evidence
EvaluationBothMeasure faithfulness, context precision, and context recall

Ingestion and parsing

RAG quality starts before anyone queries a model. If you index a broken extract, the retriever will confidently return broken evidence. Sources are messy: PDFs, Word files, HTML help centers, wikis, tickets, and transcripts. Tables, lists, code, and headings need to be preserved, because they are often the answer. Scanned pages need OCR, and web pages need boilerplate removed.

Attach identity and metadata here: a stable document ID, source, title, URL, timestamps, language, team, and the access-control attributes that later prevent one tenant from retrieving another tenant's files. Deduplicate near-identical pages, record a content hash, and delete or supersede chunks when a document is replaced. Otherwise the index will serve two conflicting policies. This is where many "we tried RAG and it hallucinated" projects actually failed.

Chunking

The video's first concept is the right place to start: split documents into small, meaningful pieces before you index them. A chunk is the unit you retrieve. If it is too large, the embedding becomes a blur of many topics. If it is too small, the model never sees the definition that sat one paragraph above the match. Token length, not character length, is what the models consume. A common starting point is a few hundred tokens with a small overlap. Fixed-size windows are simple, but they cut through tables and policy clauses. Recursive, structure-aware splitting walks a document from sections to paragraphs to sentences, using headings when they exist; this is usually the default for manuals and wikis. Semantic grouping clusters adjacent sentences that belong to the same idea.

Small-to-big retrieval, concept 10 in the video, should be planned at chunking time. You index small chunks so matching is precise, then you hand the model a larger parent window. Keep a map from each chunk back to its parent, its position, and the metadata you will filter on.

StrategyStrengthWeaknessTypical use
Fixed-size with overlapSimple, predictable token budgetsCuts through structureFirst baseline, homogeneous text
Recursive / markdown-awareRespects headings and listsDepends on clean structureDocs, wikis, blogs, policies
Semantic / sentence groupingChunks follow meaningSlower; thresholds need careNarrative reports, transcripts
Small-to-big / parent-documentPrecise match, broader context for the modelMore storage and a two-level lookupHandbooks, legal, long technical docs

Embeddings

An embedding model turns a chunk into a list of numbers, a vector, so that passages with similar meaning sit close together in that space. That is the video's second concept. At query time you embed the question with the same model, or a model pair trained to share the space, and look for nearby chunk vectors.

The usual similarity is cosine similarity, or the equivalent inner product on normalized vectors. Higher dimension is not automatically better. What matters is that the model was trained for retrieval, that it handles your languages and domains, and that you never mix vectors from two incompatible models in one index. A general model will treat a product SKU or an internal acronym as just another token — which is one reason hybrid search exists. Embed offline in batches, and re-embed the corpus when you change models.

Vector databases, indexes, and metadata

A vector database stores those embeddings and, as the video says, finds the closest chunks in milliseconds. Exact search is too slow at scale, so production systems use approximate nearest neighbor (ANN) indexes that trade a little recall for speed.

HNSW, Hierarchical Navigable Small World, is the index most teams meet first. It builds a layered graph: upper layers let the search jump across the space, lower layers refine the result, and a search starts at the top and greedily walks toward the query vector. You tune it with parameters such as M (neighbors per node) and ef (candidates considered). Higher values improve recall and cost more memory and latency.

The store should not hold vectors alone. Each record needs the chunk text or a pointer to it, the parent document ID, and metadata you can filter on: source, date, team, product, language, access group. The video lists this as concept 5. Keep a lexical index alongside the vectors for hybrid search and exact identifiers.

Retrieval: dense, sparse, and hybrid

Dense retrieval is the embedding search above. It is strong when the user and the document use different words for the same idea: "how do I get my money back?" should still find a page titled "Refund policy."

Sparse retrieval, most often BM25, is the classical keyword method used in search engines. It scores a document by term frequency, down-weighted by how common the term is in the collection. BM25 is excellent at exact identifiers: names, SKUs, RFC numbers, and API error strings.

Hybrid search, concept 4 in the video, combines the two. Retrieve a candidate set from each method, then fuse the rankings with reciprocal rank fusion (RRF). Try hybrid search first: exact names and fuzzy ideas are both covered. Always apply metadata filters as part of the index query. Fetch more candidates than you will send to the model — the top 20 to 50 is a common range — because reranking is where the list gets short.

Fixing the question

Users do not ask questions the way your documents are written. The next three concepts in the video close that gap before you search.

Query rewriting turns a vague question into a self-contained search query. "What about the thing we changed last month?" might become "2026 shipping policy change for international orders." Preserve dates, product names, and exclusions the user stated.

Query decomposition splits a question that is actually several questions, retrieves for each part, and composes the answer. This is also the start of multi-hop RAG, where the second search depends on the answer to the first.

HyDE, Hypothetical Document Embeddings, is concept 8. The video's narration says "hide," which is the acronym pronounced that way. The method comes from Gao, Ma, Lin, and Callison-Burch, "Precise Zero-Shot Dense Retrieval without Relevance Labels" (2022; ACL 2023). The model writes a hypothetical answer; you embed that answer and search with it, because answers look like answers. Treat it as a tool you evaluate, not a default you leave on blindly.

Picking the best context

Retrieval gets you a pile of maybe-relevant chunks. The generator should not see the whole pile.

Reranking, concept 9, is the standard fix. You pull a relatively large set — the video's example is the top 50 — and a second model scores each query-passage pair. Cross-encoders read the question and the passage together, which is slower than a vector lookup and much more accurate. You then keep the best handful, often three to ten, for the prompt.

Small-to-big retrieval expands each winning small chunk to its parent section, so the model sees definitions and exceptions that did not sit inside the matched window. Context compression, concept 11, strips residual irrelevance so you fit the context window and cut cost. Measure recall after you add it, because compression can also delete the one clause that changed the answer. Finish with a short, ordered list of passages, each with a source ID you can cite.

Augmentation and prompt construction

The prompt is a contract. A solid pattern has four parts: a system instruction that tells the model to use only the provided sources, cite them, and say when they are insufficient; the retrieved passages, each clearly delimited, with a stable source label, title, date, and URL or document ID; the user question; and output instructions for structure and citation format.

Order the passages with the most relevant first, unless you have measured that your model attends better to the end of the context. Do not allow untrusted document text to override the system instruction. Keep a hard cap on tokens so a long retrieval cannot crowd the question out of the window.

A minimal retrieve-then-generate loop, in Python-like pseudocode, is:

def answer(question, user):
    query = rewrite(question)
    filters = access_filters(user)  # tenant, team, document ACL
    dense = vector_search(embed(query), k=50, filters=filters)
    sparse = bm25_search(query, k=50, filters=filters)
    candidates = reciprocal_rank_fusion(dense, sparse)
    ranked = cross_encoder_rerank(query, candidates)[:5]
    passages = expand_to_parent_sections(ranked)
    prompt = render_prompt(question=question, passages=passages)
    response = generate(prompt)
    return response, citations(passages)

That is the video's path — rewrite, retrieve, rerank, generate — with access control where it belongs: on the retrieval call, not after the fact.

Generation with citations

The generator's job is to write a readable answer that a reader can verify. Faithfulness is the requirement: every claim should be supported by the retrieved context, which is concept 14 in the video.

Citations make that requirement testable. Each factual sentence, or each paragraph, should point at the passage it came from. Use the same IDs you put in the prompt, and show the reader a title and a link, not a raw vector ID. If two sources disagree, say so and cite both. If the passages do not contain the answer, the model should refuse rather than fill the gap from memory.

Do not confuse a citation with proof. Models sometimes attach a plausible source to a sentence they still invented, which is why you evaluate faithfulness against the actual passage text.

Advanced patterns

Once the basic path works, four extensions appear in real systems.

GraphRAG, concept 12, builds a knowledge graph of entities and relationships, then retrieves along those links. Microsoft's 2024 paper by Edge and colleagues, "From Local to Global: A Graph RAG Approach to Query-Focused Summarization", is the usual reference. You extract entities and relations, summarize clusters of the graph, and retrieve over those summaries when a question cuts across many documents.

Agentic RAG, concept 13, lets the model decide whether to search, which tool to use, and when it has enough. Cap the number of steps, log every tool call, and keep the same access filters on every retrieval.

Multi-hop retrieval plans two or three searches, or uses the answer of hop one as the query of hop two, without a fully general agent.

Self-RAG (Asai et al., "Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection", 2023) trains a model to decide when to retrieve and to critique its output against the evidence. CRAG (Yan et al., "Corrective Retrieval Augmented Generation", 2024) evaluates retrieved documents and triggers a refined search when the first results look weak.

RAG vs. fine-tuning vs. long context

These three options are often pitched as substitutes. They solve different problems, and they combine well.

ApproachWhat it changesStrengthsLimitsUse it when
RAGThe prompt, via retrieved evidenceFresh, citable, corpus-specific answers; update the index without retrainingBad retrieval means a bad answer; adds latencyThe facts live in documents that change, or must be cited
Fine-tuningThe model's weightsStyle, format, domain language, tool use, narrower behaviorExpensive to refresh; not a reliable factual memory; risk of leaking training dataYou need the model to write or behave in a stable, learned way
Long contextHow much you can stuff into one promptSimple; good for a single long document or a small, known set of filesCost and latency grow with tokens; quality can drop as the window fills; does not scale to a whole knowledge baseThe relevant files already fit, and you can name them

Fine-tuning does not replace RAG for facts: a fine-tuned model can still invent a clause, and it cannot cite a page you added yesterday. RAG does not replace fine-tuning for behavior, such as a stable company voice. Long context changes the economics of retrieval, but it does not erase it. Three PDFs can go in the prompt; 40,000 support articles still need a search step.

Evaluation

If you cannot measure the system, you will tune it by anecdote. The video ends on this point for a reason.

Faithfulness asks: is every claim in the answer actually backed by the retrieved context? An answer can be factually true in the world and still unfaithful if the model did not get that fact from the sources you provided.

Context precision asks: of the chunks we retrieved, how many were actually relevant? Context recall asks: of the chunks we needed, how many did we retrieve? Precision tells you whether you are stuffing the prompt with noise. Recall tells you whether the evidence never arrived. A fourth question is answer relevancy: did we address the user's actual question?

RAGAS (Es et al., 2023) is a common open-source toolkit for these ideas. It is a starting point, not a verdict. Build a small evaluation set of real questions, the documents that should be retrieved, and answers you would ship. Track retrieval metrics such as recall@k separately from generation metrics.

Production concerns

A prototype that answers five demo questions is not a production RAG system.

Latency. The user waits on query embedding, index lookups, a reranker, and the generator. Budget a p95, not just an average.

Cost. You pay to embed the corpus and every query, to rerank candidates, and, above all, to send context tokens to the generator.

Freshness. The index needs incremental updates, deletes, and a rebuild path. A filter on updated_at is not enough if the new file has not been parsed yet.

Security and access control. Every query must carry the user's identity and only search documents that identity may see. ACL filters belong in the index query, not after the fact.

Prompt injection. Retrieved text is untrusted input. Treat passages as data, not as instructions, and do not let a retrieved page trigger an unauthorized tool call.

Observability. Log the rewritten query, chunk IDs and scores, token counts, stage latency, and citations, so you can tell a retrieval miss from a generation miss.

A reference architecture

Each stage should be replaceable and measurable.

  1. Source connectors pull from file stores, wikis, ticket systems, and databases.
  2. Parsing workers extract text and attach document IDs, hashes, and ACLs.
  3. A chunker writes chunk records with parent IDs and a parent-child map for small-to-big retrieval.
  4. An embedding worker upserts vectors for new or changed chunks and updates a lexical index in the same job.
  5. The indexes hold HNSW (or equivalent ANN) vectors, BM25 postings, and filterable metadata.
  6. A query service authenticates the user, rewrites the question, runs hybrid retrieval under ACL filters, reranks, and expands to parent sections.
  7. A prompt builder renders instructions, delimited passages with source labels, and citation rules.
  8. A generator produces the answer, preferably with structured citations. A grader can reject or re-query weak evidence.
  9. An evaluation and logging plane stores traces, scores faithfulness and context precision and recall, and alerts on lag and latency.

That is RAG end to end.

If you want more walkthroughs like this, follow @rankcore.ai and browse the rest of the guides on blog.rankcore.ai.

Want to go deeper?

Our step-by-step video courses turn these ideas into results.

See courses

Comments

Sign in or create a free account to join the discussion.

No comments yet — be the first.