Sub topic 5
Retrieval and Context Assembly as Part of the Pipeline
This chapter assumes you have read the earlier chapters on the anatomy of an LLM app and on versioning prompts. It also assumes you know what an embedding is (a vector that represents the meaning of a text) and have used a vector search or keyword search library at least once.
Retrieval-augmented generation (RAG) is a pattern where the app looks up relevant documents at request time and places them in the prompt. The model answers from that text instead of from memory alone. For operations, the key point is that retrieval is a second pipeline sitting in front of the model. It has its own data, configuration, failure modes, and metrics. If you version only the prompt, you have versioned half of what determines the answer.
Two pipelines, one answer
A RAG app runs two flows that meet inside the prompt.
- Ingestion runs offline or on a schedule. It loads documents, splits them into chunks, computes embeddings, and writes them to an index.
- Query time runs on every request. It turns the user's question into a search, retrieves candidates, filters them, fits them into a token budget, and builds the final prompt.
This is why the earlier idea of the model as a dependency needs extending. Your app also depends on an index you build and keep fresh. Classic MLOps has a close relative in feature pipelines, but there is a difference. A bad feature usually shifts a number. A bad retrieved chunk changes the text the model reads, and the model may repeat it confidently.
What belongs in the retrieval configuration
Treat every setting that changes which text reaches the model as a versioned artifact, in the same way as the PromptVersion from the previous chapter.
| Setting | What it controls | What goes wrong if it silently changes |
|---|---|---|
| Embedding model | How text maps to vectors | Query vectors and stored vectors no longer match, so results become near-random |
| Chunk size and overlap | How much text each chunk holds | Large chunks waste tokens. Small chunks lose the surrounding sentence that gave a fact its meaning |
| Top-k | How many candidates are returned | Too few misses the answer. Too many adds noise and cost |
| Minimum score | Cutoff for weak matches | Without it, the model is handed irrelevant text and tries to use it |
| Context token budget | Space reserved for retrieved text | Truncation drops chunks without anyone noticing |
| Index snapshot or build ID | Which data the index holds | Answers change because documents changed, not because code changed |
The embedding model deserves special attention. If you change it, you must re-embed every document. A mixed index, where some vectors come from the old model and some from the new, gives results that look plausible and are wrong.
Context assembly is a real step
Between "search returned hits" and "the prompt was sent" there is a step that is easy to leave implicit: context assembly. It decides which chunks are kept, in what order, how they are labeled, and what happens when they do not fit.
Common decisions in this step:
- Filtering by score. Drop hits below a minimum similarity score. It is usually better to give the model less text than to give it irrelevant text.
- Deduplication. Overlapping chunks and repeated documents waste budget.
- Budgeting. Reserve tokens for the system prompt, the question, and the answer. Give the rest to context. Counting tokens with the model's own tokenizer is more accurate than the rough estimate used below.
- Ordering. Models often use information at the start and end of a long context better than information in the middle. Put the strongest chunks where they are most likely to be used, and check this with your own evaluation set.
- Labeling. Give every chunk a stable ID in the prompt so the model can cite it and your logs can record it.
- The empty case. If nothing passes the filter, say so explicitly in the prompt or skip generation. Do not send an empty context block and hope.
The following code makes these decisions explicit and returns a record you can log. It is complete and runs as shown.
import hashlib
import json
from dataclasses import dataclass, asdict
@dataclass(frozen=True)
class RetrievalConfig:
index_name: str
embedding_model: str
chunk_size: int
chunk_overlap: int
top_k: int
min_score: float
context_token_budget: int
@property
def config_id(self) -> str:
raw = json.dumps(asdict(self), sort_keys=True)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
def estimate_tokens(text: str) -> int:
# Rough rule of thumb: about 4 characters per token for English.
return max(1, len(text) // 4)
def assemble_context(hits, config):
"""hits: list of dicts with chunk_id, text, score."""
kept, dropped, used = [], [], 0
ranked = sorted(hits, key=lambda h: h["score"], reverse=True)[: config.top_k]
for hit in ranked:
if hit["score"] < config.min_score:
dropped.append({"chunk_id": hit["chunk_id"], "reason": "low_score"})
continue
cost = estimate_tokens(hit["text"])
if used + cost > config.context_token_budget:
dropped.append({"chunk_id": hit["chunk_id"], "reason": "budget"})
continue
kept.append(hit)
used += cost
context = "\n\n".join(f"[{h['chunk_id']}] {h['text']}" for h in kept)
return {
"context": context,
"retrieval_config": config.config_id,
"kept": [h["chunk_id"] for h in kept],
"dropped": dropped,
"context_tokens": used,
}
config = RetrievalConfig(
index_name="support-kb",
embedding_model="example-embed-2026-01",
chunk_size=400,
chunk_overlap=50,
top_k=3,
min_score=0.5,
context_token_budget=40,
)
hits = [
{"chunk_id": "kb-12", "score": 0.91, "text": "Refunds take 5 business days. " * 3},
{"chunk_id": "kb-30", "score": 0.84, "text": "Duplicate charges are reversed automatically. " * 2},
{"chunk_id": "kb-77", "score": 0.31, "text": "Our office dog is named Biscuit."},
]
result = assemble_context(hits, config)
print(json.dumps({k: v for k, v in result.items() if k != "context"}, indent=2))Running it keeps kb-12, drops kb-30 because it would exceed the 40-token budget, and drops kb-77 for a low score. The second drop is the kind of event that normally goes unseen. Because the function returns the dropped chunks and their reasons, a missing answer can be traced to a budget decision instead of blamed on the model.
Log what was retrieved
In the tracing chapter you will log latency and token counts for each model call. For RAG apps, add the retrieval side to the same trace:
- the retrieval config ID and the index build ID,
- the query actually sent to the search (which may be a rewritten version of the user's question),
- the IDs and scores of the chunks kept and dropped,
- the number of context tokens.
Chunk IDs are usually enough. Storing full chunk text in every log line is expensive and may copy sensitive data into your logging system. Store the IDs and look up the text from the index snapshot when you need it.
Separating retrieval quality from generation quality
When a RAG answer is wrong, there are two broad causes, and the fixes are different.
- Retrieval failed. The needed chunk was never in the context. Changing the prompt will not help.
- Generation failed. The right chunk was in the context, and the model ignored it, misread it, or added claims of its own.
Evaluate the two separately. For retrieval, build a set of questions where you have marked which chunks should be returned. Then measure recall at k: the share of questions where at least one correct chunk appears in the top k results. For generation, hold the retrieved context fixed and score the answers, for example with the programmatic checks and model-graded scoring covered in the evaluation chapter. A single end-to-end score hides which half broke.
Useful retrieval checks include:
- the right chunk appears in the top k,
- an out-of-scope question returns nothing above the minimum score,
- a question about a document updated yesterday retrieves the new version, not the old one.
Common failure modes
| Symptom | Likely cause | First thing to check |
|---|---|---|
| Answers cite outdated policy | Stale index, or old and new document versions both indexed | Index build ID and document timestamps in the trace |
| Fluent answer with no support in the documents | Nothing relevant retrieved, and no empty-context rule | Kept chunks and scores for that request |
| Quality drops after an unrelated deploy | Embedding model or chunking changed | Retrieval config ID in the trace |
| Correct chunk retrieved but not used | Context too long, or the chunk sits in the middle | Chunk order and context token count |
| Cost rises with no traffic change | Top-k or chunk size increased | Context tokens per request over time |
| Users see data they should not | Retrieval ignores access control | Whether filters on user or tenant run inside the search |
The last row is a security issue as well as a quality issue. Apply permission filters in the search itself, not afterward in the prompt, and never rely on the model to withhold text it has already been given. Retrieved text is also untrusted input: a document can contain instructions aimed at the model. The safety chapter returns to this.
Keeping the index fresh
The index is data, so it drifts the way training data does, but the symptom is different. Nothing about the model changes. The world changes, documents are edited or deleted, and the index falls behind. Plan for these points:
- Update path. Decide whether the index is rebuilt on a schedule or updated incrementally when a source document changes.
- Deletes. A removed document must be removed from the index. Deletes are the update most often forgotten.
- Build IDs. Give each build an ID and record it in traces, so you can tell whether a regression came from code or from content.
- Rollback. Keep the previous index available. Switching an alias back is much faster than rebuilding.
Exercise
After a deploy, support answers about refund timing become vague, and traces show the prompt version is unchanged. The logged retrieval config ID has changed, and the kept chunk list is now often empty. Name two likely causes and the log fields you would check to tell them apart.
Show answer
One likely cause is a changed embedding model or chunk setting that makes stored and query vectors mismatch, so scores fall below minscore. Another is a raised minscore or a lowered contexttokenbudget that drops chunks. Compare the old and new retrieval config (embedding model, chunk size, minscore, budget) and look at the dropped list. If the reasons are mostly "lowscore" with uniformly low scores, suspect an embedding mismatch or a bad index build. If the reasons are "budget", suspect the budget or chunk size change.
Exercise
Why should you evaluate retrieval and generation separately in a RAG app?
Show answer
Wrong answers have two different causes, a missing chunk in the context or a model that misuses a correct chunk. A single end-to-end score cannot tell them apart, so you would not know whether to change the retrieval configuration or the prompt and model.