1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

What Is RAG? Retrieval-Augmented Generation Explained With a Working Example

RAG lets an AI model answer from your own documents rather than from memory alone. Learn how the pipeline works, run a tiny version in plain Python, and see why real systems fail and how to test them.

9 min read
What is RAG? Retrieval-augmented generation explained with a working example

Key takeaways

  • RAG finds relevant information first, adds it to the prompt, and then asks the model to answer from it.
  • It is the usual way to connect a language model to private or frequently changing data.
  • Most quality problems start in retrieval and data preparation, not in the model.
  • RAG reduces made-up answers but does not eliminate them, so you need to test it.

Ask a general AI assistant about your company’s refund policy, and it can only guess. It has never seen your documents. RAG, short for retrieval-augmented generation, solves this by looking up the right information and handing it to the model along with the question.

This guide explains each stage in plain language, then builds a tiny version using only Python’s standard library. We ran that code on Python 3.13, and the scores shown come from that run. It uses no language model, so it demonstrates retrieval and prompt building, and we did not test the final answer step.

What is RAG?

Retrieval-augmented generation is a technique that combines a search step with a language model. When a question arrives, the system searches a knowledge source, adds the best results to the prompt, and asks the model to answer based on that material.

Think of an open-book exam. A closed-book student relies on memory and may confidently misremember. An open-book student can look up the right page first. RAG gives the model that book, and also lets it point to which page it used.

The problem RAG solves

A language model on its own has three limits for business use:

  • It does not know your private data. Your policies, tickets and contracts were not part of its training.
  • Its knowledge has a cutoff. It cannot know about a price you changed this morning.
  • It may invent answers. When unsure, it can produce something plausible yet false.

RAG addresses all three, and you do not have to retrain anything. Update a document, re-index it, and the very next answer can use it.

How RAG works, step by step

A RAG system has two pipelines. One prepares your data ahead of time, and the other runs for every question.

Indexing: preparing your data

  1. Load: collect content from PDFs, wikis, databases or tickets.
  2. Clean and chunk: remove junk, then split documents into small passages.
  3. Embed: convert each passage into a list of numbers, called an embedding, that captures its meaning.
  4. Store: save the embeddings in a searchable index, often a vector database.

Querying: answering a question

  1. Retrieve: embed the question and find the passages closest in meaning.
  2. Augment: insert those passages into the prompt.
  3. Generate: the model writes an answer using that context.

Retrieval does not have to use vectors. It can be a keyword search or even a SQL query, whichever finds the right information for your data.

A tiny working example

To see the moving parts clearly, here is a small retriever with no libraries. It represents text as word counts, a much simpler stand-in for real embeddings, and it scores similarity using the cosine measure.

import math, re
from collections import Counter

DOCS = {
    "refunds": "Refunds are paid within 7 days to the original payment method.",
    "shipping": "Standard shipping takes 3 to 5 working days across India.",
    "warranty": "All keyboards include a 2 year warranty against defects.",
}

def vectorize(text):
    return Counter(re.findall(r"[a-z0-9]+", text.lower()))

def similarity(a, b):
    dot = sum(a[word] * b[word] for word in a)
    size = math.sqrt(sum(v * v for v in a.values()))
    size *= math.sqrt(sum(v * v for v in b.values()))
    return dot / size if size else 0

def retrieve(question, k=1):
    q = vectorize(question)
    scored = [(similarity(q, vectorize(t)), name) for name, t in DOCS.items()]
    return sorted(scored, reverse=True)[:k]

def build_prompt(question):
    (score, name), = retrieve(question)
    return (
        "Answer using only the context. If it is not there, say you do not know.\n"
        f"Context: {DOCS[name]}\n"
        f"Question: {question}"
    )

Asking about refunds finds the right passage and builds this prompt:

print(retrieve("How many days until refunds are paid?"))
# [(0.4558..., 'refunds')]

print(build_prompt("How many days until refunds are paid?"))
# Answer using only the context. If it is not there, say you do not know.
# Context: Refunds are paid within 7 days to the original payment method.
# Question: How many days until refunds are paid?

In a complete system, you would now send that prompt to a language model. The important detail is the instruction to admit when the answer is missing, which you can learn more about in our guide to prompt engineering.

What our example misses

Now try a question that means the same thing but uses different words:

print(retrieve("When can I get my money back?", k=3))
# [(0.0, 'warranty'), (0.0, 'shipping'), (0.0, 'refunds')]

