Skip to content
RAG: Retrieval Augmented Generation explained to developers

A language model knows many things, but it doesn't know yours. It hasn't read your company's internal policy, it doesn't know what yesterday's price list said nor what's in the tickets opened this morning. And when it doesn't know, it often answers anyway, with the same confidence as when it is correct.

The Retrieval-Augmented Generation (RAG) is the most common way to solve the problem. Before letting the model answer, relevant documents are retrieved and passed to it together with the question. Said like that it sounds trivial, and indeed the prototype is: it can be built in an afternoon. The real work starts afterward, when you need to understand why the system gets one out of ten questions wrong and where to intervene.

Why isn't a LLM alone enough? An LLM learns from a large corpus of texts during training and then stops. This leads to three practical limitations. Knowledge is frozen at the cutoff date, so anything that happened after that is unknown to it. Private data (internal documents, databases, non‑public archives) it has never seen. And when information is missing it tends to fabricate something plausible, without stating its source, which makes verification difficult.

The naive solution is to paste all the documentation into the prompt. It works with a few documents. Then it runs into the context window limit, token costs that are incurred with each request, and a quality issue: models perform worse on material that lies in the middle of a very long context, an effect described in the literature as lost in the middle. It's better to pass only what is needed.

What is RAG

The term originates from a 2020 paper by Lewis and colleagues, then at Facebook AI Research (Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks), in which the retriever and generator were trained together. Today, RAG almost always refers to a simpler version: a pre‑trained LLM to which, at runtime, a context retrieved from an external knowledge base is provided.

The flow is always the same: the user asks a question, the system searches the knowledge base for the most relevant passages, inserts them into the prompt alongside the question, and the model answers based on that material. The model itself is untouched: to update what it knows you simply update the documents, which is the main reason a RAG is cheap to maintain.

But how does a RAG system work? There are two distinct phases. Offline the knowledge base is prepared: documents are read, split into chunks, transformed into vectors, and stored in an index. Online, for each question, the most similar chunks are retrieved, the prompt is built, and the answer is generated. The following sections walk through these steps in order.

It starts with the source documents: PDFs, web pages, wikis, emails, databases. This phase is often underestimated and causes silent damage. A PDF with two‑column tables, repeated headers on each

Then the documents should be split into chunks, portions small enough to be retrieved precisely and large enough to make sense on their own. There is no universally perfect size. As a starting point, a few hundred tokens with a 10‑20% overlap between consecutive chunks work well, after which you fine‑tune based on your own data. A chunk that is too short loses context: “this clause applies only if …” without the “if” is useless to anyone. One that is too long dilutes the signal and takes up space in the prompt. Splitting according to the document’s structure works better than cutting every N characters, and repeating the section title inside each chunk improves retrieval more than you might expect.

A useful variant is parent‑document retrieval: you index small chunks for precise search, but you pass the larger section they belong to to the model.

The problem is that the text starts immediately with the definition of embedding, without explaining to the reader why we are talking about vectors and where they fit into the RAG process. First we introduce the data flow, then we explain the concept.

Where the data for RAG is stored

Documents are not simply loaded into a database and retrieved through a traditional text search. First they must be transformed into numerical representations that allow the system to locate the content semantically closest to the user’s question.

This transformation is performed by an embedding model, which converts each piece of text into a numeric vector. An embedding captures the meaning of the text through a sequence of numbers, enabling comparison of content even when completely different words are used. For example, “how do I request vacation” and “procedure for taking leave days” share almost no terms, yet they can have very close embeddings because they express the same concept.

Choosing the embedding model is important. When working with Italian documents, it’s advisable to use a multilingual model or one trained on Italian as well, validating its quality on your own documents rather than relying solely on generic rankings. It is essential to use the same model both when converting the documents and when transforming users’ questions: otherwise, the resulting vectors may not be comparable correctly.

Once generated, embeddings need to be stored in a system that supports vector similarity search. Options vary: in‑memory libraries like FAISS, extensions for existing databases such as pgvector for PostgreSQL, or specialized vector databases like Qdrant, Weaviate, and Milvus.

For a first RAG project, using a database extension already present in the infrastructure is often the most practical solution. With pgvector, for example, we can store the vectors in PostgreSQL together with references to the original documents and their associated metadata, avoiding the need to introduce an additional service to install, configure, and maintain.

Retrieval: how to find the right information

Once the documents and their embeddings are stored, the RAG system is ready to receive user questions. But how does it pinpoint, among thousands of documents, the exact passage that contains the sought answer?

