Sub topic 5
Retrieval and Context Assembly as Part of the Pipeline
This chapter assumes you understand the basic machine learning lifecycle, can read Python, and know what a prompt and a language model are. You should also be familiar with basic application logging.
Why retrieval changes the application
A language model does not automatically know your current product documentation, private records, or recent events. A retrieval-augmented generation (RAG) application first finds relevant information, then places that information in the model's context.
The model is only one part of this system:
- The user sends a question.
- The application converts the question into a search request.
- A retriever finds relevant documents or document fragments.
- A context assembler selects, orders, and formats those fragments.
- The model receives the question and assembled context.
- The application returns an answer and records what happened.
This means the retrieval pipeline can change the answer even when the model and prompt stay unchanged. A new embedding model, search index, chunking rule, metadata filter, or ranking strategy can alter the evidence available to the model.
From documents to model context
A typical retrieval system prepares documents before serving user requests.
1. Ingest and split documents
Ingestion loads source documents. A splitter divides each document into chunks that are small enough to retrieve and fit into the model's context window. Each chunk should retain useful metadata, such as:
- Source document ID
- Section heading
- Access-control labels
- Creation or update time
- Chunk position
Overly large chunks include irrelevant text. Overly small chunks may lose the meaning needed to answer a question.
2. Index the chunks
An embedding model converts each chunk into a vector, which is a list of numbers representing the chunk's meaning. A vector index stores these vectors for similarity search.
The index is not the only configuration that matters. Record the embedding model, chunk size, overlap, parser version, and source-data snapshot. Rebuilding the index with different settings creates a different retrieval artifact.
3. Retrieve and assemble context
At request time, the application searches for candidate chunks. It may combine vector search with keyword search, apply permissions, remove duplicates, and rerank the candidates.
The final context should be explicit and bounded. For example:
from dataclasses import dataclass
@dataclass(frozen=True)
class Chunk:
source: str
text: str
score: float
def assemble_context(chunks: list[Chunk], max_chars: int = 3000) -> str:
"""Return ranked, labeled chunks within a character budget."""
selected = []
used = 0
for number, chunk in enumerate(sorted(chunks, key=lambda item: item.score, reverse=True), 1):
block = f"[Source {number}: {chunk.source}]\n{chunk.text}"
if used + len(block) > max_chars:
break
selected.append(block)
used += len(block)
return "\n\n".join(selected)
candidates = [
Chunk("billing.md", "Refunds are issued within five business days.", 0.91),
Chunk("shipping.md", "Standard delivery takes three to five days.", 0.72),
]
context = assemble_context(candidates)
prompt = f"""Answer using only the sources below.
If they do not contain the answer, say that you do not know.
Sources:
{context}
Question: When are refunds issued?
"""
print(prompt)The context assembler is application logic, not a minor formatting step. It decides which evidence the model can see and whether the answer can be traced back to a source.
The retrieval pipeline as a versioned dependency
For useful debugging, log or version the inputs that shape retrieval:
| Artifact | Example change | Possible effect |
|---|---|---|
| Chunking configuration | 500 to 1,000 characters | Different evidence is returned |
| Embedding model | Model A to Model B | Similarity rankings change |
| Metadata filter | Add department restriction | Some documents disappear |
| Reranking rule | Prefer recent documents | Evidence order changes |
A retrieval failure can look like a model failure. If the correct document was never retrieved, changing the prompt may not solve the problem. Compare retrieved chunks with the expected evidence before diagnosing the model's response.
Inspecting retrieval quality
Create test questions whose expected supporting documents are known. Measure whether the relevant document appears in the top results. Also check whether restricted documents stay excluded.
In production, trace the query, retrieval settings, selected source IDs, scores, context size, and final answer. Avoid logging sensitive document text unless your data policy allows it.
Exercise
A RAG answer is wrong, but the model follows the prompt correctly. What should you inspect first?
Show answer
Inspect the retrieved chunks and permission filters. Confirm that the correct source was retrieved, included in the assembled context, and not displaced by irrelevant or outdated content.