Sub topic 7
Inside a retrieval pipeline
This chapter assumes you can call a chat-style LLM API and read Python. It also assumes you know that an embedding is a vector of numbers representing meaning, and that a context window limits how much text a model can read at once.
The two phases
A retrieval pipeline has an offline phase and a query-time phase. The offline phase prepares your documents. The query-time phase finds the best passages for each question and puts them in the prompt.
Chunking
Embedding a whole manual as one vector blurs every topic together. Embedding single sentences loses context. So you split documents into chunks, usually a few hundred words each, and overlap neighboring chunks so a fact that crosses a boundary appears intact in at least one of them.
def chunk(text, size=200, overlap=40):
words = text.split()
if not words:
return []
step = size - overlap
return [
" ".join(words[i:i + size])
for i in range(0, max(len(words) - overlap, 1), step)
]
doc = " ".join(f"w{i}" for i in range(500))
pieces = chunk(doc)
print(len(pieces)) # 3 chunks, each overlapping the next by 40 wordsSplitting on natural boundaries such as headings and paragraphs usually beats fixed word counts. Keep the source name and section title with each chunk so you can cite it later.
Embedding and ranking
Each chunk is embedded once and stored with its vector. At query time you embed the question with the same embedding model, then rank chunks by cosine similarity. Cosine similarity compares the direction of two vectors and ignores their length. The following code is the core of the ranking step, with toy two-dimensional vectors standing in for real embeddings:
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
def top_k(query_vec, chunks, k=3):
# chunks is a list of (text, vector) pairs
ranked = sorted(chunks, key=lambda c: cosine(query_vec, c[1]), reverse=True)
return [text for text, _ in ranked[:k]]
chunks = [
("Refunds take 5 days.", [0.9, 0.1]),
("The app supports dark mode.", [0.1, 0.9]),
]
print(top_k([0.8, 0.2], chunks, k=1)) # ['Refunds take 5 days.']This brute-force scan is fine for thousands of chunks. For millions, a vector database or approximate nearest-neighbor index trades a little accuracy for much lower latency.
Building the grounded prompt
The final step places the retrieved text in the prompt and tells the model to stay within it.
def grounded_prompt(question, passages):
context = "\n\n".join(passages)
return (
"Answer using only the context below. "
"If the answer is not in the context, say you don't know.\n\n"
"Context:\n" + context + "\n\nQuestion: " + question
)The "say you don't know" instruction matters. Without it, the model often fills gaps from its own memory, which defeats the purpose of grounding.
Common errors
- Mixing embedding models. Vectors from different models are not comparable. Re-embed everything when you change models.
- Chunks too large or too small. Large chunks dilute the match and waste context window. Small chunks lose the surrounding facts.
- Fixed k for every query. Too small a k misses the answer. Too large a k adds noise. Tune k against your evaluation set.
- Blaming the model for retrieval misses. If the right chunk is not in the top k, the model cannot use it. Check retrieval separately from generation.
Exercise
A user asks about a refund policy, but the model answers incorrectly. The policy text is indexed, yet it never appears in the top 3 results. Name one change to the pipeline that might fix this, and explain why changing the prompt would not.
Show answer
Adjust retrieval, for example by using smaller chunks with overlap, raising k, or using a better embedding model. The model only sees what retrieval returns, so if the policy chunk is missing from the prompt, no prompt wording can make the model use it.