A RAG example shows that the plumbing works. Documents get indexed, the chunks relevant to a question get retrieved and pasted into the prompt, and the model answers from them. It does not prove that the pattern answers your questions correctly on your corpus, because a typical demo is judged on whether one question comes back with a clean answer. Treat a retrieval-augmented generation example as an integration blueprint. Any claim about how the system behaves belongs to an evaluation run against your own documents and the queries your users actually send.
That distinction shapes everything below: the pattern itself, the variants, what people build with it, and the design choices that quietly break it.
What Does a RAG Example Do, Step by Step?
Retrieval-augmented generation pairs a pretrained language model (parametric memory) with an external index of documents (non-parametric memory), which a neural retriever searches at inference time. Lewis et al. introduced RAG models of this kind in 2020. Hugging Face’s documentation gives the practical consequence: grounding generation in retrieved passages often makes answers more factual and lets you update the model’s knowledge by changing the index instead of retraining the model.
The sequence below combines LangChain’s and AWS’s descriptions of a RAG pipeline:
- Load. Source content is read into document objects.
- Split. Text splitters break large documents into chunks, since large chunks are harder to search and either overflow the model’s context window or waste tokens.
- Embed. An embedding model turns each chunk into a numeric vector that captures its meaning.
- Store. The chunks and their vectors go into a vector store; AWS describes this ingestion, with its cleaning, formatting and chunking, as a one-time upfront activity.
- Retrieve. At query time the question is embedded with the same model, and the top-k most similar chunks are pulled from the store by a similarity measure such as cosine similarity.
- Augment. An orchestrator adds the retrieved chunks to the prompt as context alongside the user’s question.
- Generate. The model produces an answer from a prompt that contains both the question and the retrieved data.
Steps one to four prepare the index once, upfront. Steps five to seven run each time a query is submitted.
What a Python RAG Example with LangChain or Hugging Face Wires Together
A Python RAG example is mostly glue between components you choose: a document loader, a text splitter, an embedding model, a vector store, a retriever, a prompt template and a generator model. LangChain’s evaluation tutorial builds the minimal version in three stages: chunk and index a few of Lilian Weng’s blog posts in a vector store, retrieve chunks for the user’s question, then pass the question and those chunks to an LLM. LangChain’s documentation Q&A example goes further, indexing part of docs.langchain.com, writing retrieved chunks to a filesystem and handing analysis to subagents so the orchestrating agent’s context stays clean.
On the Hugging Face side, the RAG documentation describes a RagRetriever wrapping a FAISS index, with the number of retrieved documents defaulting to five. The Hugging Face advanced RAG cookbook shows why that number is not free: five retrieved documents of 512 tokens each means the reader model needs a context length of at least 4k tokens.
One caveat the examples themselves raise deserves attention early. Retrieved text shares the context window with your system prompt, so a model may follow instructions embedded in a document, and LangChain states that no prompt or delimiter strategy fully prevents this indirect prompt injection.
What RAG Examples Look Like as an Architecture, from Indexing to Generation
Seen as architecture rather than code, a RAG system has four phases: pre-retrieval, retrieval, post-retrieval and generation, a structure one survey of retrieval-augmented text generation uses for both single-pass and multi-step systems.
Pre-retrieval covers indexing and the query. Indexing means preparing and segmenting text, then representing it as semantic vectors with a pretrained model. Query manipulation (rewriting, disambiguating) addresses ambiguous phrasing and vocabulary mismatch between the question and the documents.
Retrieval is the search itself. Lexical methods such as BM25 rank by term frequency and miss the meaning of a query, while dense embeddings capture semantics, and dense indexing methods rely on approximate nearest-neighbour search. Despite that, many published systems still rely on BM25 for its efficiency.
Post-retrieval refines what came back. Filtering removes irrelevant or low-quality documents, and re-ranking orders the remainder by how much each is likely to help the answer. The Hugging Face cookbook recommends retrieving more documents than you need and re-ranking them with a cross-encoder such as ColBERTv2 before keeping the top few.
Generation usually concatenates the question with the retrieved content and passes it to the LLM, which has to stay faithful to the sources while still writing a coherent answer.
A production design also needs guardrails that check the query, the retrieved context and the response for accuracy and hallucination, and an index that is refreshed on a schedule, since an index that goes stale produces outdated answers.
What Are the Main Types or Variants of RAG, and When Would an Application Use Each One?
The Gao et al. survey groups RAG into three development paradigms: Naive RAG, Advanced RAG and Modular RAG. Databricks describes RAG moving toward hybrid architectures that combine it with tools, structured databases and function-calling agents. The same four-phase survey also names five retrieval strategies, each suited to different application needs.
| Retrieval strategy | How it retrieves | Fits when |
|---|---|---|
| Basic (single-hop) | Once, in a linear pass through the four phases | Simple lookups where efficiency matters more than exploration |
| Iterative | In several steps, each informed by the previous results, sometimes tied to chain-of-thought reasoning | Multi-step questions such as research assistance |
| Recursive | Through hierarchical structures | Hierarchically organised information |
| Adaptive | On demand, when the model judges retrieval useful, as in Self-RAG | Dynamic environments that need flexibility |
| Conditional | Under predefined criteria | Applications with strict compliance or constraint requirements |
Self-RAG trains a model to decide when to retrieve and to critique the passages and its own output, in contrast to conventional RAG, which always retrieves a fixed number of documents and never revisits answer quality. Corrective RAG (CRAG) adds a lightweight evaluator that scores the retrieved documents and triggers different actions, including web search, when retrieval looks poor. Self-RAG reacts to conventional RAG retrieving a fixed number of passages whether or not they help; CRAG reacts to retrieval that returns poor or sub-optimal documents.
Retrieval can also be grounded in image data, as in visual RAG for retail computer vision.
Our judgement on choosing among these is simple. Start with the basic strategy, and move to iterative, adaptive or corrective designs only when an evaluation on your own queries shows the basic one failing in the way those designs address.
What RAG Examples Are Usually Built For
Databricks lists the common uses as customer support chatbots, internal knowledge search and search experiences that answer questions directly from company documents. LangChain’s own tutorial example is a documentation Q&A agent. Databricks notes that in these uses the data sources can be updated without retraining the model.
DoorDash’s support system is a production version of the support-assistant case. According to its case write-up in the ZenML LLMOps database, it summarises the conversation, retrieves similar historical cases and knowledge base articles, builds a templated prompt and generates a response. The same write-up reports that a guardrail layer checking groundedness, coherence and policy compliance cut hallucinations by 90% and severe compliance issues by 99%, and that the team still routes complex cases to human agents. The figure that matters is less the 90% than the architecture: the RAG pipeline was one of three components, next to a guardrail and an LLM judge.
Industrial uses look different again. Two of our pieces cover them: grounding inspection knowledge for LLMs on a production line and the RAG model architecture in a moderation triage pipeline.
Design Choices That Cause Irrelevant Context or Ungrounded Answers
The quality of retrieval is fundamental to any effective RAG system. When retrieval does not surface the relevant information, the LLM cannot compensate, however capable it is. The choices below are where that happens.
Chunk size. Barnett et al. (2024) put the trade-off plainly: chunks that are too small leave some questions unanswerable, and chunks that are too long add noise to the answers. The Hugging Face cookbook says the same in other words: too small truncates ideas, too large dilutes them. Chroma’s chunking evaluation found that the strategy has a significant effect on retrieval accuracy and efficiency, and that the default settings of some popular chunkers perform relatively poorly.
Chunks stripped of context. Anthropic points out that standard RAG removes context when it encodes chunks, so a chunk can lose the information that would have made it retrievable. In its experiments, prepending chunk-specific context before embedding and BM25 indexing cut the top-20 retrieval failure rate by 49%, and by 67% with re-ranking added.
Embedding model and retriever fit. The four-phase survey reports that retriever performance depends on how well its training data matches the target corpus: a retriever trained on PubMed logs did markedly better on PubMed, and simply combining more retrievers did not always help. A general-purpose embedding model in a tutorial says little about how it will rank your contracts or maintenance logs.
Semantic similarity mistaken for relevance. The RAGBench authors note that most retrieved documents are semantically related to the query, but that is not enough: the question is whether the context contains the specific information needed to answer. Cuconasu et al. found that high-scoring documents that do not contain the answer hurt the LLM’s accuracy. Yoran et al. analysed five open-domain question answering benchmarks and characterised the cases where adding retrieval reduces accuracy.
No path for “I don’t know”. When retrieval returns nothing relevant, models often answer anyway, which raises the risk of incorrect outputs. A demo built on questions its corpus can answer never exercises that path.
What Can a Working RAG Example Tell You About Feasibility, and What Does It Leave Unproven?
A working RAG example shows that the plumbing works: documents are retrieved, fed to the model and used in a grounded answer. It does not show that the pattern gets your task right on your corpus, and that gap is where most retrieval-augmented deployments quietly go wrong.
Testing a RAG system means testing its retrieval behaviour, not only the quality of its outputs. The authors of the Chunk Coverage paper show why per-question scores mislead: if a 100-chunk corpus is tested only by queries that retrieve the same three chunks, the test suite has exercised 3% of the corpus, however good each answer looked. Their metric has limits of its own (it measures what a test suite exercised, not whether retrieval was correct) and is most informative where the corpus is a necessary source of the answer.
Magesh and colleagues tested commercial legal research tools whose vendors described RAG as eliminating or avoiding hallucinations, and found that the tools from LexisNexis and Thomson Reuters each hallucinated between 17% and 33% of the time. Those tools did hallucinate less than GPT-4, which is the honest version of the claim: RAG reduces hallucination, it does not remove it. Barnett et al. (2024) concluded that validating a RAG system is only feasible during operation and that its robustness evolves rather than being designed in at the start. The same paper notes that RAG systems are hard to test because the question data often does not exist yet and has to be generated synthetically or gathered by piloting.
Seven Failure Points a Demo Will Not Show You
Barnett et al. name seven failure points to consider when designing a RAG system.
| Failure point | What happens | The open question for your evaluation |
|---|---|---|
| Missing content | The answer is not in the documents, and the system responds anyway instead of declining | Does it refuse on questions your corpus cannot answer? |
| Missed top-ranked documents | The answer exists but does not rank inside the top-k cut-off | Is k right for your document distribution? |
| Not in context | Retrieved documents with the answer are dropped during consolidation | Does consolidation keep what matters when many documents match? |
| Not extracted | The answer is in the context, but noise or contradictions stop the model extracting it | How does it handle conflicting versions of a policy? |
| Wrong format | The model ignores an instruction to answer as a table or list | Does output format hold across your query types? |
| Incorrect specificity | The answer is too general or too specific for the user’s need | Does it match what your users actually need from an answer? |
| Incomplete | Available information in the context is left out of the answer | Are multi-document questions answered fully? |
Data freshness and indirect prompt injection add two further risks to that list.
How Are Retrieval Relevance and Grounding Faithfulness Measured Separately from Infrastructure Sizing?
RAG evaluators each compare a different pair of artefacts. LangChain’s evaluation tutorial defines four checks: correctness (the answer against a reference answer), relevance (the answer against the question), groundedness (the answer against the retrieved documents) and retrieval relevance (the retrieved documents against the question). RAGBench’s TRACe framework draws the same line: relevance measures the retriever, while utilisation, adherence and completeness measure the generator.
RAGBench’s authors describe these metrics as explainable and actionable. RAGBench reads low utilisation together with low relevance as a greedy retriever, and low utilisation alone as a weak generator that is not using the context it was given. The legal study makes a sharper version of the point: an answer can be correct but improperly grounded, when retrieval was poor and the model happened to be right while citing a source that does not support it. A single “answer quality” score hides exactly that case.
The measurements also carry their own uncertainty. Where ground-truth annotations are absent, many RAG metrics rely on an LLM as judge, which adds subjectivity. The RAGBench authors report that even the best automated evaluator they tested still falls well short of ground truth, and DoorDash pairs its LLM judge with human review of sampled transcripts. RAGBench’s own component datasets contain between 1% and 20% hallucinated responses.
Infrastructure sizing is a separate line in the pack. Latency, throughput and context-length capacity measure whether the system can serve its load, not whether retrieved context is relevant or answers grounded. The same caution applies to model-level documentation, as we argue in our piece on what a model spec sheet actually tells you: a hardware score or a spec rating sizes the box, it does not test the task. TechnoLynx’s generative and agentic AI R&D work builds RAG into products, with evaluation through its Production AI Monitoring Harness.
Reading the Next RAG Demo You Are Shown
The useful question to ask of any RAG example is not “did it answer?” but “which of its parts have been tested on our documents, and which have only been shown to connect?” Chunking, the retriever, the number of documents retrieved and filtering each involve design choices that affect output quality.
FAQ
What Type of Database Is Used for RAG?
According to Databricks, RAG typically stores unstructured text as chunked embeddings in a vector database that supports similarity search. Anthropic found that combining embeddings with BM25 retrieves better than embeddings alone.
Is RAG Still Used Today?
The RAGBench authors describe RAG as a standard architectural pattern for adding domain-specific knowledge to LLM-powered chat applications.
What Is the Key Benefit of Using RAG in Industry Applications?
RAG grounds a model’s answers in an organisation’s own, current content without retraining the model, which reduces hallucinations and keeps responses up to date. Answers can also cite their sources, so people can check them.