Retrieval-augmented generation
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A language model only knows the text it was trained on, so it cannot answer from your own documents, and when it does not know it may still answer fluently. Retrieval-augmented generation (RAG) adds a lookup: split your documents into chunks, turn each chunk into a vector with an embedding model, find the chunks closest to the question by cosine similarity, and paste them into the prompt. Follow one question through a tiny, runnable Python pipeline.
Ask the model directly
A large language model (LLM) learned from public text up to a cutoff date. It never read this shop's rules, so for "Can I return an item after 20 days?" it can only guess. A fluent answer with no source is a hallucination.
question Can I return an item after 20 days? the LLM knows only what was in its training text: public pages, up to a cutoff date not this shop's policy, not last week's changes answer "Most shops allow 14 days. Maybe?" (a guess)
اقرأ الدرس خطوة بخطوة
Ask the model directly
A large language model (LLM) learned from public text up to a cutoff date. It never read this shop's rules, so for "Can I return an item after 20 days?" it can only guess. A fluent answer with no source is a hallucination.
question Can I return an item after 20 days? the LLM knows only what was in its training text: public pages, up to a cutoff date not this shop's policy, not last week's changes answer "Most shops allow 14 days. Maybe?" (a guess)RAG: look it up first
Retrieval-augmented generation (RAG) adds a lookup step. Retrieve: find the few passages of your own documents that match the question. Augment: paste them into the prompt. Generate: the model answers from them. No retraining needed.
retrieve search your documents for the question augment paste the best passages into the prompt generate the LLM answers, reading those passages two memories (Lewis et al., 2020): parametric what the weights learned in training non-parametric a document index you can editSplit documents into chunks
First the documents are split into chunks: short passages that can be found and pasted on their own. Ours are four one-line chunks. The original RAG paper split Wikipedia into 21 million chunks of 100 words.
chunks: 0 Refunds: return any item within 30 days for your money ba 1 Shipping: orders arrive in 3 to 5 days. 2 Support hours: open 9am to 5pm, Sunday to Thursday. 3 Gift cards never expire. too long: wastes prompt space · too short: loses meaningEmbed every chunk
An embedding model turns each chunk into a vector, a list of numbers, so that texts about the same thing get similar vectors. Ours counts topic words, giving four numbers. Real ones are trained networks giving hundreds, such as 384.
vecs = [embed(d) for d in docs] topics ret ship hrs gift refunds [3, 1, 0, 0] shipping [0, 3, 0, 0] hours [0, 0, 3, 0] gifts [0, 0, 0, 3] stored once, ahead of time: the vector indexEmbed the question
When a question comes in, the same embedding model turns it into a vector too. "return" and "days" give [1, 1, 0, 0]. It must be the same model, or the two kinds of vector could not be compared.
q = embed(question) "Can I return an item after 20 days?" return -> ret · days -> ship q = [1, 1, 0, 0]Find the closest chunks
Search scores every chunk by cosine similarity with the question: 1 means the vectors point the same way, 0 means no topic in common. Refunds scores 0.89, shipping 0.71, the other two 0. We keep the top k = 2.
cosine(q, v) = q·v / (|q| |v|) refunds 4 / (1.41 × 3.16) = 0.89 shipping 3 / (1.41 × 3.00) = 0.71 hours 0 / (1.41 × 3.00) = 0.00 gifts 0 / (1.41 × 3.00) = 0.00 hits = top 2: refunds, shippingPaste them into the prompt
Augment: the two retrieved chunks and the question are pasted into one prompt, with an instruction to answer only from that context. The model itself does not change at all; only what it reads does.
Answer using only this context. Context: - Refunds: return any item within 30 days for your money back. - Shipping: orders arrive in 3 to 5 days. Question: Can I return an item after 20 days?Generate a grounded answer
The LLM reads the prompt and answers from it: yes, returns are accepted within 30 days, so 20 days is fine. It can name its source, the refunds chunk. The shipping chunk was retrieved too, but it is not needed.
llm(prompt) -> "Yes: returns are OK within 30 days." source: refunds grounded: every claim can be checked in the contextChange documents, not weights
If the refund rule changes, edit that chunk and embed it again; the next answer follows. No retraining. The weak spot is search: if it fetches the wrong chunks, the model answers from the wrong facts.
policy changes -> edit docs[0] -> vecs[0] = embed(docs[0]) the LLM weights stay exactly the same limits: wrong chunks retrieved -> wrong or missing answer the model can still ignore or misread the context
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A shop changed its refund window last week. Why can't a plain LLM reliably answer questions about the new rule?
A model's knowledge comes from its training text, collected up to a cutoff date. It never saw this shop's private, recent policy, so any answer is a guess, and a fluent guess with no source is a hallucination.
02In RAG, what is stored in the vector index?
Ahead of time, each chunk goes through the embedding model and its vector is stored. At question time the question's vector is compared against these.
03The question vector is [1, 1, 0, 0] and a chunk's vector is [0, 2, 0, 0]. What is their cosine similarity?
Dot product 1·0 + 1·2 = 2. Lengths: √2 and 2. So 2 / (√2 × 2) = 1/√2 ≈ 0.71. Only the direction matters, not the length.
04Why must the question be embedded with the same embedding model as the chunks?
Similarity only means something when both vectors live in the same space. A vector from another model uses different numbers for the same meaning.
05The refund rule changes again. What is the RAG way to update the system?
The knowledge lives in the documents, not the weights. Edit the chunk, re-embed it, and the next retrieval finds the new text. The LLM is unchanged.
المسرد
- Retrieval-augmented generation (RAG)
- Answering with an LLM after first retrieving relevant passages from a document collection and adding them to the prompt.
- Hallucination
- Fluent, confident text from a model that is not supported by any source, or is simply false.
- Chunk
- A short passage cut from a longer document, small enough to be found and pasted into a prompt on its own.
- Embedding model
- A model that turns a text into a vector (a list of numbers) so that texts with similar meaning get similar vectors.
- Vector index
- The stored vectors of every chunk, organised so the ones closest to a query vector can be found quickly.
- Cosine similarity
- The dot product of two vectors divided by the product of their lengths: 1 when they point the same way, 0 when they share nothing (for non-negative vectors).
- Top k
- The k chunks with the highest similarity scores; these are the ones pasted into the prompt.
- Parametric vs non-parametric memory
- What a model knows in its weights, versus knowledge kept in an external document index that can be edited without retraining.
الملاحظات والمصادر
- The embedding here is a toy: four numbers, each counting words that start with a topic stem. Real embedding models are trained neural networks; all-MiniLM-L6-v2, for example, gives 384 numbers, and no single number means one named topic.
- With four chunks we can compare against every vector. With millions, vector databases use approximate nearest-neighbour search (for example FAISS) to find the top k quickly.
- The answers in the figure are illustrations of what a model typically does, not the output of a real model.
- The Python program in the lesson is real and needs no libraries: run it and it prints the finished prompt, ready to send to any chat model.
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (NeurIPS 2020)
- Karpukhin et al., Dense Passage Retrieval for Open-Domain Question Answering (EMNLP 2020)
- Jurafsky & Martin, Speech and Language Processing (3rd ed. draft), ch. 5: Embeddings (Aug 2026 draft; cosine similarity)
- Jurafsky & Martin, Speech and Language Processing (3rd ed. draft), ch. 11: Information Retrieval and RAG (Aug 2026 draft)
- Reimers & Gurevych, Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (2019)
- sentence-transformers/all-MiniLM-L6-v2 model card: 384-dimensional sentence embeddings
- Johnson, Douze & Jégou, Billion-scale similarity search with GPUs (FAISS, 2017)
- Ji et al., Survey of Hallucination in Natural Language Generation (ACM Computing Surveys, 2023)
- Python documentation: math.hypot
اختبار يتاح بعد الخطوة الأخيرة.