Sub topic 1
Why Models Need Outside Knowledge
Prerequisites
This chapter assumes basic Python, familiarity with prompts and large language models, and basic knowledge of vectors, dot products, APIs, and JSON.
Why Models Need Outside Knowledge
A language model learns patterns from its training data. Its knowledge may be outdated, incomplete, or unrelated to your private documents. It also cannot reliably remember every detail from training.
Retrieval-augmented generation (RAG) gives the model relevant passages at question time. The system retrieves those passages from an external source and places them in the prompt. The model then generates an answer using that context.
The RAG Pipeline at a Glance
A typical pipeline loads documents, cleans them, splits them into chunks, creates an embedding for each chunk, and stores the embeddings. For a question, it embeds the question, finds similar chunks, and adds them to the model prompt.
RAG, Fine-Tuning, and Long Context
RAG is usually a good fit for changing facts, private data, and answers that should cite source passages. Updating the source or search index can update the system without retraining the model.
Fine-tuning changes model behavior by training on examples. Use it for style, formatting, or specialized task behavior. It is usually a poor way to store frequently changing facts.
A long-context prompt can include many documents directly. This is simple, but it can increase cost and latency. The model may also overlook important details. RAG reduces the prompt to passages likely to matter.
Loading and Cleaning Source Documents
Ingestion is the process of preparing source data for search. Load files or API records, extract useful text, remove repeated headers and navigation, normalize whitespace, and preserve metadata such as title, date, and access permissions.
Splitting Documents into Chunks
A chunk is a searchable piece of a document. Chunks that are too large contain unrelated ideas. Chunks that are too small lose context. Overlap repeats characters or tokens at boundaries, reducing the chance that a sentence is split between chunks.
def chunk_text(text, size=500, overlap=50):
if not 0 <= overlap < size:
raise ValueError("overlap must be in [0, size)")
step = size - overlap
chunks = []
for start in range(0, len(text), step):
chunks.append(text[start:start + size])
if start + size >= len(text):
break
return chunksTurning Text into Embeddings
An embedding is a vector representing the meaning of text. An embedding model maps similar meanings to nearby vectors. Store each chunk's vector with its text and metadata. Later chapters use vector similarity to retrieve relevant chunks.
Exercise
When should you prefer RAG over fine-tuning for a policy manual that changes weekly?
Show answer
Prefer RAG because the indexed source can be refreshed without retraining the model.