On this page
- What is RAG, in plain terms?
- Where did RAG come from?
- How does RAG work, step by step?
- 1. Split documents into chunks
- 2. Turn each chunk into an embedding
- 3. Store the vectors
- 4. Retrieve the best matches
- 5. Add the chunks to the prompt and generate
- 6. Keep the index current
- How do you make RAG retrieval better?
- Contextual retrieval
- Reranking and query rewriting
- GraphRAG
- What is agentic RAG?
- RAG vs fine-tuning vs long context: which should you use?
- Where you already use RAG
- How to build a RAG system: hosted services and what they cost
- Does RAG stop hallucinations?
- Is RAG safe? The security risks
- Frequently asked questions
RAG, short for retrieval-augmented generation, is a way of making an AI model look things up before it answers. When you ask a question, the app first searches a collection of documents for the passages that best match it, pastes those passages into the model's prompt, and has the model write its reply from them. That lets a chatbot answer from material it was never trained on, such as your company's handbook or this week's news, and point to the source behind each claim.
You've probably used it already. AI search engines, Claude's Projects, Google's Gemini Notebook (formerly NotebookLM) and most "chat with your documents" features run on some version of it. Below: where the idea came from, how a pipeline works, how it compares with fine-tuning and million-token context windows, what hosted services cost and where it still goes wrong.
What is RAG, in plain terms?
A language model on its own is like a student sitting a closed-book exam. Everything it knows was absorbed during training, it can't check anything, and its knowledge stops at a cutoff date. RAG turns that into an open-book exam: before the model answers, a search step hands it the pages most likely to hold the answer. NVIDIA's explainer compares the search step to a court clerk who fetches the right precedents for a judge.
The 2020 paper that named the technique describes two kinds of memory. Parametric memory is what a model stores in its weights. Non-parametric memory is an outside index of documents it can search. RAG pairs the two, and that split explains most of its appeal:
- Fresher answers. You update the documents, not the model. AWS points out that this costs far less than retraining a foundation model.
- Private knowledge. The model can answer from your contracts, tickets or wiki without any of it entering its training data.
- Sources you can check. Because the system knows which passages it retrieved, it can cite them.
RAG isn't a model or a product. It's a design pattern, and you can build it around almost any large language model, from a frontier model in the cloud to one running on your laptop.
Where did RAG come from?
The term comes from "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks", a paper by Patrick Lewis and 11 co-authors from Facebook AI Research (now Meta AI), University College London and New York University. It was first posted to arXiv on 22 May 2020 and accepted at NeurIPS 2020.
The original system was small by today's standards. A retriever called DPR searched a December 2018 copy of Wikipedia, cut into 100-word chunks for a total of 21 million passages, and a BART-large model with roughly 400 million parameters wrote the answers. It set state-of-the-art results on three open-domain question-answering tasks.
One experiment in the paper shows the idea that matters most today. The authors built a second index from a December 2016 Wikipedia dump and asked who led various countries. With the matching index, the model got 70% right for 2016 leaders and 68% for 2018 leaders. With the wrong year's index, accuracy fell to 12% and 4%. The model's knowledge changed with the index, and nobody retrained anything.
Lewis later told NVIDIA that the team would have picked a nicer-sounding name had they known how far the work would spread, but nobody had a better idea when the paper was due.
How does RAG work, step by step?
A RAG system has two halves. Indexing happens ahead of time, whenever documents are added or change. Retrieval and generation happen every time someone asks a question.
| Stage | What happens | Examples |
|---|---|---|
| Chunk | Documents are split into passages | 100 words in the 2020 paper; 800 tokens by default in OpenAI's file search |
| Embed | Each chunk becomes a vector of numbers that captures its meaning | Google's gemini-embedding-001 |
| Store | Vectors go into an index built for similarity search | pgvector for Postgres, Qdrant, Milvus |
| Retrieve | The question is embedded and matched against the index, often alongside keyword search | Hybrid search, reranking |
| Generate | The best chunks are added to the prompt, and the model answers and cites them | Any chat model |
1. Split documents into chunks
Whole documents are too long to match precisely, so they're cut into passages. Small chunks match narrowly but lose the text around them; large ones keep more context but blur the match. OpenAI's file search defaults to 800-token chunks that overlap by 400 tokens, and Google's File Search tool lets you set the chunk size and overlap.
2. Turn each chunk into an embedding
An embedding model converts text into a long list of numbers, a vector, placed so that passages with similar meanings sit close together. That's what lets a question about "time off for remote staff" find a policy that only says "leave" and "telecommuting". AWS calls this semantic search: matching on meaning rather than on words.
3. Store the vectors
The vectors go into a database that can find nearest neighbors quickly. pgvector, an open-source extension, adds this to an ordinary Postgres database. Dedicated engines such as Qdrant and Milvus are built for bigger collections; Milvus says it handles tens of billions of vectors.
4. Retrieve the best matches
When a question arrives, it's embedded with the same model and compared against the stored vectors. Embeddings are good at meaning but weak at exact strings such as product codes, error numbers and names, where keyword ranking (usually an algorithm called BM25) does better. Running both is called hybrid search, and Microsoft's docs for Foundry IQ (the service formerly called Azure AI Search) recommend it for maximum recall. Foundry IQ merges the two result lists with Reciprocal Rank Fusion, so a passage that ranks well in both rises to the top.
5. Add the chunks to the prompt and generate
The top few passages go into the prompt with the question and an instruction to answer from them. The model writes the reply and the app attaches citations: OpenAI's file search names the source file, and Gemini's File Search can give the page number in a PDF.
6. Keep the index current
None of this helps if the index goes stale. AWS treats refreshing documents and their embeddings, in real time or in batches, as a standing part of the pipeline.
How do you make RAG retrieval better?
Retrieval is where most RAG systems succeed or fail. If the right passage never reaches the model, no model can answer correctly. These techniques have the best public evidence behind them.
Contextual retrieval
A chunk cut from the middle of a document often loses the details that make it findable. Anthropic's example is a chunk saying revenue grew 3% over the previous quarter, with no hint of which company or which quarter. Anthropic's Contextual Retrieval method, published in September 2024, has a model write 50 to 100 tokens of context for each chunk and adds it to the front before the chunk is embedded and keyword-indexed.
In Anthropic's tests, the share of relevant chunks that didn't make the top 20 results fell from 5.7% to 3.7% with contextual embeddings alone, to 2.9% with contextual keyword search added, and to 1.9% with reranking on top. Those are cuts of 35%, 49% and 67%, at a one-time cost Anthropic put at about $1.02 per million document tokens with prompt caching. Note what's being measured: whether the right passage was retrieved, not how good the final answers were.
Reranking and query rewriting
A reranker is a second model that reads each candidate passage next to the question and scores how relevant it really is. In Anthropic's setup, the first search pulled 150 chunks and the reranker kept the best 20. Query rewriting works on the other end: turning a vague, chatty question into better search queries. OpenAI's vector store search has a rewrite_query option, and Foundry IQ's agentic retrieval splits one question into several subqueries and runs them in parallel.
GraphRAG
Standard RAG struggles with questions about a whole collection, such as "what are the main themes in these reports?", because no single chunk holds the answer. Microsoft Research's GraphRAG, open-sourced on 2 July 2024, has a model pull a knowledge graph of entities and relationships out of the documents and write summaries of closely linked groups in advance. Microsoft reported that it beat basic RAG on comprehensiveness and diversity in roughly 70% to 80% of comparisons, at the upfront cost of building the graph.
What is agentic RAG?
Classic RAG runs one search per question, whether the question needs it or not. Agentic RAG gives the model a search tool and lets it decide: search, read the results, search again with a better query, and stop when it has enough. It's the same loop that defines an AI agent, applied to looking things up, and our explainer on what an AI agent is covers the wider idea.
The big platforms are moving this way. Microsoft now recommends agentic retrieval for new builds on Foundry IQ, its new name for Azure AI Search, and query planning became generally available in the service's REST API version dated 2026-10-01. Amazon's Bedrock Managed Knowledge Base, generally available since 17 June 2026, splits complex questions into subqueries and searches across several knowledge bases.
Agents increasingly reach their data through the Model Context Protocol, where a server can offer a search tool, or documents as resources, to any compatible app; Amazon's docs say MCP-compatible agents can call its managed knowledge bases as a tool. Our guide to MCP explains how the protocol works.
RAG vs fine-tuning vs long context: which should you use?
These three get mixed up because they all try to make a model know more, in very different ways.
| Approach | What it changes | Best for | Weak spot |
|---|---|---|---|
| RAG | What the model reads at question time | Large, changing or private document sets; answers with citations | Only as good as its search; weak at whole-collection summaries |
| Fine-tuning | The model's weights | Tone, format, specialized behavior | Slow to update; no source references |
| Long context | Nothing; you paste everything into the prompt | Material that fits in the window and rarely changes | Cost and delay on every request |
Fine-tuning retrains a model on your examples. AWS's guidance says it can take hours to days, gives no reference to sources and is a poor fit when documents change often. It recommends starting with RAG for questions over your own documents, and notes the two can be combined.
Long context is the serious rival. Every current Claude model accepts 1 million tokens, according to Anthropic's model overview, and OpenAI lists a 1.05-million-token window for every model in its current flagship lineup, GPT-6.2 Astra included. Anthropic's advice in its 2024 Contextual Retrieval post was that a knowledge base under 200,000 tokens (about 500 pages) can simply go into the prompt, with prompt caching to cut the cost.
Research mostly agrees that long context is more accurate when the material fits, and that RAG is much cheaper:
- A 2024 study by Google DeepMind and University of Michigan researchers found long-context models beat RAG on average when given enough resources, while RAG cost far less. Their hybrid, Self-Route, sent a question to long context only when RAG couldn't answer it, performing about as well as long context at 65% less cost for Gemini 1.5 Pro and 39% less for GPT-4o.
- A June 2026 paper using two small language models on a manufacturing safety benchmark found long-context prompting scored 73.1% correct against 65.4% for semantic RAG, at 26 times the token cost per query.
- Long inputs have a blind spot of their own. The "Lost in the Middle" study (TACL, 2024) found models used information best at the start or end of a long input and noticeably worse in the middle.
Here's how we'd decide. If your material fits comfortably in the window, rarely changes and every user is allowed to see all of it, paste it in and cache it. Reach for RAG when the collection is bigger than the window, changes daily, needs per-user permissions, or when you need citations you can audit. Plenty of products already do both, putting whole documents into context while they fit and switching to retrieval when they don't.
Where you already use RAG
- AI search engines. ChatGPT search decides when to search the web and shows links to its sources, and Perplexity's help center describes searching the web in real time and attaching numbered citations. That's RAG with the web as the index. Our roundup of the best AI search engines compares how well they cite.
- Claude Projects. On paid plans (Pro, Max, Ultra, Team and Enterprise), a project switches to RAG automatically when its knowledge approaches the context window limit, using a project knowledge search tool. Anthropic says this expands capacity by up to 10 times, and a label shows when it's on.
- Gemini Notebook. Google renamed NotebookLM to Gemini Notebook on 16 July 2026. Its help pages say chat answers only use data from your sources and cite direct quotes you can hover over to check.
- Local apps. LM Studio lets you attach .docx, .pdf and .txt files to a chat with a model running on your own computer, and uses RAG for documents too long to fit. Our guide to running an LLM locally covers the setup.
How to build a RAG system: hosted services and what they cost
Few teams assemble every piece themselves anymore. The big AI platforms sell retrieval as a hosted tool that handles chunking, embedding, storage and search.
| Service | What it handles | Price (29 November 2026) |
|---|---|---|
| OpenAI file search (Responses API) | Vector stores with semantic and keyword search, citations, metadata filters | Storage free up to 1 GB, then $0.10 per GB per day; $2.50 per 1,000 tool calls |
| Gemini API File Search | Chunking, embeddings, search and citations inside the Gemini API | Storage and query-time embeddings free; indexing $0.15 per million tokens with gemini-embedding-001, $0.20 with Gemini Embedding 2 |
| Amazon Bedrock Managed Knowledge Base | Connectors for S3, SharePoint, Confluence, Google Drive, OneDrive and a web crawler; hybrid search, reranking, document-level permissions | Check AWS's Bedrock pricing page |
| Foundry IQ (Azure AI Search) | Indexing, hybrid search, semantic ranking, agentic retrieval, document-level security trimming | Check Azure's pricing page |
On every service, the retrieved passages also count as input tokens, so you pay the model's normal rate for whatever text retrieval adds to each prompt. Gemini's File Search takes files up to 100 MB, and OpenAI's vector stores accept files up to 512 MB.
To build it yourself, the minimum is an embedding model, a vector index such as pgvector and a chat model. That route gives you full control over chunking, ranking and permissions, in exchange for running it all.
Does RAG stop hallucinations?
No. It reduces them, it doesn't remove them, and vendors have oversold it.
The clearest evidence comes from Stanford and Yale researchers who in 2024 tested RAG-based legal research tools from LexisNexis and Thomson Reuters, whose makers had marketed them as avoiding hallucinations. Across more than 200 legal questions, the paper found the tools hallucinated between 17% and 33% of the time: Lexis+ AI on more than one query in six, Westlaw's AI-Assisted Research on about a third. Stanford HAI's summary puts Westlaw above 34%, slightly higher than the paper's abstract. Lexis+ AI was the most accurate, answering 65% of questions correctly, and the legal tools all made fewer errors than general-purpose GPT-4.
The researchers named problems that apply well beyond law:
- Retrieval misses. If search returns the wrong passages, the model writes a confident answer from the wrong material.
- Sources that don't apply. A retrieved passage can be real but irrelevant, outdated or about a different situation.
- Going along with the user. Models tend to accept a false premise in the question instead of pushing back.
The practical fix is to measure the two halves separately. Open-source evaluation tools such as Ragas score context recall, how much of the information the answer needs was actually retrieved, and faithfulness, the share of the answer's claims that the retrieved text supports, on a scale of 0 to 1. A low recall score points at your search. A low faithfulness score points at the model.
Is RAG safe? The security risks
RAG feeds a model text it didn't write and you may never have read. That opens up attacks a plain chatbot doesn't face.
- Indirect prompt injection. A 2023 paper by Kai Greshake and colleagues showed that attackers can plant instructions in content an app is likely to retrieve, such as a web page or a shared document, and the model may follow them. Retrieval blurs the line between data and instructions.
- Poisoned documents. OWASP's 2025 Top 10 for LLM applications lists "Vector and Embedding Weaknesses" as a risk of its own. One of its example scenarios is a resume with hidden white-on-white text telling a hiring assistant to recommend the candidate.
- Small attacks, big effects. The PoisonedRAG paper, presented at USENIX Security 2025, reported a 90% attack success rate after injecting five malicious texts per target question into a knowledge base of millions. The authors found the existing defenses they tried weren't enough.
- Permission leaks. If the index ignores who can see what, one user's question can pull up another team's files, a risk OWASP flags for shared vector databases. OWASP also warns that much of the original text can sometimes be recovered from stored vectors, so treat embeddings as sensitive as the documents.
The defenses are mostly discipline. Index only sources you trust and check documents for hidden text before they go in. Use permission-aware retrieval, which Foundry IQ and Bedrock's managed knowledge bases both offer. Log what gets retrieved, and keep a human approval step before an agent acts on what it found.
Frequently asked questions
What does RAG stand for in AI?
RAG stands for retrieval-augmented generation. The name comes from a 2020 paper by Patrick Lewis and colleagues at Facebook AI Research, University College London and New York University.
Does RAG stop AI hallucinations?
No. It cuts them by giving the model real sources to work from, but a Stanford-led study of RAG-based legal research tools still found hallucination rates between 17% and 33%. Check the citations on anything that matters.
Is RAG the same as fine-tuning?
No. Fine-tuning changes the model's weights and suits style and behavior. RAG leaves the model alone and changes what it reads at question time, which makes it better for facts that change or are private.
Do you need a vector database for RAG?
You need some way to search, and a vector index is the most common choice. It doesn't have to be a separate product: pgvector adds vector search to Postgres, and hosted tools from OpenAI, Google and Amazon manage the index for you.
Is RAG still needed now that models take a million tokens?
Often, yes. Long context tends to be more accurate when everything fits, but studies find RAG far cheaper per question, and it's the practical option when documents outgrow the window, change constantly or need per-user permissions.
What is agentic RAG?
Agentic RAG gives the model a search tool and lets it decide when and what to look up. It can run several searches and refine its queries, instead of getting one fixed search before every answer.
Sources
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, arXiv
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020 proceedings
- What is retrieval-augmented generation, aka RAG?, NVIDIA Blog
- What is RAG?, AWS
- Comparing retrieval augmented generation and fine-tuning, AWS Prescriptive Guidance
- Introducing Contextual Retrieval, Anthropic
- RAG and generative AI, Foundry IQ (Azure AI Search), Microsoft Learn
- Hybrid search scoring (RRF), Foundry IQ (Azure AI Search), Microsoft Learn
- What is Foundry IQ?, Microsoft Learn
- GraphRAG: new tool for complex data discovery now on GitHub, Microsoft Research
- File search, OpenAI API docs
- Retrieval, OpenAI API docs
- API pricing, OpenAI
- Models, OpenAI API docs
- GPT-6.2 Astra model page, OpenAI API docs
- Introducing the File Search Tool in Gemini API, Google
- File Search, Gemini API docs
- Gemini Developer API pricing, Google
- Amazon Bedrock Managed Knowledge Base is now generally available, AWS
- Retrieve data and generate AI responses with Amazon Bedrock Knowledge Bases, AWS docs
- pgvector, GitHub
- Qdrant
- Milvus
- Models overview, Claude Platform docs
- Retrieval augmented generation (RAG) for projects, Claude Help Center
- Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach, arXiv
- The Token Tax of Epistemic Accuracy: Comparing RAG and Long-Context Architectures, arXiv
- Lost in the Middle: How Language Models Use Long Contexts, ACL Anthology
- Introducing ChatGPT search, OpenAI
- How does Perplexity work?, Perplexity Help Center
- NotebookLM is now Gemini Notebook, Google
- NotebookLM is now Gemini Notebook, Google Workspace Updates
- NotebookLM is now Gemini Notebook, Stony Brook University IT
- Use chat in Gemini Notebook, Google Help
- Chat with documents, LM Studio docs
- Hallucination-Free? Assessing the Reliability of Leading AI Legal Research Tools, arXiv
- AI on Trial: legal models hallucinate in 1 out of 6 (or more) benchmarking queries, Stanford HAI
- Not what you've signed up for: compromising real-world LLM-integrated applications with indirect prompt injection, arXiv
- LLM08:2025 Vector and Embedding Weaknesses, OWASP Gen AI Security Project
- PoisonedRAG: knowledge corruption attacks to retrieval-augmented generation of large language models, USENIX Security 2025
- Faithfulness, Ragas docs
- Context recall, Ragas docs
Was this helpful?
Thanks, noted. It helps decide what gets updated first.


