In 2020, a team led by Facebook AI Research split Wikipedia into 21 million chunks of 100 words and let a language model look things up before it answered. They called the method retrieval-augmented generation, or RAG.
Six years later, RAG is still how developers get a model to answer from documents it never saw in training: help centres, product docs, contracts, whole websites.
It's also where those chatbots go wrong. Often not because of the model.
By the time the model writes a word, much of the answer quality is already fixed: what text you collected, how you cut it up and which pieces the search handed back. That's the part most explainers skip, and it's where scraping tools earn their place.
RAG sits next to MCP and tool calling as one of the main ways an AI app gets context it wasn't trained on. For this guide I read the original paper and the current docs from OpenAI, Anthropic, LangChain, LlamaIndex, pgvector, Firecrawl and Apify.
Some links here are affiliate links. They don't change your price.

What is RAG? The short answer
RAG is a pattern where an AI app searches a knowledge base for passages related to a question, adds the best ones to the prompt, and only then asks the model to answer.
Anthropic's engineering team describes it the same way: RAG "retrieves relevant information from a knowledge base and appends it to the user's prompt." OpenAI's accuracy guide spells out the acronym: Retrieve content, Augment the prompt, then Generate.
Think of it like an open-book exam. The model is still the student doing the writing. RAG decides which pages of the book are open on the desk.
That framing explains most of what follows. A student with the wrong pages open writes a confident, wrong answer. So does a RAG system.
Why do LLMs need retrieval at all?
A language model knows what was in its training data, up to a cutoff date. It doesn't know your pricing page, last week's policy change or the PDF your client sent this morning.
The original RAG paper, by Patrick Lewis and colleagues at Facebook AI Research, UCL and NYU, named three problems with models that only use what's stored in their weights. They can't easily expand or revise that memory, they can't show where an answer came from, and they produce "hallucinations".
Their fix was to pair the model with an external index it could search. One experiment shows why that matters.
The team swapped a 2016 Wikipedia index for a 2018 one and asked about world leaders who had changed in between. With the matching index, the model answered 70% and 68% correctly. With the mismatched index, accuracy fell to 12% and 4%.
No retraining was involved. They changed the documents, and the answers changed with them.
That's the whole appeal in one result. With RAG, keeping an AI app current becomes a document problem, not a training problem.
How does RAG work, step by step?
Every RAG system has two halves. An indexing pipeline runs ahead of time and prepares your documents. A query pipeline runs each time someone asks a question. In n8n those halves become two separate workflows, which is how I set them up in my tutorial on building a RAG chatbot in n8n.
LangChain's docs split indexing into four steps: load, split, embed and store. LlamaIndex lists five stages: loading, indexing, storing, querying and evaluation. The names differ, but the shape is the same. Here it is as six steps.

Step 1: Ingest the source text
Ingest means getting your content out of wherever it lives and into plain text: web pages, PDFs, Notion pages, database rows, support tickets.
This step decides the ceiling for everything after it. If a cookie banner, a mega-menu and three "related posts" widgets come along with the article text, they get chunked and embedded too. Later they show up in search results.
Clean text in, useful chunks out. That's why markdown has become the default format for this step, and I'll come back to it in the scraping section.
Step 2: Chunk the documents
Chunking means splitting each document into smaller pieces that can be searched one by one. A whole 40-page manual can't be retrieved as one unit, and it wouldn't fit in a useful prompt anyway.
There's no single right size, and the defaults vary a lot:
- The original paper used 100-word chunks with no overlap.
- OpenAI's vector stores default to 800-token chunks with a 400-token overlap, and let you set anything from 100 to 4,096 tokens.
- LangChain's RAG tutorial splits at 1,000 characters with a 200-character overlap.
- Anthropic's write-up says chunks are "usually no more than a few hundred tokens".
Overlap repeats the end of one chunk at the start of the next, so a sentence cut in half still appears whole somewhere. Smaller chunks give sharper matches but lose surrounding context. Bigger chunks keep the context and dilute the match.
My take: start with your tool's default, then change it only when your evaluation questions show a pattern of misses. Picking a chunk size by gut feel is how people waste a week.
Step 3: Embed each chunk
An embedding model turns each chunk into a vector, a long list of numbers that captures its meaning. Chunks about similar things end up close together, even when they use different words.
OpenAI's text-embedding-3-small produces 1,536 numbers per chunk by default, and text-embedding-3-large produces 3,072. Both accept up to 8,192 tokens of input.
Embedding is cheap. At OpenAI's list price of $0.02 per million tokens for text-embedding-3-small, 1,000 pages of about 800 tokens each come to roughly $0.016 (my arithmetic, as of 21 October 2026). The large model costs $0.13 per million tokens, so the same 1,000 pages come to about $0.10.
One rule matters more than which model you pick. Embed your questions with the same model you used for your chunks, or the distances mean nothing.
Step 4: Store the vectors
The vectors go into a database that can find the nearest neighbours of a new vector quickly. That can be a dedicated vector database, or Postgres with the pgvector extension, which is what Supabase uses for its vector features. If this part is new to you, my plain-English guide on what a vector database is explains embeddings, similarity search and HNSW indexes.
A minimal pgvector setup for chunks made with text-embedding-3-small looks like this:
The query sorts by cosine distance, the measure OpenAI recommends for its embeddings. Store the source URL with every chunk. You'll need it for citations and for debugging.
On Supabase there's one more wrinkle. Its docs note that the client libraries can't call pgvector's operators directly, so you wrap the similarity query in a Postgres function and call it with rpc().
Step 5: Retrieve the best chunks
When a question arrives, the app embeds it, finds the closest chunks and keeps the top few. That's semantic search.
Here's the catch: semantic search is weak at exact matches. Anthropic's example is a support search for "Error code TS-999". An embedding model finds content about error codes in general and can miss the one page that mentions TS-999.
The fix is hybrid search. Run a keyword ranking such as BM25 next to the vector search, then merge the two lists. OpenAI's file search already combines semantic and keyword search this way.
Anthropic measured how much better retrieval gets as you stack these techniques. Adding a short, generated context line to each chunk before embedding cut the top-20 retrieval failure rate by 35%. Adding contextual BM25 took that to 49%, and adding a reranker took it to 67%, from 5.7% of relevant chunks missed down to 1.9%.
Those are Anthropic's numbers on Anthropic's datasets. Treat them as a direction, not a promise for your documents.
Step 6: Generate the answer
Finally, the app builds a prompt from the question and the retrieved chunks and sends it to the model. The prompt matters more than people expect.
Here's a prompt adapted from the example in OpenAI's embeddings guide, with a citation rule added:
The "I don't know" line gives the model a way out that isn't making something up. The citation line lets you, and your users, check its work.
Where do scraping tools fit in a RAG pipeline?
Scraping tools live in step 1. When your knowledge base is a website, yours or a public one, someone has to turn those pages into clean text before any chunking or embedding can happen.
A raw HTML page is mostly markup, navigation and scripts. Feed that straight into a chunker and your vector store fills up with menu labels and footer links. Tools built for this job do three things a basic HTTP fetch doesn't:
- They render JavaScript, so content that only appears in the browser gets captured.
- They strip the page chrome and keep the main content.
- They output markdown, which keeps headings, lists and tables. Chunkers can split on those headings, so chunks follow the document's own structure.