This is where retrieval, the information‑recovery phase, comes into play. When a question arrives, it is also transformed into an embedding using the same model employed to index the documents. The system then compares the question vector with those stored in the archive, searching for the semantically closest chunks.

The comparison is usually performed using a measure called cosine similarity, which assesses how much two vectors point in the same direction in vector space. The results are ordered by similarity and the system selects the top k passages, where k represents the number of pieces of content to retrieve. These passages are then inserted into the context sent to the language model, which uses them to formulate the answer.

It is an apparently simple mechanism, but it hides one of the most critical issues of the whole architecture: if the system retrieves the wrong documents, the model cannot invent the correct information. We can use the most powerful language model available, but if we give it an incomplete or irrelevant context, we are unlikely to obtain a reliable answer.

For this reason, in real RAG projects, it is not enough to implement a vector search and consider the work finished. The information retrieval must be progressively improved.

Hybrid search: combining meaning and keywords

Semantic search has a limitation: it can recognize the meaning of a sentence, but it is not always the best method for locating precise references. Think of a product code, a company acronym, an item number, or the name of a specific procedure. In these cases, finding the exact term searched for can be more important than understanding its general meaning.

To solve this problem we can pair vector search with a lexical search, based on the match between the terms in the question and those present in the documents. One of the most widely used techniques is BM25, an algorithm that assigns a score to documents considering the presence of the searched terms, their frequency, and the document length. In this way we can retrieve content that semantic search might overlook.

The two searches produce different rankings, which can be combined using techniques such as Reciprocal Rank Fusion (RRF). Instead of directly comparing the scores produced by different algorithms, RRF considers the position each document occupies in its respective ranking and generates a combined ordering.

The result is a more robust search: semantic search captures concepts, lexical search finds exact references. Together they cover a larger portion of real‑world cases.

Query rewriting: better understand the question

Not all user questions are phrased completely. They often depend on the conversation context, use abbreviations, or refer to information already discussed. Imagine an employee initially asks how to request vacation leave and, shortly after, adds: “And for part‑timers?”. Taken in isolation, this second question is vague. The system must understand that the user is asking how vacation‑leave requests work for employees on a part‑time contract.

A useful technique is query rewriting, which involves having a language model rephrase the question before initiating the search. The model receives the conversation context and produces an autonomous query, more explicit and suitable for document retrieval.

We can also generate multiple variants of the same question, perform separate searches, and combine the results. This way we increase the chances of retrieving relevant documents that might use terminology different from the user's.

A related technique is HyDE (Hypothetical Document Embeddings). In this case the model generates a hypothetical document that could represent an answer to the question. The generated text is transformed into an embedding and used to search for similar documents in the repository. We are not trying to use that answer as reliable information: it serves only as an intermediate representation to improve retrieval.

Metadata: narrowing the search scope

Another element that can significantly improve retrieval is the use of metadata associated with chunks. When we index a document, we can retain additional information such as publication date, version, department, language, or document type.

These data allow applying filters before or during the search. If an employee looks for information about vacation leave, for example, we can limit the search to up‑to‑date procedures and personnel‑related documents, preventing the system from retrieving outdated regulations or content belonging to other areas.

Metadata does not replace semantic search, but makes it more selective. They are particularly useful when the archive contains similar documents, different versions of the same procedure, or information that needs to be distinguished based on context.

Response generation and information control

After completing the retrieval, the RAG application has the document passages to use for answering the question. At this point it automatically prepares the prompt to send to the language model, inserting the original question, the retrieved content, and the instructions defined during development.

These instructions are essential because they define how the model should use the received information. In particular, it is asked to base its answer on the provided context, not to fabricate details that do not appear in the documents, and, when possible, to cite the sources used.

The application can also specify how to behave when the retrieved documents do not contain sufficient information. Instead of attempting an answer anyway, the model should explicitly state that it lacks the necessary elements to respond.

The language model then processes the prompt and returns the answer to the user. This mechanism helps reduce so‑called hallucinations, but does not eliminate them entirely. An LLM can still misinterpret a passage, combine incompatible information, or present as certain an information that is not.

For this reason, a reliable RAG system is not built only by choosing a good language model. The entire pipeline must be cared for: document quality, chunking, embedding model, retrieval strategy, context selection, and answer generation.

A practical example: implementing a simple RAG system in Python

This example does not yet use a real vector database. The embeddings are stored in a NumPy matrix and the search is performed in memory via dot product.

This is an intentional choice to explain the mechanism without immediately introducing PostgreSQL, pgvector, or Qdrant. In a real application, we would use a vector store instead of the NumPy matrix.


