AI Agent Assurance for Your Agent Deployments
Agent Assurance Tests How Your Agent Actually Behaves across Workflows, Tools, and Actions to Catch Failures and Vulnerabilities.
npm install -g @testmuai/rook@latest
What Is RAG in AI? Retrieval-Augmented Generation, Step by Step
What does RAG mean in AI? Retrieval-augmented generation explained: the pipeline, a working retriever, RAG vs fine-tuning and long context, and where it fails.
OVERVIEW
RAG in AI means retrieval-augmented generation. Before a language model answers, the system retrieves passages from an outside source, such as a company's documents or a search index, and the model writes its answer from them. The term was coined in a 2020 paper by Patrick Lewis and colleagues, Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.
The ClashEval benchmark (Wu, Wu and Zou, 2024) gave six top-performing LLMs, GPT-4o among them, over 1,200 questions across six domains such as drug dosages and Olympic records. The models adopted incorrect retrieved content, overriding their own correct prior knowledge, over 60% of the time.
A RAG system can fail at retrieval, when the text holding the answer never reaches the model, or at generation, when the model trusts retrieved text it should not.
Overview
RAG, short for retrieval-augmented generation, is a method in which an AI system searches an external collection of documents for passages related to a question. It adds the best matches to the prompt and has a language model write the answer from them. It lets a model use current or private information without retraining.
How Does RAG Work?
- RAG indexing: Source documents are cleaned, split into chunks, encoded as vectors by an embedding model and stored in a vector database. Indexing runs before any question arrives and again whenever the documents change.
- RAG retriever: At question time, the retriever returns the top K stored chunks most similar to the question. A chunk ranked below the top K cutoff never reaches the language model, so the answer cannot use it or cite it.
- Hybrid retrieval: Keyword search such as BM25 and embedding search find different matches, so a RAG system can run both. BM25 finds an exact string such as an error code that an embedding model can miss.
- Augmented prompt: The retrieved chunks are added to the prompt beside the question and an instruction, such as answer only from these sources and cite the source id. Every top K chunk enters the prompt, relevant or not.
- RAG generator: The language model writes the answer from the augmented prompt and, when instructed, cites the source ids it used. Hallucination-free: no. The model can still state things the retrieved chunks do not support.
- RAG knowledge updates: Retraining required: no. Replacing the indexed documents changes what a RAG system can answer, as the 2020 paper that named RAG showed by swapping a 2016 index for a 2018 one.
- RAG agents that act: An AI agent that retrieves a policy and then changes a record needs the action checked as well as the answer, because a correct answer does not prove a correct action.
What Is RAG in AI?
RAG in AI is an architecture for language model applications in which the answer is conditioned on chunks of text fetched at question time, not only on what the model learned in training. The fetched chunks travel with the question inside the prompt, so the model can use facts that were never in its training data, such as a policy published last week.
The 2020 paper named the gap it was closing: pre-trained models "cannot easily expand or revise their memory, can't straightforwardly provide insight into their predictions, and may produce hallucinations." Its abstract adds that "providing provenance for their decisions and updating their world knowledge remain open research problems." Retrieval answers both in part: change the documents to update what the system knows, and show the retrieved chunks to give provenance.
Typical deployments are a help-center AI chatbot answering from support articles and an internal assistant over engineering documentation, where documents change faster than anyone would retrain a model.
What Does RAG Mean?
Each letter names a stage. Retrieval finds chunks related to the question, augmented means those chunks are added to the model's input, and generation is the model writing the answer from that input.
RAG names an architecture rather than any one product or model. Any system that wires a retriever, such as a vector database, keyword search or web search, to a generator is RAG.
Parametric and Non-Parametric Memory in RAG
Lewis et al. described RAG models as ones that "combine pre-trained parametric and non-parametric memory for language generation." In their models the parametric memory was a pre-trained sequence-to-sequence model, knowledge held in its weights, and the non-parametric memory was "a dense vector index of Wikipedia, accessed with a pre-trained neural retriever."
The practical split: to change what the weights know you train again, while to change what the index knows you replace documents. Agents keep other kinds of memory too, across steps and sessions, which AI agent memory covers.
Where Did Retrieval-Augmented Generation Come From?
Retrieval-augmented generation comes from the Lewis et al. paper, first posted on 22 May 2020 by researchers at Facebook AI Research, University College London and New York University and accepted at NeurIPS 2020. It proposed "a general-purpose fine-tuning recipe" rather than a single model, and the figures below are historical results from that paper.
- Retriever - Dense Passage Retriever (DPR) fetched passages from the Wikipedia index, conditioned on the input question.
- Generator - BART, a sequence-to-sequence model, wrote the output; in the paper's words, to combine the input with the retrieved content "we simply concatenate them."
- Size versus recall - On Natural Questions, RAG-Sequence scored 44.5 exact match with 626M trainable parameters, while T5-large, a parametric-only model with 770M parameters, scored 28.9.
A smaller model with an index beat a larger model relying on its weights alone, and that was the paper's case for the technique.
In an interview for NVIDIA's RAG explainer (first published in November 2023), lead author Patrick Lewis apologized for the unflattering acronym. He said: "We definitely would have put more thought into the name had we known our work would become so widespread."
How Does a RAG Pipeline Work, Step by Step?
The Gao et al. survey of RAG for large language models describes the basic flow as indexing, retrieval and generation, which it also calls a "Retrieve-Read" framework. Production pipelines split those stages into the seven steps below, and each step has its own failure.
Ingest and Clean the Sources
Per the survey, "Indexing starts with the cleaning and extraction of raw data in diverse formats like PDF, HTML, Word, and Markdown, which is then converted into a uniform plain text format." Extraction errors carry into every later step, so read a sample of the extracted text before indexing anything.
Keep each document's source, date and owner as metadata: citations, stale-index checks and access control all depend on them.
Chunk the Text
Documents are split into chunks, the units the retriever returns. The Gao et al. survey says "The most common method is to split the document into chunks on a fixed number of tokens (e.g., 100, 256, 512)." It states the trade-off plainly: larger chunks "can capture more context, but they also generate more noise, requiring longer processing time and higher costs," while smaller ones "may not fully convey the necessary context."
Whatever the size, a chunk can lose a fact that sat in the sentence before it, such as the name of the company a figure belongs to, a failure covered in its own section below.
Embed and Index the Chunks
"Chunks are then encoded into vector representations using an embedding model and stored in vector database," in the survey's words. An embedding places chunks with similar meaning close together, so a question about refunds can find a chunk about returns even when the words differ.
Comparing a query with every stored vector is too slow for large stores, so vector databases use approximate nearest neighbor indexes. A common one is Hierarchical Navigable Small World graphs (HNSW), which Malkov and Yashunin describe as allowing "a logarithmic complexity scaling."
Retrieve the Top Chunks
At question time, "The system prioritizes and retrieves the top K chunks that demonstrate the greatest similarity to the query." K is a setting you choose, and it caps how much of the index the model can ever see for one question.
The survey notes that "The original queries are not always optimal for LLM retrieval," which is why pipelines rewrite or expand queries before searching. It also recommends hybrid search, because "Sparse and dense embedding approaches capture different relevance features and can benefit from each other": keyword scoring finds exact strings, while embeddings find paraphrases.
Rerank the Retrieved Chunks
Reranking reorders the retrieved candidates before they enter the prompt. The survey lists reranking and context compressing as the main post-retrieval methods, and says reranking "reorders document chunks to highlight the most pertinent results first, effectively reducing the overall document pool."
A reranker cannot surface an answer chunk the first stage never returned, so measure first-stage recall before tuning it.
Augment the Prompt
The retrieved chunks are inserted into the prompt beside the question, usually with an instruction to answer only from them, to cite source ids and to say when the sources do not contain the answer. Label each chunk with its id so the model can cite it and you can trace an answer back.
Every chunk in the top K goes in, whether it helps or not, as the gift-card chunk in the next section's run shows.
Generate and Cite the Answer
The model writes the answer from the augmented prompt. An answer whose every claim traces to a supplied chunk has groundedness, and citations let a reader check it claim by claim.
Asking for citations does not guarantee them. The ALCE benchmark (Gao, Yen, Yu and Chen, EMNLP 2023) found that "on the ELI5 dataset, even the best models lack complete citation support 50% of the time." Verify that each cited chunk supports the sentence it is attached to.
What Does a RAG Retriever Return in a Toy TF-IDF Run?
A retriever returns a ranked list of chunks with scores, and the answer document is not always near the top. A stdlib-only Python script run on 2026-12-01 shows it: six invented help-center documents, a bag-of-words TF-IDF retriever with cosine similarity, no stemming and top-k set to 2.
Q3 was worded so its answer document uses different words (customs duties, international) from the question (import tax, abroad), a constructed illustration of vocabulary mismatch rather than a measurement. No model is called, so generation is not run.
| ID | Document text | Answer source for |
|---|---|---|
| D1 | Returns are accepted within 30 days of delivery. The refund goes to the original payment method. | None |
| D2 | Standard shipping takes 3 to 5 business days. Express shipping takes 1 to 2 business days. | Q1 |
| D3 | Electronics carry a one year warranty against manufacturing defects. Claims need the order number. | None |
| D4 | You can cancel an order until it ships. After it ships, return the order instead of cancelling it. | Q2 |
| D5 | Customs duties on an international order are collected from the recipient by the carrier. | Q3 |
| D6 | Gift cards never expire and cannot be exchanged for cash or used to pay shipping fees. | None |
The scoring core of the script, trimmed (the document list, the index builder and the printing are left out):
import math
import re
from collections import Counter
# STOP: a small stopword list (omitted here)
# idf per word: log((n + 1) / (df + 1)) + 1
def tokens(text):
words = re.findall(r"[a-z0-9]+", text.lower())
return [w for w in words if w not in STOP]
def weigh(words, idf):
tf = Counter(words)
total = len(words) or 1
return {w: (c / total) * idf.get(w, 0.0)
for w, c in tf.items()}
def cosine(a, b):
dot = sum(v * b.get(w, 0.0) for w, v in a.items())
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
def rank(question, idf, vecs):
q = weigh(tokens(question), idf)
scored = [(cosine(q, v), d)
for d, v in vecs.items()]
return sorted(scored, key=lambda s: (-s[0], s[1]))Under Python 3.14.6 on Windows, the run printed:
Toy TF-IDF retriever: 6 docs, top-k = 2
========================================
Q1: How long does express shipping take?
D2 score 0.412
D6 score 0.152
expected D2: rank 1, in top-2
Q2: Can I cancel my order after it ships?
D4 score 0.842
D5 score 0.120
expected D4: rank 1, in top-2
Q3: Do I pay import tax when my order ships abroad?
D4 score 0.629
D6 score 0.186
expected D5: rank 3, MISSED by top-2
========================================
Q3 full ranking (shared words with question):
D4 0.629 order, ships
D6 0.186 pay
D5 0.120 order
D3 0.090 order
D1 0.000 none
D2 0.000 none
========================================
Q3 with a 3-word synonym table added:
import = customs, tax = duties,
abroad = international
D5 score 0.584
D4 score 0.423
========================================
Prompt assembled for Q1 (generation not run):
Answer only from the sources below.
Cite the source id. If they do not
contain the answer, say so.
[D2] Standard shipping takes 3 to 5 business days...
[D6] Gift cards never expire and cannot be exchan...
Question: How long does express shipping take?- The miss - for Q3, the answer document D5 ranks third with a score of 0.120 and falls outside the top 2. It shares only the word "order" with the question, while D4, a cancellation policy, wins on "order" and "ships."
- The noise - for Q1, the right document D2 ranks first, but the gift-card document D6 also enters the prompt at 0.152, on the single shared word "shipping." The model now has an irrelevant chunk to ignore.
- The fix - a hand-written synonym table of three entries (import to customs, tax to duties, abroad to international) moves D5 to rank 1 with a score of 0.584.
A synonym table written for one question does not scale; production pipelines use query rewriting, embeddings that match meaning, and keyword search beside them for exact strings. Anthropic's contextual retrieval post (September 2024) gives the case for keeping both: a search for "Error code TS-999" can pull general error-code content from an embedding model while BM25 finds the exact "TS-999" match.
Its contextual retrieval method prepends chunk-specific explanatory context to each chunk before embedding it and before building the BM25 index. The same post measured retrieval failure as 1 minus recall@20, the share of relevant documents not retrieved in the top 20 chunks. It reported how each change lowered that rate from 5.7%:
| Retrieval setup (Anthropic, 2024) | Top-20 failure rate | Reduction |
|---|---|---|
| Standard embeddings (Gemini Text 004) | 5.7% | Baseline |
| Contextual Embeddings | 3.7% | 35% |
| Contextual Embeddings plus Contextual BM25 | 2.9% | 49% |
| Both, then a reranker | 1.9% | 67% |
These are Anthropic's figures from its own experiments, not an independent benchmark. They are averages across four knowledge domains (codebases, fiction, arXiv papers and science papers) with Gemini Text 004 embeddings and the top 20 chunks, and the reranker was Cohere's.
How Is RAG Different From Fine-Tuning and Long Context?
RAG keeps knowledge in an external index searched for each question, fine-tuning moves knowledge or behavior into the model's weights, and long context puts the whole source into the prompt of every call. The table compares them using only what the cited papers and Anthropic's post state.
| Aspect | RAG | Fine-tuning | Long context |
|---|---|---|---|
| Where knowledge lives | An external index, outside the model | The model's weights | The prompt, sent again on every call |
| How you update it | Replace or re-index documents; Lewis et al. swapped a whole index | Train again (the Gao et al. survey: "requiring retraining for updates") | Edit the text you send |
| Strength the sources name | Real-time knowledge updates with high interpretability (Gao et al.) | Deep customization of the model's behavior and style (Gao et al.) | Higher average performance than RAG when resourced sufficiently (Li et al.) |
| Cost the sources name | Higher latency than fine-tuning (Gao et al.), significantly lower cost than long context (Li et al.) | A training run for each knowledge update | Higher cost per query than RAG (Li et al.) |
| Fits when | Knowledge changes often or is too large for one prompt | The gap is how the model behaves or writes | The source is under 200,000 tokens, about 500 pages (Anthropic, September 2024) |
The Gao et al. survey says RAG and fine-tuning "are not mutually exclusive and can complement each other." Balaguer et al.'s agriculture case study (January 2024) measured it: fine-tuning raised accuracy by over 6 percentage points, and RAG added 5 more on top, cumulatively.
Li et al. (Google DeepMind and the University of Michigan, 2024) compared RAG with long-context (LC) models and found that "when resourced sufficiently, LC consistently outperforms RAG in terms of average performance." Yet the two produced identical predictions for over 60% of queries at very different costs. If your corpus fits the model's context window at a per-call price you accept, try that before building an index.
Li et al. also proposed Self-Route, which routes each query to RAG or to the long-context model based on the model's self-reflection. It kept performance comparable to long context while cutting cost by 65% for Gemini-1.5-Pro and 39% for GPT-4O.
What Are the Main Types of RAG in AI?
The Gao et al. survey sorts RAG systems into three generations: naive, advanced and modular. GraphRAG changes what gets retrieved, and agentic RAG changes who decides when to retrieve.
| Type | What it does (Gao et al.) | What it addresses |
|---|---|---|
| Naive RAG | Indexing, retrieval and generation in one pass, the "Retrieve-Read" framework | The baseline; its retrieval "often struggles with precision and recall" |
| Advanced RAG | Adds steps before retrieval (query rewriting, expansion) and after it (reranking, context compressing) | Misaligned or irrelevant chunks and missed information from naive retrieval |
| Modular RAG | Goes beyond the fixed sequence of the first two, "offering enhanced adaptability and versatility" | Pipelines that need different steps for different questions |
GraphRAG
GraphRAG is Microsoft Research's technique for "richly understanding text datasets by combining text extraction, network analysis, and LLM prompting and summarization into a single end-to-end system." It targets a question type chunk retrieval handles badly: the GraphRAG paper says "RAG fails on global questions directed at an entire text corpus, such as What are the main themes in the dataset?"
An LLM builds the index in two stages: it derives an entity knowledge graph from the documents, then pregenerates summaries for each group of closely related entities. Building the graph costs LLM calls over the whole corpus, so reserve it for corpora where people ask global questions.
Using GPT-4, the GraphRAG paper's global approaches won between 72% and 83% of comprehensiveness comparisons against conventional vector RAG on podcast transcripts and between 72% and 80% on news articles. Both ranges had p below 0.001.
Agent-Driven Retrieval
In agentic RAG, retrieval becomes a tool that an agent calls when it decides it needs information, and the agent can rewrite the query, search again or check another source before answering. A ReAct agent shows the shape: each search is one action in a loop of reasoning, acting and reading the result. It targets multi-step questions that single-pass retrieval misses, at the price of more model calls.
Where Does RAG Fail?
RAG fails when one pipeline step hands the next the wrong input. Each failure below names the primary source that documents it.
The Right Chunk Is Not Retrieved
Vocabulary mismatch is one cause, as Q3 showed above. Li et al. analyzed the examples RAG could not answer (those its routing step marked unanswerable) and summarized four typical failure reasons:
- Multi-step questions - the results of earlier steps are needed to retrieve information for later steps, which single-shot retrieval cannot do.
- General questions - a query such as what a group thinks about a topic, for which the retriever struggles to formulate a good search.
- Long, complex questions - the query is "challenging for the retriever to understand."
- Implicit questions - the answer demands "a thorough understanding of the entire context," not one passage.
A Chunk Loses Its Context
Anthropic's post gives the textbook case: a chunk that reads "The company's revenue grew by 3% over the previous quarter" does not say which company or which quarter. Per the post, that makes it "difficult to retrieve the right information or use the information effectively." Anthropic presents contextual retrieval as its fix for this problem.
The Index Is Stale
A RAG system is only as current as its last re-index. The 2020 Lewis et al. paper tested this with 82 world leaders who changed between 2016 and 2018 (a historical result). RAG answered 70% correctly with the 2016 index for 2016 leaders and 68% with the 2018 index for 2018 leaders, but only 12% and 4% with the index and the year mismatched.
The authors' reading was that "we can update RAG's world knowledge by simply replacing its non-parametric memory." The flip side is that a changed document stays wrong in answers until it is re-indexed, so track each source's date.
Sources Conflict or Are Wrong
When a retrieved chunk is wrong, models tend to follow it. ClashEval also found that "the less confident a model is in its initial response (via measuring token probabilities), the more likely it is to adopt the information in the retrieved content." Two versions of the same policy in one index produce the same problem, so retire superseded documents rather than leaving both searchable.
Because models follow what they retrieve, a slanted document can also carry its bias into answers, which is one route by which LLM bias enters an application.
The Model Ignores the Context
The opposite failure is a model that answers from its own weights or invents content. The Gao et al. survey lists the risk that the model "produces content not supported by the retrieved context," and the general causes are covered in AI hallucination. A model can also drop a retrieved fact when the user insists otherwise, a failure known as AI sycophancy.
The original paper saw an extreme form in preliminary experiments on tasks such as story generation (a historical result from its appendix). There the retriever would "collapse" and return the same documents regardless of input, after which "the generator would learn to ignore the documents." A pipeline whose answers do not change when you swap the retrieved chunks has the same symptom.
The Vector Store Leaks Across Users
OWASP's LLM08:2025 Vector and Embedding Weaknesses warns that "In multi-tenant environments where multiple classes of users or applications share the same vector database, there's a risk of context leakage between users or queries." Its prevention advice is to "Implement fine-grained access controls and permission-aware vector and embedding stores," which means filtering by the reader's permissions at retrieval time, not after generation.
A related risk is a planted document written to be retrieved and obeyed, covered under RAG poisoning.
How Do Teams Evaluate a RAG System?
Teams score retrieval and the answer separately, because a correct answer can hide a lucky retrieval and a wrong one can come from a perfect retrieval. Retrieval is scored against a labelled set of questions and their answer documents, with measures such as the recall@20 that Anthropic used. The answer is scored on whether it is correct and supported by the chunks it cites.
The formulas, with a worked example, are in RAG evaluation metrics, and building test sets, component and end-to-end checks and CI gates is covered in RAG testing. For labelled questions to start from, see datasets for training and evaluating RAG models, and for frameworks that automate the scoring, RAG evaluation tools. Word-overlap scores such as ROUGE compare an answer with a reference answer, and an answer with a wrong fact can still score well on them.
How Do You Test an Agent That Retrieves and Then Acts?
Test the action against the system it changed, not the answer alone. A support agent that answers from a knowledge base and then opens a case or changes an order can quote the right policy and still change the wrong order. Its own summary of what it did is not evidence.
Agent Assurance is TestMu AI's product for agents that act through tools, files and APIs. During exploration it goes through your PRD, policy documents and knowledge base. It extracts what the agent should answer, the policies it must follow, the domain facts and the boundaries, so the rules it checks come from your own documents.
That matters when retrieval fails. If the retriever misses the policy chunk, as the toy run missed D5 for Q3, the agent may still act on a guess. A criterion built from your policy documents still applies to that action, because it comes from exploration, not from what the retriever returned.
- Checks matched to each criterion - a model judge grades a criterion over the exchange (
check: llm_judge) only where one is needed. Other criteria use a read of the system the agent changed (check: mcp_probe) or a rule such as a regex. Every check runs against evidence, with records confirmed by a read-only query through a tool you approve. - Hallucination scenarios - the adversarial categories include
hallucinationalongside prompt injection, data exfiltration and policy violation, so invented facts are probed on purpose. - Any reachable agent - the agent is invoked for real, reached as an HTTP endpoint, an MCP tool or a command through a profile with reviewable hook scripts. Anything it does not expose is reported as Unable to Verify, not as a failure.
Most eval and observability tools score what your agent said and recorded. Agent Assurance checks what the run changed, and reports what it could not verify.
If your RAG system is an agent judged on what it says, Agent Testing fits better: it tests chat, voice, phone, video and image agents. For chat and voice agents it scores Hallucination Detection, which flags false, fabricated or unsupported information.
The npm package needs Node.js 20 or newer:
npm install -g @testmuai/rook@latestOn macOS and Linux, Homebrew and the shell installer need no Node. The skill installer, npx @testmuai/rook-skill, needs Node.js 22 or newer. A 7-day free trial carries 10,000 credits; see Agent Assurance pricing for what follows it.
What Should You Build First in a RAG System?
When you build RAG in AI applications, start with retrieval: write real questions your users ask, mark the document that answers each one, and record where it ranks in your retriever's output. Every question whose answer sits outside your top K is a failure no model can fix, as Q3 showed.
If the pipeline feeds an agent that acts, the Agent Assurance docs show how to check its actions as well.
npm install -g @testmuai/rook@latest, or for a full walkthrough of the product.Was this helpful?
Authors

