What LLMs and RAG are and how they work
A large language model (LLM) is a transformer model that predicts the next token from a text. Retrieval-augmented generation (RAG) is an approach in which the model receives document fragments found in your own data before it answers.
A token is the unit of text the model works with (see the “Tokenization” section). A base model continues text; a chat model, fine-tuned on dialogues, expects its input as a chat template: messages with roles and content. A single flat string gives a worse answer. The prompt and the answer together must fit in the context window, the model’s limit in tokens. How the model works inside and what its size means are covered in the AI models reference.
Why RAG
A model’s knowledge is frozen at its training date: it knows nothing about recent events and has never seen your company’s internal documents. RAG closes both gaps. Before generation, the retrieved fragments are inserted into the prompt, the answer is based on them, and it can be checked against the source. This makes answers more factual, and knowledge is updated by replacing the index, with no retraining.
| Approach | What changes | Cost | When to choose it |
|---|---|---|---|
| RAG | the vector index and the prompt; model weights are untouched | rebuilding the index when documents change | fresh or private documents; answers checked against the source |
| Adapter fine-tuning (PEFT) | a small number of added parameters (the adapter) | much less memory than full fine-tuning; the adapter is easy to store and share | you need behaviour or an answer format that a prompt cannot achieve |
| Full fine-tuning | all model weights | a lot of memory and compute: the optimiser stores state for every parameter | when prompts and adapters are not enough |
Choose RAG when the problem is knowledge, and fine-tuning when it is the model’s behaviour: style, answer format or language. How to fine-tune a model and how much memory it takes — see the AI models reference, the section “Fine-tuning: full, LoRA and QLoRA”.
Two pipelines
A RAG system is built from two pipelines. The indexing pipeline prepares the knowledge base and runs whenever documents are updated; the query pipeline runs for every user question. They share the vector index: the first fills it and the second reads it.
- Documents are loaded and split into fragments (chunks) along paragraph and heading boundaries, so that no idea is cut off mid-way.
- An embedding model turns each chunk into a vector, a list of numbers that reflects the meaning of the text.
- The vectors are written to a vector index, a store that quickly finds the nearest vectors.
- The user’s question is turned into a vector by the same embedding model.
- Search returns the
top-knearest chunks from the index. - Reranking picks the most relevant of them: a model compares the question and a chunk more precisely by looking at them together.
- The retrieved chunks and the question are assembled into a prompt with context.
- The LLM generates an answer based on those chunks.
The quality of the answer depends on the quality of what is retrieved: the LLM relies only on the chunks that reach the prompt. An overloaded prompt drowns the model in information (lost in the middle), and a missed fragment never makes it into the answer. The stages are covered in the “Embeddings”, “Indexing and vector search” and “Search and reranking” sections. The index itself can be stored in PostgreSQL with the pgvector extension; see the PostgreSQL reference.
Where to run it
Transformers works with PyTorch and runs locally. You need Python 3.11+ and PyTorch 2.6+; an NVIDIA GPU speeds things up, and large models can be fitted into memory with 4-bit quantisation. Install the library in a virtual environment:
uv venv .envsource .env/bin/activateuv pip install "transformers[torch]"Run a ready-made model with the pipeline function: it tokenises the input, calls the model and decodes the output on its own. For chat models, pass a list of messages rather than a single string:
from transformers import pipeline # a chat model expects messages with roles, not a single stringpipe = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct")messages = [{"role": "user", "content": "What is RAG?"}]out = pipe(messages, max_new_tokens=100)print(out[0]["generated_text"])Finding relevant fragments is a classic machine learning task; its basics are in the “Machine learning fundamentals” reference.
Section sources
the section is written from these pages- Text generationhuggingface.co/docs/transformers/llm_tutorial(opens in a new tab)
- Advanced RAG on Hugging Face documentation using LangChainhuggingface.co/learn/cookbook/advanced_rag(opens in a new tab)
- RAGhuggingface.co/docs/transformers/model_doc/rag(opens in a new tab)
- Parameter-efficient fine-tuninghuggingface.co/docs/transformers/peft(opens in a new tab)
- Installationhuggingface.co/docs/transformers/installation(opens in a new tab)
- Pipelineshuggingface.co/docs/transformers/main_classes/pipelines(opens in a new tab)