On this page · 13 sections

The help center from the last article (opens in a new tab) grew. Eight short articles became fifty, the way help centers do: free trials, invoices, single sign-on, webhooks, recurring tasks. Nobody touched the application. It still sent the whole help center with every question, and it had served customers well.

Then a customer asked: “How many members can I have on the Basic plan?”

The help center says five. The model said:

{"answered": false, "answer": "The Basic plan supports up to 2 members.", "source_ids": []}

The application did its job. The model had marked its own answer as unanswered, so the customer got the decline message instead of a wrong number. But the help center had the answer. Across 24 questions that the help center answers, the reply contained the expected fact for 3.

There was no error. The model server’s log had one warning:

msg="truncating input prompt" limit=2050 prompt=4264 keep=4 new=2050

With the whole help center, the prompt was 4,264 tokens. The server kept 2,050 of them in total (new=2050, including the four tokens it keeps from the start), and reported 2,050 prompt tokens in its response. The instructions and the first 23 articles never reached the model, including the one about members.

This is the problem retrieval-augmented generation, or RAG, solves: the knowledge an application needs is bigger than what you can, or should, send to the model with every question. This article builds the smallest RAG version of the same assistant, runs it against sending everything, and looks at what it fixes, what it costs, and what still breaks.

Try to Understand It This Way

Imagine a new support agent on their first day. There’s a 500-page binder with everything about the product.

You have three options. You could send them on a training course built from the binder; it changes how they work, but it’s slow, has to be repeated whenever the binder changes, and they’ll still misremember details. You could read the whole binder aloud before every call; that works while the binder is ten pages, and becomes absurd at 500. Or you could give them a good index: when a customer calls, someone pulls the three pages that best match the question and puts them on the desk. The agent answers from those pages, and says “I don’t know” when they don’t help.

The third option is the basic RAG pattern. The binder is your knowledge base. The person pulling pages is retrieval. The agent answering from the pages on the desk is generation. The training course is closer to fine-tuning, the subject of the next article: it changes the model’s behavior and weights, but it isn’t a substitute for a searchable source of truth when facts change.

The analogy also shows where it goes wrong. The wrong pages can be pulled. The agent can misread the right page. And when the answer isn’t in the binder at all, the pages on the desk are still the closest pages, and a helpful agent may try to answer from them anyway. All three happened in the experiment below.

How RAG Works

The term comes from a 2020 paper by Lewis et al., which described models that “combine pre-trained parametric and non-parametric memory for language generation”: what the model learned in training, plus an external index it can search. The paper fine-tuned its retriever and generator together. In applications today, RAG usually names the broader pattern with off-the-shelf models, which is what this demo does.

The pattern has two phases.

Index time, once, and again whenever the documents change:

50 help-center articles ──► embedding model ──► 50 vectors ──► saved index

Query time, on every question:

question ──► same embedding model ──► question vector
         ──► compare with the 50 article vectors ──► the k most similar articles
         ──► prompt: instructions + those k articles + the question
         ──► chat model ──► checks ──► reply

The embedding step works as in “Embeddings Explained: The Building Block Behind Semantic Search (opens in a new tab)”: text becomes a vector, and texts with similar meaning get similar vectors. With 50 articles, the demo compares the question against every vector directly, which is cheap at this size and exact. A vector database isn’t what makes something RAG; it’s how retrieval scales. At millions of documents, you may use an approximate-nearest-neighbor index, often provided by a vector database like the ones in “Vector Databases Explained: What Problem Are They Solving? (opens in a new tab)”, along with its other jobs: storing the index, updating single documents, and filtering by metadata.

In code, the application from Article #11 changes in one place: step 2, building the context. Simplified from the demo (illustrative: the demo’s version also checks vector dimensions, breaks ties in a fixed order, and turns a failed embedding call into the same 503 as a failed model call):

def retrieve(question, k):
    query = embed(["search_query: " + question])[0]
    scored = [(cosine(query, entry["vector"]), entry["id"]) for entry in index]
    scored.sort(key=lambda s: -s[0])
    return [article_id for _, article_id in scored[:k]]