Samyak Goyal
Author · 05 hubs
Samyak Goyal is a Senior Member of Technical Staff at TestMu AI engineering Kane CLI, the command-line tool that runs browser automation from the terminal, where a flow described in natural language executes in a real Chrome browser and returns pass or fail with shareable proof. He is a backend engineer with 4+ years of experience, previously an SDE at Innovaccer, where he built APIs, introduced Kafka, and cut deployment from weeks to hours. Samyak also builds multi-agent systems, skill-orchestration frameworks, and a personal copilot that indexes 200+ microservice repositories.

Sirajuddin Khan
Reviewer
Sirajuddin Khan is Vice President of Product Management at TestMu AI, where he drives the company's agentic AI product strategy, building a suite of autonomous agents that includes Agentic Browsers and Agentic Visual Testing and shifting the unit of work from test execution to autonomous outcomes. One of the company's earliest product leaders, he has owned the roadmap for the high-performance execution cloud and grew the cross-browser testing products from early adoption to market leadership. He brings over a decade of experience across SaaS, B2B, and eCommerce, with earlier product roles at Wydr and ShopClues, where his catalog and search work cut delivery SLAs and lifted seller activity. Sirajuddin holds an MBA in Information Technology from Sikkim Manipal University and a B.Tech in Computer Science Engineering from Maharshi Dayanand University.
RAG in AI FAQs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests


