Retrieval-Augmented Generation

Retrieval-Augmented Generation, or RAG, combines information retrieval with a language model.

Instead of relying only on information stored in the language model, a RAG system retrieves relevant information from an external knowledge base.

Documents

Documents are loaded from a knowledge source such as Markdown files, PDF documents, databases or web pages.

Chunking

Large documents are divided into smaller pieces called chunks.

Chunk size affects retrieval quality. Very large chunks may contain too much unrelated information, while very small chunks may lose important context.

Chunk overlap can preserve context around chunk boundaries.

Embeddings

An embedding model converts text into numerical vectors.

Texts with similar semantic meaning tend to have vectors located close to each other in the embedding space.

Vector databases and vector indexes allow applications to search for vectors similar to a query vector.

FAISS is a library designed for efficient similarity search over vectors.

Retrieval

When a user asks a question, the question is converted into an embedding.

The vector index searches for the document chunks whose embeddings are most similar to the question embedding.

The most relevant chunks are returned to the application.

Generation

The retrieved chunks are added to the context sent to a language model.

The language model uses the retrieved context and the user's question to generate an answer.

Sources

A RAG system can keep metadata about every chunk, including the original document name.

This allows the application to show which documents were used to generate an answer.

Hallucinations

Language models can generate information that is incorrect or unsupported.

A RAG system can reduce this problem by instructing the model to answer using the retrieved context.

If the knowledge base does not contain enough relevant information, the application should avoid inventing an answer.