# 2. Build the context: only the retrieved articles, not the whole help center
context = [articles[i] for i in retrieve(question, k=3)]

The rest of the application stays as it was: the versioned prompt, the JSON schema, the output checks, the decline message, and the log record. The prompt’s instructions are word for word the same; only the articles inside it change. One small addition: the JSON schema only allows the model to cite the articles it was actually given.

The search_query: prefix isn’t decoration. The embedding model used here, nomic-embed-text, was trained with task prefixes, and its model card says “the text prompt must include a task instruction prefix”. Documents get search_document: at index time, questions get search_query: . The demo’s index records the model and the prefixes it was built with, and refuses to run with different settings, or with articles that changed since indexing. A stale index can cause recently changed content to be missed or ranked incorrectly; if the index also stores the document text, it can serve stale content too.

The Experiment

The demo, 01-basic-rag, is the first example in the rag-engineering repository. It sends 30 questions through the same application four ways:

all, default context   every article; Ollama chooses the context length
all, 8K context        every article, with a context large enough to hold them (8,192 tokens)
rag, top 1             only the most similar article
rag, top 3             only the 3 most similar articles

24 of the questions are answered by the help center. Each is labeled with the article that answers it, so retrieval can be measured on its own. Six are questions the help center doesn’t answer, like “Do you have a phone number I can call?” and “Is there a desktop app for Windows?”. For those, declining is the right behavior. The product and the help center are fictional; the questions are test inputs, not real customer traffic.

Implementation note: the exact setup
Runtime:      Ollama 0.40.16, /api/chat and /api/embed, Apple M4 Pro (24 GB), AC power
Chat model:   llama3.2:3b (a80c4f17acd5, Q4_K_M)
Embeddings:   nomic-embed-text (0a109f422b47), 768 dimensions,
              prefixes "search_query: " and "search_document: "
Retrieval:    cosine similarity against all 50 article vectors; one article = one chunk
Generation:   temperature 0, seed 1, at most 300 output tokens, JSON schema in "format";
              the chat model unloaded before each mode
Context:      default (Ollama chose 4,096 tokens), or num_ctx 8192
Questions:    24 answerable, 6 not in the help center
Runs:         twice in Python, twice in JavaScript, 2026-11-12

All four runs produced identical replies, retrieval scores, and token counts. Only request ids and latencies differed.

“Key fact” is a pattern check on the reply the customer saw (for example, “5” for the members question). It measures whether the expected fact appeared, not whether the answer was correct.

The sequence: each run sends the 30 questions through all four modes, so one run produces 120 replies. After the first run (Python), I read all 120 by hand. That changed the patterns for three questions: one pattern had passed a wrong answer (the Trash example below), and two had failed correct answers. The first run’s saved replies were re-graded with the fixed patterns, and the three later runs used them from the start. The replies of all four runs were then compared in code and were identical, so the hand reading covers the reported results; it’s also what found the wrong answers below that a pattern can’t see. The patterns were adjusted after seeing outputs, so treat them as checked against hand labels, not as rules fixed in advance.

The results:

                          answerable questions (24)                 not in docs (6)
mode                      key fact   answered without it   declined      declined     prompt tokens (median)
all, default context         3               2                19          6/6               2,050
all, 8K context             18               1                 5          6/6               4,262
rag, top 1                  19               1                 4          2/6                 261
rag, top 3                  22               1                 1          3/6                 431

Three things stand out. Sending everything at the default context collapsed. With three retrieved articles, the expected key fact appeared in 22 of 24 answerable replies, compared with 18 of 24 when the whole help center fit in the prompt, and the median prompt was 431 tokens instead of 4,262 (RAG also makes one embedding call per question, which isn’t in that count). And RAG was worse at declining questions the help center doesn’t answer. Let’s take them in order.

What Happened When Everything Was Sent

The server log showed the same warning for all 30 questions in the default mode. Ollama’s documentation describes a default context length “based on VRAM”, 4k below 24 GiB; on this machine it chose 4,096 tokens, and the help center needed about 4,260.