import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")

chunks = [
    "Vacation requests must be submitted through the HR portal at least 7 days in advance.",
    "Travel expense reimbursement requires the submission of original receipts.",
    "The corporate VPN is mandatory to access internal systems remotely.",
]

chunk_emb = model.encode(chunks, normalize_embeddings=True)

def recupera(domanda: str, k: int = 2):
    q = model.encode([domanda], normalize_embeddings=True)[0]
    punteggi = chunk_emb @ q
    top = np.argsort(punteggi)[::-1][:k]

    return [
        (chunks[i], float(punteggi[i]))
        for i in top
    ]

def costruisci_prompt(domanda: str, passaggi) -> str:
    if not passaggi:
        return "No relevant documents are available."

    contesto = "\n".join(
        f"[{i+1}] {testo}"
        for i, (testo, _) in enumerate(passaggi)
    )

    return (
        "Answer the question using only the following context. "
        "Cite the source numbers. If the answer is not in the context, "
        "say that you don't know.\n\n"
        f"Context:\n{contesto}\n\n"
        f"Question: {domanda}"
    )

domanda = "How much notice is required to request vacation?"

passaggi = recupera(domanda)

for testo, punteggio in passaggi:
    print(f"Score: {punteggio:.4f} | {testo}")

prompt = costruisci_prompt(domanda, passaggi)

print("\nPrompt for the generative model:\n")
print(prompt)

# response = llm.generate(prompt)

How to tell if it works

A RAG system that seems to work when we test it manually is not necessarily a reliable system. To evaluate its quality we need to distinguish two fundamental aspects: the ability to retrieve the correct documents and the ability to generate a response consistent with the retrieved information. These are two distinct phases and can present different problems.

Retrieval evaluation aims to understand whether, among the documents selected by the system, the one that actually contains the answer is present. To measure this capability we can use metrics such as Recall@k, which indicates how often the correct document appears among the top k results, or MRR (Mean Reciprocal Rank), which considers the position of the first relevant result. It is not enough to retrieve a useful document: it is important that it is returned in the top positions, because the number of passages provided to the generative model is usually limited.

Generation evaluation concerns the quality of the answer produced by the LLM. Even when retrieval has identified the correct documents, the model may misinterpret them, introduce information not present in the context, or provide an answer that is not pertinent to the question. In this phase metrics such as Faithfulness, which measures how well the answer is supported by the retrieved information, and Answer Relevance, which assesses how relevant the answer is to the user's question, become important.

To obtain a concrete evaluation it is useful to build a small test set starting from real questions. For each question you need to define the expected answer and identify the documents that contain the necessary information. Even an initial dataset of 50–100 questions can be sufficient to spot obvious problems and compare different configurations.

This test suite should be reused every time we change the document chunking, the embedding model, the retrieval strategy, or the prompt. This way we can verify whether a change truly improves the system or introduces regressions elsewhere in the process.

There are tools like Ragas, which automate part of the evaluation by using a language model as a judge to analyze the answers and the retrieved context. They are useful tools, but their results should not be taken as absolute truth: even an LLM used to evaluate another LLM can make mistakes. Therefore it is important to periodically compare automatic evaluations with a sample of manually verified results.

Security and privacy

It is a topic that emerges too late in many projects. Regarding permissions the rule is simple: if a user cannot read a document, the system must not retrieve it for them. Access control should be applied in the retrieval phase, filtering by permissions, and not delegated to the prompt: “do not reveal confidential documents” is not a security control.

Then there is indirect prompt injection. Retrieved documents are fed into the prompt, so malicious text inside a web page, an email, or a PDF can contain instructions aimed at the model. The retrieved content should be treated as untrusted data: clearly separated from instructions, with tools that have limited powers and without irreversible actions that the model could take without confirmation.

Finally personal data. A vector index contains personal data if the documents do so, and GDPR applies there as well: legal basis, minimization, right to delete. The location where the embedding model and the LLM run and the destination of the data must be verified, especially in public administration and healthcare.

When RAG is not needed

It does not help if the problem is behavioral or format‑related rather than knowledge‑related. It does not help for questions that require calculations or aggregations on structured data: there you need SQL or dedicated tools, not semantic similarity. And if the corpus is so small that it comfortably fits in the context, you might as well place it there.

For everything else—broad, changing, private knowledge with answers that can be traced back to sources—RAG is almost always the right starting point. When it does make a mistake, the first thing to look at is what was retrieved: in most cases the wrong answer originates there.