Skip to content
Ask for a Budget
EngineeringAugust 31, 202610 min readUpdated on November 11, 2026

How to build a RAG: from documents to an assistant that cites its source

The six steps, the chunking parameters, the cost of each stage and the seven mistakes that already caused rework, with numbers from a real 2,563-chunk index.

How to build a RAG: from documents to an assistant that cites its source
Índice do artigo
faltam 10 min de leitura

The entire index of our corpus, with 374 documents and 2,563 chunks, is built in 0.4 seconds and takes up 2.15 MB. No database, search server or paid service was involved.

Most material on how to build a RAG starts with choosing the vector database and ends with the prompt. That is the reverse of the order that works, and it produces systems that impress in the demo and disappoint in use.

This article describes the six steps in the order in which they decide the result, with the real parameters of an index we built and measured. Each step covers what it unlocks and what happens when it is skipped.

Article summary

  • Evaluation comes first, not last. It answers, for free, the most expensive question in the project: can the knowledge base support the business's questions?
  • Chunking parameters matter more than the choice of database: target of 350 words, ceiling of 550, overlap of 80.
  • Two filters come before the expensive model. A cheap classifier blocks out-of-scope questions, and the search excludes outdated content.
  • The 2,563-chunk index fits in 2.15 MB and is built in 0.4 s, which removes the database, the cache and a whole class of bugs.

What to decide before writing the first line

Three decisions lock in the rest of the project, and all of them are business decisions, not engineering ones. Postponing them causes rework at the stage where it is most expensive.

  • Which sources go in, and which is the official version of each subject when two contradict each other
  • Who can see what, because permissions need to be part of the search, not the text of the answer
  • What is time-sensitive, such as price, deadline and SLA, and therefore needs its own validity rule
  • What happens when the system does not know, including the exact text it will show
  • Who owns reading the questions without a good answer and fixing the content

The last one is the one that most often disappears from the scope and the one that most decides whether the assistant is still good six months later. Without an owner, the knowledge base ages and answers slowly get worse, with no alarm.

Step 1: turn documents into chunks

The model does not receive documents, it receives pieces. Chunking well is what decides whether the piece that reaches the model contains a complete idea or the end of one line of reasoning and the beginning of another.

The rule that works is to respect the document's structure before counting words: cut by section, and only then group short sections or split long ones until you reach the target size.

ParameterValue and reason
Target per chunk350 words, enough for a complete idea without diluting the terms the search relies on
Ceiling550 words, so a long section does not become a chunk that dominates the context on its own
Overlap80 words between neighboring chunks, so an answer that falls on the seam is not lost
Floor25 words; below that, the chunk is discarded for carrying no information
Median obtained119 words, because many sections are short and become chunks of their own

The gap between the 350 target and the 119 median says something useful about institutional content: it is made of many short sections. Forcing the target size by gluing together unrelated sections makes the search worse instead of better.

Isometric illustration of a document being split into smaller cards that partially overlap

Each chunk needs to carry the metadata that will be used later: the source URL, the document title, the date, the type of source and the section it came from. Retrieving text without knowing where it came from makes citation impossible, and citation is half the value of the system.

The URL deserves special attention. It needs to be the same one the site publishes as canonical, otherwise the assistant's citations point to addresses that redirect.

Step 2: index, starting with the simplest option

The industry's default choice is to generate embeddings and store them in a vector database. The choice we recommend to start with is lexical word search, the kind search libraries have implemented for decades.

The reason is not ideological, it is about sequence: lexical search has no per-query cost, needs no external service, runs in seconds and produces a baseline that anything more sophisticated has to prove it beats. Without a baseline, you do not know whether the vector database helped.

2,563Chunks indexed
14,519Terms in the index
2.15 MBIndex size
0.4 sTime to build

At this scale, the whole index fits in the process's memory and scanning everything is faster than querying an approximate structure. What this unlocks is operational: without a database, the most annoying category of RAG error disappears, which is the index and the text getting out of sync and the system citing a document that has already changed.