Firecrawl is built around this. Its scrape endpoint turns a URL into "clean Markdown or structured data", handles JavaScript-heavy pages and also parses PDFs into markdown. Its crawl endpoint follows a site's sitemap and links and returns markdown for every page it reaches. Each scraped page costs 1 credit, and the free plan includes 1,000 credits a month with no card, as of 21 October 2026.
I've collected working code for scrape, crawl, map and batch jobs in my Firecrawl API examples. If you're sizing a bigger crawl, Firecrawl's pricing breaks down what credits cost per plan.
For the full ingest step, from crawl settings that strip boilerplate to splitting pages on their headings, see my step-by-step guide on how to scrape a website to markdown for LLMs.
Apify's answer is an Actor called Website Content Crawler. Apify says it crawls sites "to feed AI models, LLM applications, vector databases, or RAG pipelines", outputs Markdown, plain text or HTML, strips navigation, headers, footers, ads and cookie banners, and plugs into LangChain, LlamaIndex, Pinecone and Qdrant. It's billed per usage, and Apify's free plan gives you $5 of usage each month.
Which one? Firecrawl is the shorter path when you want markdown back from an API call in your own code. Apify suits teams that want a configurable crawler with ready integrations and a dashboard to run it from.
One more thing before you point a crawler at someone else's site. Scraping public pages can still run into terms of service, copyright and privacy law, especially if the pages contain personal data. I covered those layers in is web scraping legal?, and it's worth ten minutes before you index a site you don't own.
RAG vs fine-tuning vs long context: which one do you need?
These three get compared as if they compete. They solve different problems.
| RAG | Fine-tuning | Long context | |
|---|---|---|---|
| What it changes | What the model sees for each question | The model's learned behaviour | What the model sees for each question |
| Best for | Large or changing knowledge, answers with sources | Consistent format, tone or task behaviour | Small, stable sets of documents |
| Updating knowledge | Re-index the changed documents | Collect examples and train again | Edit the prompt |
| Cost per question | A search plus a few thousand tokens | Normal inference on the tuned model | Every document token, every time, cheaper with caching |
| Citations | Easy, you know which chunks went in | Hard | Possible, but the model must point to the passage |
| Typical failure | Search misses the right chunk | Behaves well, still lacks fresh facts | Details lost in the middle, cost at scale |
| Setup effort | Medium | High | Low |
OpenAI's own accuracy guide draws the same line. RAG is for giving the model context, fine-tuning is for teaching it consistent behaviour, and production systems often use both. If a model answers in the right format but with wrong facts, fine-tuning won't help. If it has the right facts but ignores your format, more retrieval won't help.
Is RAG dead now that context windows hold a million tokens?
No, but the threshold moved.
In 2024, Anthropic wrote that if your knowledge base is under 200,000 tokens, about 500 pages, you could skip RAG and put everything in the prompt. Today every current Claude model lists a 1-million-token context window, and many Gemini models have 1 million or more.
Run the numbers with Claude Sonnet 5.5's list prices as of 21 October 2026 ($2 per million input tokens, $0.10 per million for cache hits). It covers input tokens only:
- Stuffing a 500,000-token knowledge base into every question: $1.00 per question.
- The same prompt served from the prompt cache: $0.05 per question, plus $1.25 each time the cache is written.
- RAG sending 20 chunks of 800 tokens: 16,000 tokens, about $0.03 per question.
Caching narrows the gap a lot. For a small, stable document set that gets many questions in a short window, long context with caching is the simpler build.
Two things still favour RAG. Knowledge bases grow past any window, and a help centre with thousands of articles won't fit. And models don't read long prompts evenly. The "Lost in the Middle" study (Liu et al., 2023) found accuracy was highest when the relevant passage sat at the start or end of the context and dropped significantly when it sat in the middle.
My rule of thumb: if the whole corpus fits comfortably and rarely changes, try long context first. If it's large, changes weekly or needs citations, build RAG.
Why do RAG systems give wrong answers?
OpenAI's guide splits RAG failures into two buckets. Retrieval can supply the wrong context, or so much irrelevant context that it drowns the right passage. Or the model gets the right context and does the wrong thing with it.
That split is the most useful debugging habit in RAG. Before you touch the prompt, check whether the right chunk was even retrieved.

