Sub topic 6
Retrieval-augmented generation by hand
This chapter assumes you can call a chat API, read JSON, and write basic Python. It also assumes you know roughly what an embedding is: a list of numbers that represents the meaning of a text, so that similar texts have nearby vectors. You will build a small retrieval-augmented generation (RAG) pipeline with only the provider SDK and NumPy. Seeing each step makes it clear what a framework like LlamaIndex later automates.
The pipeline in five steps
RAG answers a question using your own documents. The model has not seen those documents, so your code finds the relevant passages and puts them in the prompt.
Indexing runs once, or whenever the documents change. The query phase runs for every question.
Indexing: chunk and embed
Chunking splits long text into pieces small enough to embed and to fit in a prompt. The simplest approach is a fixed size with some overlap, so a sentence cut at one boundary still appears whole in the next chunk.
import numpy as np
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def chunk(text, size=500, overlap=50):
step = size - overlap
return [text[i:i + size] for i in range(0, len(text), step)]
def embed(texts):
response = client.embeddings.create(
model="text-embedding-3-small",
input=texts,
)
return np.array([item.embedding for item in response.data])
documents = [
"Access requests are filed through the IT portal. A manager must approve each request.",
"New hires receive a laptop on day one. Laptops are returned when employment ends.",
]
chunks = [c for doc in documents for c in chunk(doc)]
vectors = embed(chunks) # shape: (number of chunks, embedding size)The "store" here is the NumPy array vectors. A real system would use a vector database, but for a few thousand chunks an array is enough.
Querying: search and generate
To find relevant chunks, embed the question with the same model and compare it to every chunk. Cosine similarity measures the angle between two vectors. OpenAI embeddings are normalized to length 1, so a dot product gives the same result.
def retrieve(question, k=2):
query_vector = embed([question])[0]
scores = vectors @ query_vector
top = np.argsort(scores)[::-1][:k]
return [chunks[i] for i in top]
def answer(question):
context = "\n\n".join(retrieve(question))
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "Answer using only the context. 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.contentWho approves access requests?"))The whole pipeline is about 30 lines. Every decision is visible: chunk size, of results, and the exact prompt text.
Common errors
- Mixing embedding models. Vectors from different models are not comparable. Use the same model for chunks and questions, and re-embed everything if you change it.
- Chunks that are too large or too small. Large chunks dilute the match with unrelated text. Tiny chunks lose the surrounding meaning.
- Re-embedding on every run. Embedding costs money and time. Save
vectorsto disk, for example withnp.save, and reload them. - No fallback instruction. Without "say you don't know," the model may invent an answer when retrieval returns weak matches.
What this shows about frameworks
The hand-written version leaves several jobs to you: file loaders for PDFs and web pages, smarter chunking, persistent vector storage, and re-indexing when files change. These are the areas where LlamaIndex saves the most code, as a later chapter shows.
Exercise
Your RAG pipeline returns confident but irrelevant answers for some questions. Name the first thing to inspect, and why.
Show answer
Inspect the retrieved chunks and their similarity scores for those questions. The model only sees what retrieval returns, so irrelevant context points to a retrieval problem such as poor chunking or a mismatched embedding model. Changing the prompt or the chat model will not fix it.
Exercise
Why must the question and the chunks be embedded with the same model?
Show answer
Each embedding model maps text into its own vector space. Vectors from two different models are not comparable, so the similarity scores would be meaningless.