Step 3: the gatekeeper that comes before the search

Before searching for anything, one question needs an answer: is this a subject for the company? Putting this decision after the search is the most common design mistake, and it costs at both ends.

The temptation is to use the search score as the criterion: if nothing scored well, the subject is out of scope. We measured it and the hypothesis is refuted. The question "what is the best carrot cake recipe" scored 9.52 in our index, against 8.88 for "do you build AI chatbots". The out-of-scope question won.

The same classifier handles the second dangerous category, which is questions about price, deadlines and SLA. They are in scope, and even so they should not be answered by text generation: they go down their own path, with curated and up-to-date content, or to a human contact.

Step 4: choose what goes into the model's context

Retrieving ten chunks and sending all ten is a prototype's default behavior, and it produces two problems that only show up in real use.

The first is document dominance. A long page has many sections and, if all of them score reasonably well, it fills the whole list and the rest of the knowledge base becomes invisible. The fix is a cap on chunks per document, which in our case is two.

The second is outdated content. Since relevance does not see dates, old documents win often. The fix is to tag each chunk with a freshness band derived from its date and exclude the expired bands before building the context, with permanent exclusion for anything time-sensitive.

Isometric illustration of chunks passing through two filters before reaching the model's desk

The third adjustment is subtler and worth measuring before you apply it: how many chunks to deliver. In our measurement, doubling the list from 10 to 20 chunks bought 3.6 percentage points of accuracy.

This means that, beyond a certain point, additional material adds cost and noise without adding answers. The gain lies in improving the content, not in sending more of it.

Step 5: generate the answer with a citation

Only here does the large model come in, and it comes in with a restrictive instruction: answer only with the material provided, and say it does not know when the material does not support the answer. A good model follows this quite consistently when the retrieved material is clean.

Isometric illustration of an answer panel connected by three wires to three specific folders inside a filing cabinet

The citation is what turns the answer into something auditable: every statement gets a source address, and whoever received the answer can check it without asking anyone for help.

It is also what makes correction possible. A wrong answer with a source points to which document needs to change; a wrong answer without a source turns into an argument.

This piece has an implementation trap that only shows up on screen.

Step 6: evaluation, which almost every project skips

This is the step that separates an engineering project from a series of guesses, and the good news is that it is the cheapest of all: it runs without a model, without an API key and at no cost.

The evaluation material already exists in most companies: it is the questions the operation answers in writing, each one linked to the document that answers it. Two metrics are enough to start. The first is whether the right document appeared among the top results. The second, more revealing, is how much of the correct answer was present in the retrieved material.

retrieval evaluation
$ node tools/rag/eval.js638 questions evaluated, 1,788 chunks in the indexrecall@10          74.9%answer coverage   54.1%strict 85% criterion: not met
Output of the August 31, 2026 run, with the FAQ chunks left out of the index (1,788 of the 2,563). The output that matters is not the first line, it is the list of failures that comes after it.

The real value of this step is not in the aggregate number, it is in the list of questions that failed. Reading that list is the highest-return activity of the whole project, because each failure points to a document that needs to be written, fixed or retired.

One method detail that changes the result: the evaluation needs to remove the text of the questions themselves from the index. Without that, you are measuring whether the system finds what is already written in the same words, which gives excellent numbers and proves nothing. That is why the terminal above shows 1,788 chunks, not the 2,563 of the full index: the FAQ chunks, which contain the questions themselves, are left out while the evaluation runs.

Where the money goes

The operating cost of a RAG is very asymmetric, and understanding the asymmetry is what lets you design cheaply.

StageCost per questionNote
Scope classificationVery lowA few dozen input tokens, minimal output, small model
SearchPractically zeroScans an in-memory index, with no external call
Answer generationThe highest of allThe only step that uses the large model, along with the retrieved context
IndexingNot per questionRuns at build time or on a schedule, and ours takes 0.4 seconds