By counting tokens for growing prefixes of the help center, the cut falls inside the 24th article. Apart from the first four tokens (keep=4), the beginning of the prompt was dropped: the application’s instructions (“Answer the customer’s question using only the help center articles below.”), the JSON contract described in words, and 23 articles, including plans, refunds, password resets, and members. What survived was the last 26 articles and the question. (Article #11 showed why those four kept tokens don’t help: they belong to the chat template, not to your prompt.)

Without its instructions, the model improvised. For questions about dropped articles, it invented: “up to 2 members”, “The Pro plan is $12.50/user/month”, “The password reset link is valid for 30 minutes”. Several replies repeated the same source id until they ran into the 300-token limit, leaving incomplete JSON.

Very few of those inventions reached a customer, and that’s worth noticing. The 19 declines fell into three separate groups, because the application checks in order and stops at the first failure: 7 weren’t valid JSON; 7 were marked unanswered by the model itself (most still had an answer written into the field, often an invented one); and 5 cited no article, which the application requires before it runs the value-presence check from “Why LLMs Hallucinate, and What Engineers Can Do About It (opens in a new tab)”. The layers from Article #11 kept the failure quiet for customers. They couldn’t make up for knowledge the model never received.

The fix that comes to mind first is a bigger context.

Is a Bigger Context Enough?

With an 8,192-token context, the whole help center fit, and 18 of 24 answerable questions got the key fact. That’s a real fix, and at this size it may be the right one.

It was also fast. Ollama’s prompt cache (see “How LLM Inference Works (opens in a new tab)”) kept the processed help center between requests: every question started with the same help center, and the server reused a median of 4,248 cached prompt tokens per question. The first request took 6.65 to 8.27 seconds across the four runs, including loading the model; after that, the median request took 0.39 to 0.58 seconds. RAG with three articles had a median of 0.79 to 1.33 seconds: it pays for an embedding call, and its prompt changes with every question, so the cache could reuse only the first 148 tokens or so, the part of the prompt before the articles.

This isn’t only a local quirk. Anthropic’s write-up on contextual retrieval makes the same point for its models: if a knowledge base is “smaller than 200,000 tokens (about 500 pages of material)”, you can include the whole thing in the prompt, and prompt caching “makes this approach significantly faster and more cost-effective”. Different models, a different context budget, but the same idea: below some size, you may not need retrieval at all.

So why build RAG? Some of the reasons showed up in this run; the others matter in production:

  • Knowledge grows. Fifty articles fit in 8K. At this article size, five thousand would be roughly 400,000 tokens: beyond most context windows, and a large context costs memory and prefill time even where it fits.
  • Prompt tokens. Every question sent about 4,260 prompt tokens with the whole help center, against 431 with RAG, plus RAG’s embedding call for the question. Where you pay per input token, that’s roughly ten times the chat model’s input cost, and cache discounts vary by provider.
  • Answers. With RAG top 3, the expected key fact appeared in 22 replies, against 18. With the whole help center, the model declined five answerable questions with an empty reply, including “How do I get my money back?” and “Is single sign-on available on the Basic plan?”. With three retrieved articles, three of those five replies contained the key fact. That’s one 3B model on one help center; a different model may behave differently, so measure it on yours.
  • Updates. Changing one article only requires re-embedding that article (this small demo simply rebuilds its whole index, which takes about a second).
  • Permissions. In a real product, different users can see different documents. Retrieval can filter to what this user is allowed to read before anything reaches the model. A prompt that contains everything can’t.

Retrieval: Finding the Right Pages

Retrieval was measured on its own first, with no chat model involved. For each answerable question: does an article that answers it appear in the top K results? That’s Recall@K, from Article #3. Each question is labeled with the article that answers it (two questions have two such articles, and either counts), so here it’s the hit rate:

Recall@1 = 22/24 = 0.92
Recall@3 = 24/24 = 1.00
Recall@5 = 24/24 = 1.00

The two misses at rank 1 are worth reading:

'How do I get my money back?'            trash 0.6619, refunds 0.6544, failed-payments 0.6457
'What does the Pro plan cost per year?'  plans 0.8594, annual-billing 0.7744, free-trial 0.6560

“Get my money back” ranked the Trash article (“Trash and recovering deleted items”: getting things back) just above Refunds. “Cost per year” ranked the monthly pricing article above the annual-billing one. Both are the kind of near miss that similarity search makes: the words and the topic match, and the intent doesn’t.

The choice of K changed what customers saw. With top 1, the money question got only the Trash article, and the model declined. The annual question got only the monthly prices, and the model did arithmetic:

{"answered": true, "answer": "The Pro plan costs $25 per month. To calculate the cost per year, multiply the monthly cost by 12. So, the Pro plan costs $25 x 12 = $300 per year.", "source_ids": ["plans", "plans", "plans"]}

The real annual price is $250. The value check caught it, because $300 isn’t in the cited article, and the customer got the decline message. With top 3, both right articles were in the prompt, and both answers had the key fact. A larger K gives the model more chances to get the right article, at the cost of more tokens and more distracting text; the right K is something to measure, not guess.

Article #3 warned that similarity scores are relative, and it shows here. The best match for a question the help center can’t answer scored as high as 0.8508; the best match for one it can answer scored as low as 0.6535. No threshold on the score separates the two sets in this data.

Under the hood: what Recall@K does and doesn't tell you

Recall@3 = 24/24 says that, for every answerable question, an answering article was among the three sent to the model. It doesn’t say the answer was right: one of those 24 still got a wrong answer (below). That’s why retrieval and the final answer are measured separately.

It also says nothing about the six questions without an answer in the help center. They have no correct article, so they can’t appear in Recall@K at all; they need their own test set and their own criterion (did the application decline?).

And the scale matters. 24 questions over 50 articles is enough to show the metric and the failure shapes, not to rate a retrieval system. Recall@5 here means sending a tenth of the corpus; on a real knowledge base with thousands of documents and real user questions, the same numbers would mean something very different.

What Still Breaks

RAG moved the problem; it didn’t remove it. Every failure below came from the test runs.

The right page, misread

“I deleted a project by mistake last week. Can I get it back?” Both RAG modes retrieved the Trash article, which says deleted items stay in Trash for 30 days and can be restored. The model answered:

No, after 30 days, items are permanently deleted and cannot be recovered, even by support.

That’s one of the article’s own sentences with “No” in front of it. It reuses the article’s 30-day fact but reverses its meaning: the customer deleted the project last week, so it should still be recoverable. Retrieval was perfect. The value check passed, because “30 days” appears in the source. This is a generation failure, and no retrieval metric will show it.

No right page exists

For the six questions the help center doesn’t answer, retrieval still returned the closest articles, as this implementation always does. With three of them, the model answered half of these questions from near-miss content:

'Is there a desktop app for Windows?'          (top 1, retrieved: offline)
  Yes, our desktop app for Windows allows you to work offline and sync changes when you reconnect...
'How many days does it take for a refund to arrive?'   (top 3)
  A refund is returned to the original payment method within 30 days of the request.
'What is the maximum number of tasks in one project?'  (top 3)
  There is no limit on the number of tasks in a project, ...

The refund answer is the dangerous kind. The article says refunds can be requested within 30 days; the model turned that into how long a refund takes to arrive. The value check passed, because “30 days” appears in the cited article. With the whole help center in the prompt, the same model declined all six, but it also declined five answerable questions; it was more cautious across the board, not more accurate.

This implementation always returns the top K articles, even when every match is weak. It has no “nothing relevant found” decision. In these runs, the model often treated the closest-looking pages as enough to answer. A production system needs a way to recognize when the retrieved context isn’t relevant enough; the next articles in this phase work on that from both sides, in retrieval (better ranking, recognizing weak matches) and in generation (checks that go beyond values).

Pages that are out of date, or that talk back

Two more failure modes weren’t triggered in this run, but they’re part of the design. The index can go stale: an article changes and nobody re-embeds it. The demo refuses to run when the stored fingerprints don’t match the articles. And documents are input: anything indexed can contain text the model may follow. OWASP lists this under LLM08:2025, “Vector and Embedding Weaknesses”, with a scenario of a document with hidden instructions in a RAG system, and recommends that “all input documents must be validated before they are added to the RAG knowledge base”. Article #11’s warning about injected instructions applies to every retrieved page, not only to the user’s message.

Engineering Decisions

1. Measure whether you need retrieval yet

If the knowledge fits comfortably in the context, changes rarely, and everyone can see all of it, sending it whole with prompt caching may be simpler and fast enough. Decide from your sizes, update rate, permissions, and token costs, and test the model’s answers both ways, as here.

2. Never let the context overflow silently

Count tokens before sending. If the prompt doesn’t fit, fail loudly or retrieve; don’t let the server decide what to drop. Here, the server dropped the instructions first.

3. Treat the index as a build artifact

Record the embedding model, the prefixes, and a fingerprint of every document with the index, and refuse to serve from an index that doesn’t match. Re-index when documents change, and know how stale your index is allowed to be.

4. Choose K by measuring

Top 1 lost two questions to near-miss rankings that top 3 recovered. More context isn’t free either: it costs tokens, and in this run, with all fifty articles in the prompt, the model declined more answerable questions. Measure Recall@K and the final answers for a few values of K.

5. Evaluate retrieval and generation separately

Recall@3 was perfect; the answers weren’t. Keep a labeled set of answerable questions for retrieval, read the answers too, and keep a separate set of questions that should be declined. The last set is where this RAG version did worst.

6. Constrain and log what the model saw

Let the model cite only the articles it was given (here, an enum in the schema), check every cited id, and log the retrieved ids with each request. When an answer is wrong, the first question is “what did the model see?”, and the log should answer it.

7. Treat documents as untrusted input

Validate what goes into the knowledge base, keep access control in the retrieval layer, and don’t let retrieved text grant permissions.

When to Use It (and When Not To)

RAG fits when the knowledge is large, changes often, belongs to you rather than to the model’s training data, or differs between users. Support assistants, internal documentation search, policy and contract questions, and product catalogs are typical.

It’s less useful when the knowledge is small and stable enough to send whole, when the task is about how to respond rather than what facts to use (style, format, tone: often a prompt or fine-tuning question), or when answers need reasoning across many documents at once, which top-k retrieval of a few chunks doesn’t provide.

What to Take Away

  • RAG is retrieval, then generation. Find the few pieces of knowledge a question needs, and give the model only those.
  • Sending everything fails silently when it doesn’t fit. A 4,260-token help center was cut to 2,050 tokens, instructions first, with a success response.
  • Sending everything can be fine when it does fit. With prompt caching, it was the fastest mode here after the first request. RAG wins on context size, prompt-token use, update granularity, and permission filtering. In this run, it also put the expected key fact into more answers, but that didn’t guarantee those answers were correct.
  • Measure retrieval and answers separately. Perfect Recall@3 still produced a wrong answer from the right article.
  • Top-K retrieval always returns something. Unless you add a relevance decision, the model gets the closest pages even when none answers the question. Test questions your knowledge base doesn’t answer; that’s where this version failed most.

Think About These Use Cases

  • An internal HR assistant: Some policies apply only to some countries. How would retrieval make sure an employee only sees the policies that apply to them?

  • A changelog that updates daily: How stale can the index be before answers become wrong, and how would you detect that?

  • A 100-page contract: One document, but too long for the context. What changes when the “knowledge base” is a single long document instead of many short ones?

  • “I don’t know” as a feature: For the questions that should be declined, which signals could your application use to decline, beyond the similarity score?

  • The whole-knowledge-base alternative: Your knowledge base is 30,000 tokens and the model’s context is 128,000. Would you build RAG? What would you measure to decide?

If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️

What’s Next?

RAG gives a model knowledge at question time. The other lever is training the model further, like the support agent’s training course: it changes how the model behaves, which is not the same as giving it a source of truth to look things up in.

In the next article, we’ll look at RAG vs Fine-Tuning: When Should You Use Which?: what each one actually changes, what each costs to build and maintain, and how to decide between them.

← All articles