The failure modes that show up again and again in the docs and papers I read:
- Dirty source text: boilerplate from menus and footers fills chunks and outranks the real content.
- Chunks without context: Anthropic's example is a chunk reading "The company's revenue grew by 3% over the previous quarter" with no company or quarter named, so it can't be matched to the question.
- Exact terms missed: product codes, error codes and names that pure vector search glides past. Hybrid search fixes most of this.
- Too much context: stuffing in more chunks can bury the one that matters, and lost-in-the-middle effects make it worse.
- A stale index: the documents changed, the vectors didn't. LangChain's docs recommend refreshing the vector store on a schedule when the source changes.
- Poisoned or leaked content: retrieved text is input the model reads and may obey. OWASP's 2025 Top 10 for LLM apps lists vector and embedding weaknesses as LLM08, covering injected content and data leaking to users who shouldn't see it.
That last one deserves its own warning. If your RAG system indexes pages you don't control, a hidden instruction on one of them can end up in the prompt. That's indirect prompt injection, and RAG is one of its most common entry points. Filter retrieval by user permissions too, so one customer's documents never answer another customer's question.
How do you evaluate a RAG system?
Evaluate the two halves separately, with your own questions.
Start by writing a set of real questions your users ask, each with the answer and the document it should come from. Then measure:
- Retrieval: did the right chunk appear in the top results? Anthropic used recall at 20, the share of relevant chunks found in the top 20.
- Generation: is the answer supported by the retrieved text, and does it answer the question?
The Ragas library packages these as named metrics. Context Precision and Context Recall check retrieval. Faithfulness checks whether the answer sticks to the retrieved context, and Response Relevancy checks whether it addresses the question.
Log the retrieved chunks with every answer in production too. When a user reports a wrong answer, that log tells you in seconds which half broke.
Rerun the same question set after every change to chunk size, embedding model, retrieval settings or prompt. Anthropic's write-up puts it in three words: always run evals.
Is RAG still relevant with AI agents and MCP?
Yes. Agents changed who decides when to search.
In classic RAG, every question triggers one search. In agentic RAG, the model gets search as a tool and decides when to call it, what to search for and whether to search again after reading the first results. LangChain's current RAG tutorial is built on its Deep Agents library, with patterns like retrieving chunks, offloading them to files and delegating reading to sub-agents.
That's a loop rather than a single pass, so the design questions shift to when the agent should stop searching and how it checks its own answer. I covered those in my guide to loop engineering in AI.
MCP fits underneath. A retrieval system can be exposed as an MCP server so any compatible app can search it, and Firecrawl runs a hosted MCP server that gives agents scrape and search as tools. MCP moves the context. RAG decides which context is worth moving.
Where RAG falls short
RAG is not a hallucination cure. If retrieval returns the wrong passage, the model can write a fluent answer from it. If it returns nothing useful, the model may fall back on its training data unless the prompt forbids it.
It also adds moving parts: a crawler or loader, a chunker, an embedding model, a database and an evaluation set, each of which can drift. For a few dozen stable pages, that's overkill. Long context or a well-written system prompt will get you there faster.
And it can't fix bad source material. If your docs contradict each other or are out of date, RAG will retrieve the contradiction faithfully.
Skip RAG if your knowledge fits in the prompt, rarely changes and doesn't need citations. Build it when the documents are many, change often and the answer has to point back to a source.
Frequently asked questions
If you're starting a RAG project this week, spend your first hours on the boring end of the pipeline. Get clean markdown, keep a source URL on every chunk and write twenty real test questions before you compare embedding models.
The model is the easy part to swap. A messy index follows you everywhere.


