What Is React? A Library for Building UIs from Components
React is a JavaScript library for building interfaces from reusable components. This article runs a real counter button in React and in plain JavaScript to…
Suppose you ask your company's support chatbot about the latest leave policy. It answers fluently and even quotes clauses that sound real. The problem is that the policy changed last month, and the chatbot has no idea. It is not lying to you on purpose. It is only answering from what it remembers from training, back when the old policy was still in force. That gap is why more people are starting to ask what is RAG.
That is a built-in weakness of large language models, or LLMs. Their knowledge freezes at training time. Ask about something that happened after that point, or about internal documents it has never seen, and it still answers with confidence. The answer may just be wrong.
RAG fixes that weakness without retraining the model. What is RAG, in short? It lets the model look things up in your documents before answering, instead of making it remember everything. It is like letting a student bring books into the exam. This article does not explain RAG in the abstract. I built a real mini RAG on five articles from gnurtlab.com itself. I measured how many questions it finds the right answer for, and show what happens when documents are split the wrong way.
Quick summary
- What is RAG: a technique that lets an LLM look up your documents before answering, so answers rest on fresh facts and carry sources you can check.
- The mini RAG on five gnurtlab.com articles (12,721 words) found the article with the answer in 8/8 test questions with paragraph chunking; fixed 25-word windows dropped it to 5/8.
- RAG does not replace fine-tuning: RAG adds new facts, fine-tuning teaches behavior. A small document set can just be pasted into the prompt.
RAG stands for Retrieval-Augmented Generation. It is a technique that lets a large language model look up external documents before generating an answer. You ask a question. The system finds the most relevant passages, puts them into the prompt with your question, and the model answers from those passages. Answers then rest on fresh facts and internal documents, with sources you can check.
The term comes from the paper "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks". Its first author is Patrick Lewis, a researcher at Facebook AI Research (now Meta AI) and University College London at the time, with 11 co-authors. The paper was submitted to arXiv on 22/05/2020 and accepted at the NeurIPS 2020 conference. The original model combined two kinds of memory. Parametric memory was the pre-trained BART text generator. Non-parametric memory was a dense vector index of Wikipedia, read through a neural retriever called DPR. The original index was built from the December 2018 Wikipedia dump, split into 100-word passages, 21 million of them in total. With it, the authors set the best results of the time on three open-domain question answering tasks: Natural Questions, WebQuestions, and CuratedTrec.
The word that matters is "external". An ordinary LLM only has the knowledge in its weights, what it learned during training. RAG adds a bookshelf beside it: your documents, updated whenever you like. To change a number in a document, you edit the document and re-index. No retraining needed. That is why RAG fits facts that change fast and facts that are private: things that never appear in public training data.
To see what is RAG in practice, look at how a RAG system runs in four steps. I use the mini RAG in this article as the running example, so every step points at something real.
Step 1: load the documents. You gather the documents the AI needs to search: articles, PDFs, an internal wiki, support tickets. The mini RAG loads five articles from gnurtlab.com on AI agents, MCP, APIs, Python, and SQL. That is 12,721 words in total.
Step 2: split the documents into chunks. A chunk is the smallest unit the system retrieves. Split too big and each chunk carries irrelevant information. Split too small and a chunk loses context. The mini RAG splits by paragraph, at most about 150 words per chunk, with each heading merged into the paragraph after it. That gives 109 chunks.
Step 3: embed and index. Each chunk becomes a vector, a list of numbers that stands for the meaning of that passage, and goes into a vector store for fast search. Real systems use a neural embedding model for this step. The demo uses TF-IDF, a classic method based on word frequency. TF-IDF does not understand meaning the way a neural embedding does. It only counts which words appear where. But it is enough to measure how chunking affects quality, and it runs on this machine with no GPU.
Step 4: retrieve, then generate. When you ask a question, the system turns it into a vector of the same kind, finds the nearest chunks by cosine similarity, puts the top 3 chunks into the prompt, and the LLM answers from them. The generation step with a real LLM does not run in this demo, because this machine has no local LLM. The demo measures retrieval accuracy: whether the system finds the passage with the answer. Retrieval has to be right first. With the wrong chunk, even a strong LLM struggles to answer correctly.
The code below is the exact code that ran on this machine on 06/12/2026, with Python 3.12.3 and scikit-learn 1.9.1. It is written in Python. You can run it again right after installing scikit-learn.
#!/usr/bin/env python3
# Mini RAG: retrieval over 5 gnurtlab.com articles
# Run: pip install scikit-learn (tested with scikit-learn 1.9.1)
# python3 rag_mini.py
import re
import urllib.request
from html.parser import HTMLParser
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
DOCS = {
"what-is-an-ai-agent": "https://gnurtlab.com/en/what-is-an-ai-agent/",
"what-is-mcp": "https://gnurtlab.com/en/what-is-mcp/",
"what-is-an-api-how-it-works-and-why-every-app-needs-it": "https://gnurtlab.com/en/what-is-an-api-how-it-works-and-why-every-app-needs-it/",
"what-is-python": "https://gnurtlab.com/en/what-is-python/",
"what-is-sql": "https://gnurtlab.com/en/what-is-sql/",
}
class TextExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.in_article = False
self.depth = 0
self.parts = []
self.skip = False
def handle_starttag(self, tag, attrs):
d = dict(attrs)
if tag == "article" and d.get("id") == "article":
self.in_article = True
self.depth = 1
return
if self.in_article:
if tag == "article":
self.depth += 1
if tag in ("script", "style", "figure", "nav", "pre"):
self.skip = True
if tag in ("h2", "h3"):
self.parts.append("\n## ")
elif tag in ("p", "li"):
self.parts.append("\n")
def handle_endtag(self, tag):
if self.in_article and tag == "article":
self.depth -= 1
if self.depth == 0:
self.in_article = False
if tag in ("script", "style", "figure", "nav", "pre"):
self.skip = False
def handle_data(self, data):
if self.in_article and not self.skip:
self.parts.append(data)
def fetch_article(url):
req = urllib.request.Request(url, headers={"User-Agent": "RAG-mini-demo"})
html = urllib.request.urlopen(req, timeout=30).read().decode("utf-8")
extractor = TextExtractor()
extractor.feed(html)
text = "".join(extractor.parts)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n\s*\n+", "\n", text)
cut = re.search(r"\n## Sources(\s|$)", text)
if cut:
text = text[:cut.start()]
return text.strip()
def split_sentences(text):
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
def split_chunks(text, max_words=150):
paras = [p.strip() for p in text.split("\n") if p.strip()]
merged = []
for p in paras:
if p.startswith("## ") and merged and merged[-1].startswith("## "):
merged[-1] = merged[-1] + " " + p
elif p.startswith("## "):
merged.append(p)
elif merged and merged[-1].startswith("## "):
merged[-1] = merged[-1] + " " + p
else:
merged.append(p)
chunks = []
for p in merged:
p = p.replace("## ", "")
words = p.split()
if len(words) <= max_words:
chunks.append(p)
else:
buf, count = [], 0
for sent in split_sentences(p):
n = len(sent.split())
if count + n > max_words and buf:
chunks.append(" ".join(buf))
buf, count = [], 0
buf.append(sent)
count += n
if buf:
chunks.append(" ".join(buf))
return chunks
def retrieve(question, vectorizer, matrix, chunks, k=3):
q = vectorizer.transform([question])
scores = cosine_similarity(q, matrix)[0]
order = scores.argsort()[::-1][:k]
return [(chunks[i], float(scores[i])) for i in order]
if __name__ == "__main__":
chunks, owners = [], []
for slug, url in DOCS.items():
text = fetch_article(url)
for c in split_chunks(text):
chunks.append(c)
owners.append(slug)
print(f"{slug}: {len(text.split())} words")
vectorizer = TfidfVectorizer(lowercase=True, sublinear_tf=True)
matrix = vectorizer.fit_transform(chunks)
print(f"index: {len(chunks)} chunks")
for question in ["What is MCP?", "How is an AI agent different from a chatbot?"]:
print(f"\nAsk: {question}")
for chunk, score in retrieve(question, vectorizer, matrix, chunks):
print(f" [{owners[chunks.index(chunk)]}] {score:.3f}: {chunk[:120]}")
To measure quality, I wrote 8 test questions myself. Each one has an expected answer: the article that holds the answer. I ran three chunking methods on the same 8 questions with the same TF-IDF retrieval.
| Chunking method | Chunks | Top 1 correct | Top 3 correct |
|---|---|---|---|
| A. By paragraph, max ~150 words | 109 | 8/8 | 8/8 |
| B. Whole article as one chunk | 5 | 8/8 | 8/8 |
| C. Fixed 25-word windows, cut mid-sentence | 512 | 5/8 | 8/8 |
Top 1 correct means the top chunk belongs to the article with the answer. Top 3 correct means one of the top three chunks does.
Method B looks best at 8/8. But the number is misleading. Each "chunk" in method B is a whole article of 1,607 to 3,335 words. Retrieval returns the right article. But the LLM gets a prompt with the entire article in it, while the answer is only a few sentences of that. Cosine similarity scores for method B are also very low, only 0.14 to 0.18, against 0.20 to 0.35 for method A. The system barely distinguishes the articles. It is only right because each article is a single chunk. Anthropic calls this context rot: a model's ability to recall information falls as the number of tokens in context grows. Their advice is to keep the smallest possible set of high-signal tokens. Method B does the opposite.
Method C is the worst, and it fails the way beginners usually fail: 25-word windows cut sentences in half, so chunks lose context. The question "What is an API?" came back with a chunk from the SQL article. It scored 0.463, higher than the correct chunk from the API article. "What is Python used for?" came back with a chunk from the MCP article. "What is SQL used for?" also came back with a chunk from the MCP article.
The problem is not that TF-IDF is weak in general. It is that a short chunk has too few sentences to tell two things apart: "this article defines API" and "this article mentions API while talking about something else". Both articles mention API many times. MCP is a standard for connecting AI to tools, and an API is how software talks to other software. With only 25 words per chunk, nothing is left but keywords, and random keyword overlap wins.
The fix in a real system is a meaning-based embedding instead of word counting. Add a reranking step too: another model scores the top chunks again before they reach the prompt. But reranking only helps if the right chunk still makes the top list. If chunking has already shredded the answer, no later step can repair it.
Even method A, the best of the three, has a weakness that chunking cannot fix. The Vietnamese run of the same experiment missed one question. "What is Python used for?" returned a chunk from the AI agent article instead of the Python article. The AI agent article has Python code samples and mentions Python many times. TF-IDF scored that chunk 0.184, above the Python article's best chunk at 0.150. The English run got all 8 right, but the same risk applies: in a real document store, articles always mention each other.
Pure keyword retrieval will pick the wrong article sooner or later. The fix is a meaning-based embedding and hybrid search, which combines keyword search with vector search. Then check the system against a test set of your own questions.
One smaller bug also showed up while I built the demo. At first I left headings standing alone, not merged with the paragraph after them. The top chunk for "What is MCP?" was then just the three words "What is MCP?", with no answer inside. A heading with no content is useless even when retrieval finds it. I fixed it by merging each heading with the paragraph right after it. It is a small bug, but a common one when people split documents by character count and forget the structure of the text.
RAG is only "fresh" while someone re-indexes the documents, and this is the part most explanations of what is RAG leave out. I checked this with a small test on the mini RAG itself. The AI agent article has a statistic from a McKinsey survey from August 2026. 40% of organizations with revenue above $1 billion say they are scaling AI agents, up from 27% a year earlier. I assumed the article was updated and the figure changed from 40% to 46%. Then I asked the system: "what percentage of organizations with revenue above 1 billion dollars are scaling AI agents?"
With the old index, not re-indexed after the article changed, the system returned the chunk with the 40% figure, at a similarity score of 0.330. With the new index, the same question returned the chunk with 46%, at a score of 0.331. The scores are nearly identical. The content is completely different. The system has no idea the fact is out of date.
The practical consequence is that RAG needs a re-indexing routine. When a document changes, the index changes with it, on a schedule or right when the document changes. Skip that step and RAG goes stale exactly like an LLM does, except that you believe it is fresh. If your documents change all the time and nobody owns re-indexing, RAG will answer with confidence from old facts. That is the exact failure you built RAG to avoid.
OpenAI, in its guide to optimizing LLM accuracy, calls RAG, fine-tuning, and pasting documents into the prompt three different levers. RAG belongs to the context optimization axis: giving the model knowledge it lacks or that has gone out of date. Fine-tuning belongs to the model optimization axis: fixing inconsistent behavior such as wrong formats or wrong tone. The two axes add up instead of excluding each other.
| Your situation | Choose | Why |
|---|---|---|
| Answers live in documents that change often, or need sources to check | RAG | Edit the document and re-index, no retraining. A study by Oded Ovadia and colleagues (December 2023) found RAG consistently beat unsupervised fine-tuning at adding knowledge, for facts the model already knew and for entirely new facts. |
| Every answer must follow one format, tone, or set of rules | Fine-tuning | This is a behavior problem, not a knowledge problem. OpenAI advises starting with 50 or more examples. |
| You need fresh facts and a strict format | Both | Fine-tuning teaches the model to use retrieved context correctly, RAG supplies the fresh facts. Many large OpenAI deployments use prompt engineering plus RAG alone. |
One thing to say plainly: fine-tuning is not a good way to teach a model new facts. The Ovadia study found that LLMs struggle to learn new facts through unsupervised fine-tuning. If your goal is "teach the model more facts", RAG is usually the shorter and cheaper path. RAG cannot fix behavior, though. That is when fine-tuning earns its place.
Knowing what is RAG also means knowing when you do not need it. When the documents are few and still fit in the prompt, skip the retrieval system. Just paste the documents into the prompt. But remember Anthropic's advice: keep the smallest possible set of high-signal tokens. The more tokens you stuff in, the harder the model finds the part that matters.
When the answer only needs general knowledge, with no documents of your own, you need none of the three. A clear prompt is enough. OpenAI advises starting with the simplest prompt and only moving up when an evaluation set shows the prompt is not enough.
| Wrong | Right |
|---|---|
| RAG stops hallucinations completely | RAG reduces them, it does not end them. An LLM can still misread the context it retrieves. MIT Technology Review gives an example: the model read the rhetorical chapter title "Barack Hussein Obama: America's First Muslim President?" and concluded the United States once had a Muslim president. The retrieved fact was real, the reading was wrong. |
| RAG replaces fine-tuning | They fix different things: RAG adds facts, fine-tuning teaches behavior. Want both, use both. |
| RAG needs a large document store | The demo in this article uses 5 articles, 12,721 words, and still measures retrieval quality. Start small, measure with real questions, then grow. |
| RAG means letting the AI read your files | Not quite. RAG means letting the AI read the right passage in your files. Without the retrieval step that picks passages, it is only pasting documents into the prompt. |
| Plug in RAG and the chatbot stops being wrong | Errors can still happen at both steps: retrieval picks the wrong passage, or the model reasons wrongly from the right passage. |
Once you know what is RAG, it needs its place in the bigger picture. What is an AI agent? is a program that decides its own steps to reach a goal. RAG is one way for an agent to get the knowledge it needs while working. What is MCP? is a shared standard for connecting AI to outside tools and data, while RAG organizes search inside your own document store. A retriever that needs data from another system usually calls it through an API. Not every question needs RAG. When the answer sits in one data table, a SQL query may answer faster and more accurately than a whole RAG system.
Once you know what is RAG, you do not need to build a complete system first. Five steps are enough to learn whether RAG fits your documents, before you spend money on it.
DOCS list with your own URLs or files.One last note on measuring: 8 questions is a rough measure, enough to expose chunking errors, but not enough to declare your system good. As the document store grows, you need more questions, and questions written by someone else. You already know where the answers sit, so your own questions tend to match how you split the chunks.
No, at least not for the demo in this article. TF-IDF runs fine on an ordinary CPU. Small neural embeddings also run on CPU, only slower. A GPU only really matters when you index millions of documents.
Google search returns a list of web pages, and you read them and draw your own conclusions. RAG picks the most relevant passage from your own documents, then lets the LLM read those passages and write an answer. Google searches the public web, RAG searches your documents, including internal ones that were never published.
Yes, but in two different places. Indexing costs once per document, and again each time a document changes. Answering costs per question, because each question sends a few chunks in the prompt and the prompt gets longer. RAG is cheaper than fine-tuning when documents change often, because you only re-index instead of retraining a model.
There is no minimum number. The demo in this article uses 5 articles and still measures. What matters more than count is whether the documents hold the answers users ask for.
Not fully. RAG updates facts, what the model knows. It does not update capability, how well the model reasons. When a much better model comes out, you still need to switch models, and your RAG moves over with it.
RAG is not magic. It organizes something people already do: before answering, open the documents and look it up. The new part is that a machine does the looking up automatically, across a large document store, and puts the right passage into the prompt. To learn what is RAG and whether it fits your documents, do not trust anyone's promises, including this article's. Run the sample code on five of your own documents, write 8 test questions, and see how many it gets right. That number answers more honestly than any promise.
Comments
You can use your Google account to comment. Google only shares your verified name and email address to display your name. You can log out at any time.
Sign in with GoogleNo comments yet. Be the first!