Sub topic 6
Retrieval-augmented generation by hand
This chapter assumes you can write basic Python, have called a chat API, and know what an embedding is: a list of numbers that places a piece of text in a space where similar meanings sit close together. You will build a small retrieval-augmented generation (RAG) pipeline with only the OpenAI SDK and NumPy. Later chapters compare it with what LlamaIndex and LangChain do for you, so you need to see the parts first.
What RAG does
A model only knows what was in its training data and what you put in the prompt. RAG fills the prompt with relevant text from your own documents before the model answers. The pipeline has two phases.
- Indexing runs once, or whenever the documents change. You split documents into chunks, embed each chunk, and store the vectors.
- Querying runs on every question. You embed the question, find the chunks whose vectors are closest, put them in the prompt, and ask the model to answer from them.
Nothing here needs a framework. Each box is a short function.
Step 1: Chunking
Models and embedding endpoints have input limits. Retrieval also works better on focused passages than on whole documents, because a vector for a 40-page file blurs many topics together. A chunk is a slice of a document sized to carry one idea.
The simplest strategy is a fixed character window with overlap. The overlap keeps a sentence that straddles a boundary intact in at least one chunk.
def chunk_text(text: str, size: int = 800, overlap: int = 100) -> list[str]:
if overlap >= size:
raise ValueError("overlap must be smaller than size")
chunks = []
start = 0
while start < len(text):
piece = text[start:start + size].strip()
if piece:
chunks.append(piece)
start += size - overlap
return chunksCharacter windows are crude. They cut words and sentences in half. Better splitters break on paragraphs, then sentences, and only fall back to characters. Frameworks ship these splitters, and they are one of the clearest things you get from them.
Step 2: Embedding and storing
The SDK's embeddings endpoint takes a list of strings and returns one vector per string. For a few thousand chunks, a NumPy matrix is a fine vector store.
import numpy as np
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
EMBED_MODEL = "text-embedding-3-small"
CHAT_MODEL = "gpt-4o-mini"
def embed(texts: list[str]) -> np.ndarray:
response = client.embeddings.create(model=EMBED_MODEL, input=texts)
vectors = np.array([item.embedding for item in response.data], dtype=np.float32)
# Normalize so a dot product equals cosine similarity.
return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)Two details matter here.
- Normalizing. Cosine similarity compares direction, not length. If every vector has length 1, a plain dot product gives the cosine, and one matrix multiplication scores every chunk at once.
- Batching. The endpoint caps how many inputs one request may carry and how many tokens in total. For a large corpus, send the chunks in batches (for example 100 at a time) and stack the results with
np.vstack.
Step 3: Retrieval
Retrieval embeds the question with the same model used for the chunks. Vectors from different embedding models are not comparable, even when their lengths match. Then you rank chunks by score and keep the top few.
def retrieve(query: str, chunks: list[str], matrix: np.ndarray, k: int = 3) -> list[tuple[float, str]]:
query_vector = embed([query])[0]
scores = matrix @ query_vector # one score per chunk
top = np.argsort(scores)[::-1][:k] # indices of the k highest scores
return [(float(scores[i]), chunks[i]) for i in top]The value k is a trade-off. A small k risks missing the passage that holds the answer. A large k adds noise, costs more tokens, and can bury the useful passage in the middle of a long prompt.
Step 4: Generation
The last step puts the retrieved text in the prompt and tells the model to stay inside it. This instruction is the main defense against the model answering from memory when retrieval fails.
def answer(question: str, chunks: list[str], matrix: np.ndarray, k: int = 3) -> str:
hits = retrieve(question, chunks, matrix, k)
context = "\n\n".join(f"[{n}] {text}" for n, (_, text) in enumerate(hits, start=1))
response = client.chat.completions.create(
model=CHAT_MODEL,
temperature=0,
messages=[
{
"role": "system",
"content": (
"Answer using only the numbered context passages. "
"Cite passage numbers like [1]. "
"If the context does not contain the answer, say you don't know."
),
},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
],
)
return response.choices[0].message.contentRunning the whole pipeline
This script ties the pieces together with sample text so you can run it as shown. It assumes the functions above are defined in the same file.
documents = [
"Access requests: submit a ticket in the IT portal. Your manager must approve it "
"before access is granted. Approval usually takes two business days.",
"Laptops: new hires receive a laptop on their first day. Report loss or theft to "
"security within 24 hours.",
"Expenses: submit receipts within 30 days. Meals are reimbursed up to 40 dollars per day.",
]
chunks = [piece for doc in documents for piece in chunk_text(doc, size=300, overlap=50)]
matrix = embed(chunks) # indexing: do this once and reuse the result
print(answer("Who approves access requests?", chunks, matrix, k=2))
print(answer("What is the capital of Peru?", chunks, matrix, k=2))The first question should be answered with a citation. The second should get "I don't know", because no chunk covers it. Run both. The second one shows whether your grounding instruction works.
What you wrote, and what a framework calls it
| Stage | Your code | Typical framework name |
|---|---|---|
| Load files | `open(...).read()` | Document loader, reader |
| Split | `chunk_text` | Text splitter, node parser |
| Embed | `embed` | Embedding model wrapper |
| Store | NumPy matrix | Vector store |
| Search | `retrieve` | Retriever |
| Prompt and call | `answer` | Query engine, retrieval chain |
The LlamaIndex example from the plan, VectorStoreIndex.from_documents(documents) followed by as_query_engine(), performs all six rows in two lines. That saving is real, but it also hides the choices you just made: the chunk size, k, the prompt, and the embedding model.
Limits of the by-hand version
Know these before you decide whether to keep it.
- Persistence. The matrix lives in memory. Save it with
np.saveand the chunks as JSON, or move to a vector database when the corpus grows. Brute-force scoring over a few hundred thousand vectors is still fast, but memory and re-indexing time become the problem first. - File formats. PDFs, HTML, and slide decks need parsers. This is usually the largest source of hand-written code in a real project, and the area where framework loaders save the most time.
- Updates. When a document changes, you must find and replace its chunks. Track a document ID and a content hash for each chunk. Re-embedding everything is simple but costs money.
- Retrieval quality. Pure vector search misses exact terms such as error codes and product names. Hybrid search combines keyword scoring with vectors. Reranking, where a second model reorders the top results, often improves answers more than changing the embedding model does.
- Evaluation. A pipeline that returns fluent answers can still retrieve the wrong passages. Keep a small set of questions with the passages that should be retrieved, and measure how often they appear in the top
k.
Why this matters for the framework decision
The by-hand pipeline is about 50 lines. That is small enough to read, test, and debug completely, and every prompt the model sees is a string you built. Its weak points are the parts around the core: loaders, splitters, stores, and updates. A framework earns its place when you need many of those pieces, and it costs you transparency about what is sent and when. Later chapters return to this trade-off. For now, keep this pipeline as a baseline to compare against.
Exercise
You change the embedding model from text-embedding-3-small to a different model, but you only re-embed the user's question and leave the stored chunk vectors alone. The script runs without errors. What goes wrong, and how do you fix it?
Show answer
The question vector and the chunk vectors now come from different models, so they live in different vector spaces (and may even have different lengths, which would raise a shape error in the matrix multiplication). Scores are meaningless and the top chunks are effectively random. Fix it by re-embedding all chunks with the new model and rebuilding the matrix before querying. Store the model name alongside the saved vectors so a mismatch can be detected.
Exercise
Your pipeline answers "I don't know" to a question whose answer is in your documents. Name two places to look first, and what you would print or change in each.
Show answer
First, retrieval: print the top-k chunks and scores for that question. If the right passage is missing, try a larger k, smaller or better-split chunks, a keyword or hybrid search step, or a reranker. Second, chunking: check whether the answer was split across a chunk boundary and increase the overlap or split on paragraph boundaries. If the right passage is retrieved but the model still declines, review the system prompt, since it may be too strict, or the context may be too noisy.