Every score is zero, because the question shares no words with any document. “Money back” means refund to a human, but word counts cannot tell. This single output explains why real systems use embeddings, which are designed so that text with similar meaning ends up with similar numbers, even with no words in common.

But do not assume embeddings solve everything. They can struggle with exact terms such as product codes and error numbers, which keyword search handles very well. This is why many production systems use hybrid search, combining the two approaches.

Chunking: the step people underestimate

Documents are split into chunks because whole files are too long and imprecise to retrieve. The size you choose involves a real trade-off:

Chunk size Advantage Risk
Too small Precise matches Loses context, such as which product a rule applies to
Too large Keeps context Dilutes meaning, and uses more of the prompt
Split by structure Respects headings and sections Needs cleaner source documents

A few hundred words with some overlap between chunks is a common starting point, but treat that as a first guess to test. Split along natural boundaries, such as headings, when you can. And attach metadata, like the document title, date and department, so you can filter results and cite sources.

Improving retrieval

When answers are poor, these are the upgrades most worth trying, roughly in this order:

  • Clean the data. Remove outdated and duplicate documents first. No algorithm fixes contradictory sources.
  • Use hybrid search. Combine meaning-based and keyword results.
  • Add a re-ranker. Fetch more candidates, then use a specialised model to reorder them by relevance.
  • Filter by metadata. Restrict results by product, region or date before searching.
  • Rewrite the query. Turn a vague follow-up like “what about the second one?” into a complete question.

Tip: Before blaming the model, look at what retrieval actually returned. If the right passage was not in the context, no model could have answered correctly from it.

RAG vs fine-tuning

Question RAG Fine-tuning
What does it add? Knowledge at question time Trained behaviour or style
Updating information Re-index the document Train again
Can it cite sources? Yes Not reliably
Best for Facts that change Consistent format or tone

They are not mutually exclusive. Our comparison of RAG vs fine-tuning vs prompt engineering covers how to choose in more depth.

How to test a RAG system

RAG is software, and it needs tests like any other software. Create a set of real questions along with the passages and answers you expect, then measure the two stages separately:

Stage Question to ask Common name
Retrieval Did we fetch the right passage? Context recall
Retrieval How much of what we fetched was useful? Context precision
Generation Is the answer supported by the context? Faithfulness
Generation Does it actually answer the question? Answer relevance

Include awkward cases too: questions with no answer in your data, questions that use different wording and questions with conflicting sources. Rerun this set whenever you change chunking, models or prompts, just like a regression suite. Our pytest tutorial shows how to run many inputs through a single test.

Why RAG systems fail

  • The answer is not in the data. The model may still attempt one, so tell it how to decline.
  • The right chunk was not retrieved. This is often a chunking or search problem.
  • Too much context. Irrelevant passages can distract the model and raise costs.
  • Stale documents. An old policy can be retrieved as confidently as the current one.
  • Tables and PDFs parsed badly. If extraction scrambles the text, retrieval never recovers.
  • Testing only with demo questions. Real users phrase things very differently.

Security and permissions

RAG brings two risks that are easy to miss. First, access control: if the index holds HR files, a junior employee’s question must not retrieve them. Apply each user’s permissions during retrieval, because instructing the model to keep secrets is not a reliable safeguard.

Second, prompt injection. A retrieved web page or document could contain text such as “ignore your instructions”. Treat retrieved content as untrusted data, limit what actions the model can take and require a human to approve sensitive ones.

Final thoughts

RAG is a simple idea with plenty of practical detail: find the right information, and then ask the model to use it. Start with a small, clean set of documents and around twenty real questions. Get retrieval working well before you add complexity, because a modest pipeline with good data usually beats a sophisticated one with bad data.

Frequently asked questions

What does RAG stand for in AI?

RAG stands for retrieval-augmented generation. A system retrieves relevant information, adds it to the prompt, and the model generates an answer from it.

Does RAG stop AI hallucinations?

It reduces them by giving the model real sources, but it does not remove them. A model can still misread context, so test answers and show citations.

Do I need a vector database for RAG?

Not always. Small projects can use an in-memory index, keyword search or SQL. Vector databases help with large collections and meaning-based search.

What is the difference between RAG and fine-tuning?

RAG supplies information at question time, so updates are quick. Fine-tuning trains a model to change its behaviour or style, and it is less suited to changing facts.

What is an embedding?

An embedding is a list of numbers representing the meaning of text. Passages with similar meanings have similar numbers, which makes meaning-based search possible.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →