Sub topic 12
Using a vector database for retrieval-augmented generation
This chapter assumes you know what embeddings are, how cosine similarity ranks vectors, and how a vector index returns approximate nearest neighbors. It covers how those pieces fit into retrieval-augmented generation (RAG).
What RAG does
A language model only knows what was in its training data and what you put in its prompt. Retrieval-augmented generation fills the prompt with relevant text fetched at question time. A vector database does the fetching.
The flow has two phases:
- Indexing (offline): split documents into chunks, embed each chunk, and store the vector, the chunk text and metadata.
- Query (online): embed the question, retrieve the top-k nearest chunks, put them in the prompt, and ask the model to answer from them.
Chunking
Embedding a whole document blurs its topics into one vector. Embedding single sentences loses context. Most systems use chunks of a few hundred tokens with a small overlap, so a fact cut at a boundary still appears whole in one chunk.
Store the source document ID, title and position with each chunk. You need them for filtering, citations and re-indexing.
A minimal retrieval step
The code below uses the exact search from earlier chapters. The embed function is a stand-in that produces random vectors, so the example runs without a model. Replace it with a real embedding model, and use the same model for chunks and queries.
import numpy as np
def embed(texts):
# Placeholder: swap in a real embedding model.
out = []
for t in texts:
seed = abs(hash(t)) % (2**32)
out.append(np.random.default_rng(seed).normal(size=64))
return np.array(out, dtype="float32")
def normalize(x):
return x / np.linalg.norm(x, axis=-1, keepdims=True)
chunks = [
"HNSW is a graph index.",
"IVF partitions vectors into clusters.",
"Product quantization compresses vectors.",
]
index = normalize(embed(chunks))
def retrieve(question, k=2):
scores = index @ normalize(embed([question]))[0]
top = np.argsort(-scores)[:k]
return [(chunks[i], float(scores[i])) for i in top]
def build_prompt(question, k=2):
context = "\n".join(f"- {text}" for text, _ in retrieve(question, k))
return (
"Answer using only the context below. "
"If the answer is not there, say you do not know.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
print(build_prompt("What does IVF do?"))With the random placeholder, the retrieved chunks are meaningless. With a real model, the IVF chunk would rank first.
Where the database matters
A real RAG system needs more than the nearest-neighbor call:
- Metadata filters restrict results by tenant, document type, date or access rights. Access control is the most important use. Filter by permission inside the query, not after generation.
- Hybrid search helps when questions contain exact terms such as product codes or error messages, which embeddings often match poorly.
- Updates and deletes keep the index current when documents change. Store a document ID so you can delete all chunks of an edited document and re-insert them.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Answer ignores the right document | The chunk was never retrieved | Check recall on test questions; adjust chunk size, k or index parameters |
| Answer is wrong but fluent | Irrelevant chunks filled the prompt | Lower k, add a similarity threshold, or re-rank results |
| Right fact is missing | It was split across chunks | Increase overlap |
| Results look random | Different embedding models for chunks and queries | Use one model and re-embed after changing it |
Debug retrieval separately from generation. If the correct chunk is not in the top-k, no prompt change will fix the answer.
Exercise
Users report that the assistant sometimes answers with outdated policy text after a document was edited. What is the likely cause in the retrieval layer, and how do you fix it?
Show answer
The old chunks of the edited document are still in the index. Store a document ID with every chunk. When a document changes, delete all chunks with that ID, then embed and insert the new chunks.
Exercise
Why should you test retrieval on its own before changing the prompt?
Show answer
If the correct chunk is not among the top-k results, the model cannot use it, so prompt changes cannot help. Measuring whether the right chunk is retrieved shows whether the fault is in retrieval or in generation.