The design consequence is the order of the filters. Every question the classifier blocks is a generation that did not happen, and generation is the only expensive item in the table. A system that searches and generates first, and only then evaluates whether it should have answered, pays for the expensive item on every bad question.

Where to host it

When the index fits in the deployment package, the architecture becomes small in a way that solves problems instead of creating them.

Node.jsReads the content, chunks it and generates the index
the index ships with the deployment, no database in between
Serverless functionClassifies, searches and streams the answer
Language modelWrites using only the retrieved material

What this simplicity unlocks is reliability. Without a database, the index and the published text are generated in the same process and cannot diverge. Without a separate cache, invalidation disappears. Infrastructure complexity becomes justified when the corpus no longer fits in memory, and not before.

Two security rules complete the design. The index cannot be published in a public folder, because that hands structured content to any crawler. And the model key cannot go into an environment variable that the site bundler includes in the browser package, because every variable of that kind becomes visible text in the browser of anyone who visits.

Seven mistakes that already caused rework

MistakeWhat happens
Choosing the vector database before measuringYou buy infrastructure for a problem that may not exist, with no baseline to compare against
Evaluating with questions that are in the indexThe numbers look great and say nothing about new questions
Using the search score as a scope filterOff-topic questions get through, and legitimate questions are refused
Ignoring document datesOld content wins the relevance contest and the answer comes out outdated
Sending every retrieved chunkOne long page dominates the context and the rest of the knowledge base becomes invisible
Promising section citations without checking anchorsThe link lands at the top of the page and the user cannot find the passage
Not defining who looks after the contentThe system starts out good and degrades on its own, with no alarm

A delivery path that works

The order below has a useful property: each stage delivers value on its own and has a verifiable acceptance criterion, which lets you stop at any point without being left with a half-built system.

  1. Content decisions, without writing code: official sources, permissions, what is time-sensitive and who owns curation.
  2. Index and evaluation, running locally. Acceptance is having the list of questions the knowledge base cannot answer, which is a deliverable in itself.
  3. Endpoint with classifier, search and generation. Acceptance is the question set passing, including out-of-scope questions falling into refusal.
  4. AI search in the existing interface, keeping the old search as a fallback for network failures.
  5. Conversational assistant, last, because it is what requires the refusal state to be ready and the data policy settled.

If the budget runs out after the second stage, the company is left with a map of the questions the business receives and does not know how to answer in writing. That map is often worth more than the assistant.

Sources and method

The parameters and numbers in this article come from a retrieval prototype built on X-Apps' public content, run on August 31, 2026, with 374 documents and 2,563 chunks.

The evaluation used 730 questions written by the content team with known source documents, of which 638 were evaluated after discarding 5 with no document body and 87 with no distinctive term in common with the expected document.

The scope caveat: these measurements evaluate retrieval, not the final quality of the generated text. The corpus is institutional content in Portuguese, and knowledge bases of another kind, such as code or multilingual legal documents, may require different chunking and search decisions.

Frequently asked questions

With evaluation, not generation. Build the index, run the real questions from the operation and read the retrieved chunks without asking any model for an answer. If the chunks answer the questions, the project is viable. If they do not, the problem is the content and no model will fix it.

Previous post
Your company's archive as an AI asset: you rent the model, not the corpus
Next post
Claude Opus 5: cost and quality at each effort level
Newsletter

One email a month, no noise

What we learn shipping custom software and applied AI.

Related articles

What is DevOps?4 min · Engineering
Understanding the Angular framework2 min · Engineering
APIs and microservices: the reinvention of technology2 min · Engineering
Blockchain APIs: what can we learn from the application?2 min · Engineering
Docker: smart storage2 min · Engineering

Accelerate your business with X-Apps

Ask for a Budget
X-Apps is an IT provider partner and advised by
Gartner
Receive our e-mails
News on software and applied AI.
Follow X-Apps