You put a language model in front of your company's documentation and asked it how to reset a password. The answer is fluent, confident and wrong: it describes a button that does not exist in your product. The model is not lying to you, it simply knows nothing about you. It knows what it read during training, and your internal documentation was not among the readings.
Retrieval-Augmented Generation (RAG) is the most widely used remedy today: before the model answers, a search component finds the passages of your documents closest to the question, and those passages are written into the prompt as material to consult. The model does not have to remember, it has to read. This article opens the AI for Web Developers series and explains the parts of a RAG system, with three small programs that I actually ran. You only need to be able to read TypeScript and to know what a call to an HTTP service is: no model is called here.
The problem: a model that does not know your data
Picture the customer support of an online shop: thousands of FAQ pages, manuals, closed tickets. If you hand the questions to a generic model, you run into three distinct limits, which are better kept apart because they have different remedies.
| Limit | What it means | What it costs you |
|---|---|---|
| Frozen knowledge | The model only knows the texts used in training, up to a certain date | It knows nothing about your private data or about news after that date |
| Hallucination | When a piece of information is missing it produces a plausible sentence anyway | Wrong answers delivered with confidence |
| No provenance | The answer does not say which document it comes from | You cannot verify it or show it to the customer as a source |
A better-written prompt solves none of the three, because the problem is not how you ask but what the model has in front of it. RAG steps in exactly there: it reduces hallucination by supplying the right text and it gives you provenance back, because you know which passages you inserted. It does not eliminate it: a model can still ignore the context or misunderstand it, which is why a section on evaluation comes later.
What RAG is, and what it is not
The name comes from the work of Patrick Lewis and colleagues, Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020). In the paper a text-generation model is combined with an external memory, a vector index of Wikipedia queried by a neural retriever, and the whole is fine-tuned on question-answering tasks. In today's web applications the word means something simpler: nothing is trained, you search and paste into the prompt. The underlying idea is the same, the amount of work changes.
The most useful comparison is the open-book exam. The student without notes answers from memory and, if there is a gap, improvises. With the notes on the desk they look for the right chapter and answer by reading. RAG is the chapter looked up on your behalf. As in the exam, the result depends on two things: how good the search is (if you open the wrong chapter you answer badly even with all the books) and how clear the instructions are (“answer only with what you find”).
The two pipelines of a RAG system
A RAG system is really two programs that share an index. The first runs beforehand, once or at intervals, and prepares the documents. The second runs at every user question. Keeping them separate in the code avoids the typical beginner's mistake, which recomputes the embeddings of all the documents on every request.
INDEXING (offline) QUERY (at every question)
documents -> loader question -> embedding (SAME model)
-> splitter (chunks) -> similarity search in the index
-> embedding of each chunk -> assembling the chunks into the prompt
-> saving into the index -> model -> answer + sources
The diagram shows where the two halves meet: the index, and the embedding model. The constraint is rigid: the document vectors and the question vector must come from the same model, with the same dimensions. If you change the embedding model, for example to move to a cheaper one, you have to redo the indexing of the whole corpus; the old and the new vectors are not comparable, and the search returns random results without signalling any error.
Embeddings: meaning becomes geometry
An embedding is a list of numbers that represents a text. Embedding models are trained so that texts with similar meaning produce nearby vectors, even when they use different words: “the cat sleeps on the couch” and “the feline rests on the sofa” end up close, “the price of gold rises” far away. Real vectors have hundreds or thousands of components; to make the calculation below readable I made up four, and it is an example, not the output of a model.
Distance is almost always measured with the cosine similarity: the angle between two vectors, ignoring their length. It is 1 for vectors pointing the same way, 0 for orthogonal vectors, -1 for opposite ones. The program computes it with a dot product and two norms, checks that the lengths match (comparing vectors of different sizes is a sign that you mixed up models) and prints three comparisons plus the error.
function cosineSimilarity(a: number[], b: number[]): number {
if (a.length !== b.length) {
throw new Error('Vectors must have the same length');
}
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < a.length; i++) {
dotProduct += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
const cat = [0.23, -0.45, 0.67, 0.12];
const feline = [0.22, -0.44, 0.68, 0.11];
const gold = [-0.56, 0.78, -0.12, 0.91];
console.log(cosineSimilarity(cat, feline).toFixed(4));
console.log(cosineSimilarity(cat, gold).toFixed(4));
console.log(cosineSimilarity(cat, cat.map(x => -x)).toFixed(4));
try { cosineSimilarity([1, 2], [1, 2, 3]); } catch (e) { console.log((e as Error).message); }
// Output:
// 0.9997
// -0.4005
// -1.0000
// Vectors must have the same length
The cat and feline vectors give 0.9997, the cat against gold -0.4005, and a vector compared with its own opposite exactly -1. Note that the practical meaning of 0 and of the intermediate values depends on the embedding model, not on the mathematics. That is why you compare scores with each other (the first is closer than the second) and you do not set an absolute threshold without having measured it on your own data.
As for the models, the choice is made on dimensions, supported language and where they run. The dimensions below come from each model's documentation; I left the prices out because they change and must be read on the price list of the moment.
| Model | Dimensions | Where it runs |
|---|---|---|
text-embedding-3-small | 1536 (default) | OpenAI paid API |
text-embedding-3-large | 3072 (default) | OpenAI paid API |
all-MiniLM-L6-v2 | 384 | sentence-transformers library, locally |
nomic-embed-text | not verified here | Model published in the Ollama library, locally |
The dimension weighs twice: a longer vector takes more space in the index and makes the search slower, but it
usually tells the nuances apart better. The OpenAI documentation adds that the models of the
text-embedding-3 family accept a parameter to shorten the vectors, so the dimension is not a final
choice. The last two are the option when the texts must not leave your environment; for local models there is
a dedicated article, Local LLMs with Ollama.
Chunking: how to cut documents
You do not compute an embedding for a whole manual: a single vector for a hundred pages would be an indistinct average. You split the text into chunks, and each chunk becomes a candidate for the search. The size is a compromise: a chunk that is too large mixes topics and pulls the vector toward the emptiness of the average; one that is too small loses the sentence that makes it understandable.
- Chunk size: measured in characters or tokens; it is the parameter to start from and the one to tune by looking at the results
- Overlap: how many characters are repeated between one chunk and the next, so as not to split an idea in half
- Preferred separators: the points where it is best to cut, that is paragraphs, then sentences, then words
There is no absolute right value: it depends on the type of document and on the embedding model, and you find
it by measuring how often the search returns the correct passage. The useful rule is to cut where the text
already has a boundary, and to repeat a bit of text between one chunk and the next as a safety belt.
Libraries such as LangChain.js provide ready-made splitters
(RecursiveCharacterTextSplitter in the @langchain/textsplitters package); their
documentation justifies the split with the same argument: large chunks are harder to search and may not fit
in the model's context window.
The program below is a minimal version, written to see the phenomenon: it cuts at the character limit, steps
back to the last space so as not to split words, and restarts overlap characters earlier.
I apply it to the same text twice, without overlap and with 40 characters of overlap.
function chunk(text: string, size: number, overlap: number): string[] {
if (overlap >= size) throw new Error('overlap must be smaller than size');
const out: string[] = [];
let start = 0;
while (start < text.length) {
let end = Math.min(start + size, text.length);
if (end < text.length) {
const lastSpace = text.lastIndexOf(' ', end);
if (lastSpace > start) end = lastSpace;
}
out.push(text.slice(start, end).trim());
if (end >= text.length) break;
let next = end - overlap;
const sp = text.indexOf(' ', next);
start = sp === -1 || sp >= end ? end : sp + 1;
}
return out;
}
const doc = 'Angular is a TypeScript framework for web applications. ' +
'It supports server-side rendering (SSR) to noticeably improve the performance. ' +
'Standalone components remove the need for NgModule. ' +
'Signals offer fine-grained reactivity without Zone.js.';
console.log('document length:', doc.length);
for (const [size, overlap] of [[120, 0], [120, 40]]) {
console.log(`--- size=${size} overlap=${overlap}`);
chunk(doc, size, overlap).forEach((c, i) => console.log(`#${i + 1} (${c.length}) ${c}`));
}
// Output:
// document length: 241
// --- size=120 overlap=0
// #1 (117) Angular is a TypeScript framework for web applications. It supports server-side rendering (SSR) to noticeably improve
// #2 (114) the performance. Standalone components remove the need for NgModule. Signals offer fine-grained reactivity without
// #3 (8) Zone.js.
// --- size=120 overlap=40
// #1 (117) Angular is a TypeScript framework for web applications. It supports server-side rendering (SSR) to noticeably improve
// #2 (120) rendering (SSR) to noticeably improve the performance. Standalone components remove the need for NgModule. Signals offer
// #3 (77) the need for NgModule. Signals offer fine-grained reactivity without Zone.js.
Without overlap the phrase “noticeably improve the performance” is cut between the first and the second chunk: the words the performance sit in a chunk that no longer says what they refer to. With overlap the second chunk restarts from “rendering (SSR) to noticeably improve the performance” and the concept stays whole. The price is visible: the indexed text grows, because some words appear in two chunks. The sizes here are ridiculous (120 characters) because the test text is short: in a real case you will start from hundreds of characters and tune.
A minimal RAG, to see the prompt
The heart of the application is a function of a dozen lines: it searches, builds the context, asks. Here I run it with two declared stand-ins, so as to show the output without calling any model. The embedding is fake: it counts how many times each word of the corpus appears in the text, and knows nothing about synonyms. The model is fake and scripted: instead of answering it returns the prompt it received, so you can see what would really reach it. The corpus is three made-up FAQs.
type Doc = { source: string; pageContent: string };
const STOP = new Set(['how', 'do', 'i', 'the', 'a', 'an', 'to', 'your', 'my', 'of', 'from', 'in', 'within', 'can', 'be', 'as', 'or', 'and', 'is']);
const tokens = (t: string) =>
t.toLowerCase().replace(/[^a-z0-9 ]/g, ' ').split(/\s+/).filter(w => w && !STOP.has(w));
const corpus: Doc[] = [
{ source: 'faq/password.md', pageContent: 'To reset your password open Settings, choose Security and press Reset password.' },
{ source: 'faq/invoices.md', pageContent: 'Invoices can be downloaded as PDF from the Billing section of your profile.' },
{ source: 'faq/shipping.md', pageContent: 'Shipments within Italy arrive in two or three working days.' },
];
const vocab = [...new Set(corpus.flatMap(d => tokens(d.pageContent)))].sort();
const embed = (t: string) => { const w = tokens(t); return vocab.map(v => w.filter(x => x === v).length); };
const cosine = (a: number[], b: number[]) => {
const dot = a.reduce((s, x, i) => s + x * b[i], 0);
const n = (v: number[]) => Math.sqrt(v.reduce((s, x) => s + x * x, 0));
return n(a) === 0 || n(b) === 0 ? 0 : dot / (n(a) * n(b));
};
const vectorStore = {
similaritySearch(query: string, k: number): Doc[] {
const q = embed(query);
return corpus
.map(d => ({ d, score: cosine(q, embed(d.pageContent)) }))
.filter(x => x.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, k)
.map(x => x.d);
},
};
// Scripted fake model: it generates nothing, it returns the prompt it received.
const llm = { invoke: async (prompt: string) => prompt };
async function handleUserQuery(query: string): Promise<string> {
const relevantDocs = vectorStore.similaritySearch(query, 2);
const context = relevantDocs
.map(doc => `[Source: ${doc.source}]\n${doc.pageContent}`)
.join('\n\n');
return llm.invoke(
'Answer ONLY with the information provided. If it is missing, say so.\n\n' +
`DOCUMENTS:\n${context || '(no document found)'}\n\nQUESTION: ${query}`
);
}
console.log(await handleUserQuery('How do I reset the password?'));
console.log('=====');
console.log(await handleUserQuery('How do I recover my credentials?'));
// Output:
// Answer ONLY with the information provided. If it is missing, say so.
//
// DOCUMENTS:
// [Source: faq/password.md]
// To reset your password open Settings, choose Security and press Reset password.
//
// QUESTION: How do I reset the password?
// =====
// Answer ONLY with the information provided. If it is missing, say so.
//
// DOCUMENTS:
// (no document found)
//
// QUESTION: How do I recover my credentials?
In the first question the search finds the password FAQ and the prompt contains the source
(faq/password.md) in front of the text: it is the provenance that a model on its own does not
give you. The instruction “answer ONLY with the information provided, if it is missing say so” is
the line that reduces invention, and context || '(no document found)' avoids sending an empty
context without declaring it. In the second question, which asks for the same thing in different words
(“recover my credentials”), the word count finds nothing. It is the limit that real embeddings
exist to overcome: lexical search looks for the same words, semantic search looks for the same meaning. And the
score > 0 filter shows the other half of the story: with a real index something always comes
back, even when it is irrelevant, so you need a measured threshold or an instruction telling the model to
declare that the material is not enough.
RAG or fine-tuning
The question always comes: why not train the model on my documents? The two techniques solve different problems, and the table sets them side by side on the criteria that matter when you have to decide.
| Criterion | RAG | Fine-tuning |
|---|---|---|
| What it adds | Facts and documents to consult | Style, format, behaviour |
| Updating a piece of information | You change the document and reindex that piece | You retrain or re-tune the model |
| Provenance | You know which passages you used and can cite them | The knowledge is in the weights: no source to show |
| Recurring cost | Search and longer prompts on every request | Short prompts, but the training cost is paid up front |
| Infrastructure | An index to maintain | Prepared training data and an evaluation procedure |
The practical rule: use RAG when you want the model to know something specific and changeable, fine-tuning when you want it to behave in a certain way, and combine the two only after seeing where the first is not enough. A note on vocabulary: when a site says it has an assistant “trained on its content” it almost always means RAG, not a training run; the article Fine-tuning vs RAG compares the two approaches more calmly.
Beyond similarity search
Taking the k closest chunks is the starting point, and for many corpora it is enough. When it is not, the libraries offer retrieval variants, and knowing their names lets you look them up in the documentation.
- Simple similarity: the k chunks with the highest score
- MMR (Maximal Marginal Relevance): picks chunks that are relevant but different from each other, so as not to repeat the same paragraph three times
- Hybrid search: combines keywords and vectors, useful for product codes and acronyms that embeddings handle badly
- Metadata filters: narrows by date, language or product before searching
- Parent document retrieval: searches on the small chunk but hands the model the larger block that contains it
The criterion that chooses among the items is the kind of error you observe. Answers that repeat the same sentence call for MMR; the article code “AB-4471” that is never found calls for a hybrid search; answers that cite the wrong version of the manual call for a metadata filter. Changing strategy without having seen the error is guessing.
When RAG is not the right tool
- Aggregations and calculations: “how many orders in October?” is an SQL query, not a text search
- A tiny corpus: if all the knowledge fits comfortably in the model's context window, you can paste it into the prompt and skip search and index
- Data that changes constantly: an index is a photograph, and between one update and the next it answers with the old version
- Multi-step reasoning: RAG puts the facts on the table, but does not make the model better at deducing
The common thread is that RAG solves the problem of where to find the information, not that of what to do with it. If your problem is a calculation, a deduction or a datum that changes every second, you need a database, a program or an agent that calls tools; the latter case is the topic of the article on AI agents.
Measuring whether it works
A RAG system seems to work until you try the three questions you know. To notice the failures you need a set of questions with the expected answer, written by someone who knows the domain, and metrics that separate the two points where the system can break. The open-source library RAGAS defines several; four are the most useful to start with.
- Context Precision: how many of the retrieved passages are really relevant
- Context Recall: whether among the retrieved passages there is everything needed to answer
- Faithfulness: whether the claims in the answer are supported by the supplied context
- Response Relevancy: whether the answer addresses the question asked
The first two judge the search, the other two judge the generation: separating them tells you where to intervene. If context precision is low you work on chunking and retrieval; if it is high but faithfulness is low, the problem is in the prompt or in the model. I do not give you reference thresholds because they depend on the domain and on how you measure: you decide the acceptable level, starting from a set of real questions, and you rerun the measurement at every change.
What you can do now
You can explain why a model on its own does not know your data and what RAG does to remedy it; you can tell indexing from query and why they use the same embedding model; you can compute and read a cosine similarity, choose a chunking and see what you lose without overlap; you can recognise the cases in which the remedy is something else. In the next article you build the real system: RAG with TypeScript and LangChain.js. To understand where embeddings live, continue with Vector Databases for Web Developers.
Frequently asked questions
Does RAG eliminate hallucinations?
No, it reduces them. The model sees the right text and so invents less, but it can ignore it, misunderstand it or fill in from its own memory if the instruction does not forbid it. The risk is limited by asking it to answer only with the supplied material, by showing the sources and by measuring the faithfulness of the answers.
Do I need a vector database to do RAG?
Not to begin with. With a few hundred chunks you can keep the vectors in memory and compare them as in the listing above. A vector database becomes useful when the chunks are many, when you need to filter by metadata or when the index must survive service restarts.
Is RAG or fine-tuning better?
It depends on what you want to change. To make the model know specific, updatable documents you start with RAG; to change tone, format or behaviour you consider fine-tuning. The two techniques can be combined, but it is better to start with the simpler one and move to the other only with a measurement in hand.
For what lies beyond the first step, integrating the OpenAI and Anthropic APIs shows how to connect a model to a web app, and AI in CI/CD brings the same model into the release pipeline.
Sources
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (arXiv:2005.11401) - the original definition of RAG, the Wikipedia vector index as external memory, the topic of provenance, consulted on 2026-11-12
- OpenAI, embeddings guide - default dimensions 1536 and 3072 of the two text-embedding-3 models and the possibility of shortening the vectors, consulted on 2026-11-12
- all-MiniLM-L6-v2 model card on Hugging Face - 384-dimensional vector space and use for semantic search, consulted on 2026-11-12
- Ollama, nomic-embed-text model - the open embedding model in the Ollama library and its command-line use, consulted on 2026-11-12
- LangChain.js, RAG tutorial - the loading and splitting steps and the reason why large chunks are harder to search, consulted on 2026-11-12
- RAGAS, available metrics - the names of the metrics Context Precision, Context Recall, Faithfulness and Response Relevancy, consulted on 2026-11-12
The three TypeScript listings were run with Node 24 in a folder outside the repository: the outputs in the comments are the real ones. The four-component vectors are made up for the example, and the corpus of the RAG loop is fictitious. The diagram of the two pipelines is not executable. No model was called.
Commenti
Caricamento commenti...
Sign in to comment