Sub topic 7
Retrieval and loading data just in time
This chapter assumes you have read the earlier chapters on token budgets and on the parts of a context. You should be comfortable reading short Python. You do not need a vector database or any particular library. The examples use only the standard library.
Two ways to get data into the window
A model can only use what is in its context window. Your data (documentation, tickets, code, logs) is almost always larger than the window. Something has to decide which parts of it the model sees. There are two broad strategies:
- Up-front retrieval. Before the model call, your code searches the data using the user's question and places the best matches in the prompt. The model never asks. This is the classic retrieval-augmented generation (RAG) pattern.
- Just-in-time loading. The context starts with only lightweight references, such as file names, document IDs, titles, or URLs. The model calls tools to fetch the full content when it decides it needs it.
Neither is better in every case. They trade predictability and latency against flexibility and token cost.
| Property | Up-front retrieval | Just-in-time loading |
|---|---|---|
| Who decides what to load | Your code, before the call | The model, during the call |
| Number of model calls | Usually one | Several, one per fetch |
| Token cost when the question is simple | Pays for retrieved text anyway | Pays only for references |
| Failure when the search is poor | Wrong passages crowd the window | Model may fetch the wrong item or stop early |
| Works well when | Questions map to a known corpus | The task explores, such as code or file systems |
Many production systems combine them. They retrieve a few likely passages up front and give the model tools to look further.
Up-front retrieval: the working model
Retrieval has four steps: split the data into chunks, score each chunk against the query, keep the top few, and place them in the context.
Chunking
A chunk is the unit you score and insert. Chunk size is a real trade-off.
- Too small (a sentence): matches are precise, but each chunk loses the surrounding explanation. The model gets a fact without its conditions.
- Too large (a whole document): each chunk contains the answer plus a lot of noise, and you spend budget on text that does not help.
A common starting point is a few hundred tokens per chunk, with a small overlap between neighbors so that a sentence split across a boundary still appears whole in one chunk. Split on natural boundaries (headings, paragraphs, functions) when you can, and fall back to fixed sizes when you cannot.
Scoring
Scoring ranks chunks by relevance. Three common approaches:
- Keyword scoring (for example BM25). It matches exact words. It is fast and strong on identifiers, error codes, and names.
- Embedding similarity. Text is converted to vectors and compared by distance. It finds paraphrases that share no words with the query, but it can miss exact strings such as
ERR_4021. - Hybrid. It combines both rankings. This is often the safest default.
The code below uses simple word-overlap scoring so it runs without dependencies. The surrounding structure (chunk, score, threshold, top-k) is the same one a production system uses with better scoring.
import re
from collections import Counter
def tokenize(text):
return re.findall(r"[a-z0-9_]+", text.lower())
def chunk(text, size=60, overlap=10):
# Split into word-based chunks; neighbors share `overlap` words.
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
def score(query, passage):
q, p = Counter(tokenize(query)), Counter(tokenize(passage))
return sum(min(q[w], p[w]) for w in q)
def retrieve(query, documents, k=3, min_score=2):
# documents maps a document id to its full text.
scored = []
for doc_id, text in documents.items():
for index, piece in enumerate(chunk(text)):
s = score(query, piece)
if s >= min_score:
scored.append((s, doc_id, index, piece))
scored.sort(key=lambda item: item[0], reverse=True)
return scored[:k]
documents = {
"refunds.md": "Refunds are issued to the original payment method within "
"five business days. Refund requests after thirty days "
"require manager approval.",
"shipping.md": "Standard shipping takes three to seven business days. "
"Express shipping takes one business day.",
}
for s, doc_id, index, piece in retrieve("how long do refunds take", documents):
print(f"[{doc_id}#{index}] score={s}: {piece}")Note the min_score threshold. Without it, retrieve would always return k chunks, even when nothing is relevant. Weak matches cost tokens and give the model material to misuse (see the earlier chapter on distraction). Returning nothing is a valid result, and your prompt should say what the model should do when no passages are found.
Placing results in the prompt
Label each retrieved passage with its source so the model can cite it and so you can debug later. Keep the format consistent:
def format_passages(results):
lines = []
for s, doc_id, index, piece in results:
lines.append(f"<passage source=\"{doc_id}#{index}\">\n{piece}\n</passage>")
return "\n".join(lines)The budgeting code from the earlier chapters decides how many of these passages fit. Retrieval proposes candidates, and the token budget decides how many are admitted.
Common retrieval errors
- Retrieving by the raw user message. Follow-up questions such as "what about for international orders?" contain no searchable terms. Rewrite the query using recent history first, or have the model produce a standalone search query.
- Fixed
kregardless of quality. Use a score threshold along with a cap, as above. - Near-duplicate chunks. Overlap and repeated documents can fill all
kslots with the same content. Deduplicate, or pick results that add new information. - Stale or conflicting sources. If an old policy and a new policy both match, the model sees a clash. Filter by date or version metadata before the model sees the text.
- Losing provenance. Without source labels you cannot tell whether a wrong answer came from bad data, bad ranking, or bad reasoning.
- Trusting retrieved text as instructions. Retrieved content is data. A document containing "ignore your rules" must not be treated as a command. Say so in the system prompt and keep retrieved text in clearly marked sections.
Just-in-time loading
In just-in-time loading, the initial context carries an index, not the content. The model sees something like a table of contents, then calls tools to read what it needs. Coding agents work this way. They list directories, search for a symbol, and open only the relevant file section.
This pattern has three useful properties:
- Cheap starting context. A catalog of 500 files with names and sizes costs far fewer tokens than the files.
- Progressive disclosure. Names, sizes, and paths are themselves signals. A file called
test_billing.pysuggests what it contains before it is opened. - Fresh data. Content is read at the moment of use, so it is not stale the way a precomputed snapshot can be.
The cost is extra round trips and the risk that the model explores aimlessly. Good tool design reduces both.
def list_docs(documents):
# A catalog: enough for the model to choose, far cheaper than the content.
return [
{"id": doc_id, "words": len(text.split()), "preview": text[:50]}
for doc_id, text in documents.items()
]
def read_doc(documents, doc_id, start=0, limit=120):
# Return a bounded slice and say whether more remains.
if doc_id not in documents:
return {"error": f"unknown document id: {doc_id}"}
words = documents[doc_id].split()
end = min(start + limit, len(words))
return {
"id": doc_id,
"text": " ".join(words[start:end]),
"next_start": end if end < len(words) else None,
}
print(list_docs(documents))
print(read_doc(documents, "refunds.md", start=0, limit=10))Design points visible in this code:
read_dochas a hardlimit. A tool that can return a 200,000-word file in one call can blow the budget in a single step.next_starttells the model how to continue, so it does not guess.- An unknown ID returns a short, specific error that the model can act on, not an exception trace.
The flow of a just-in-time call
Keeping loaded data under control
Everything the model loads stays in the history unless you remove it. Ten file reads of 2,000 tokens each leave 20,000 tokens in the window for the rest of the session. Practical controls:
- Return excerpts, not whole documents. Let the model request more.
- Clear old tool results once they have been used, keeping a one-line note of what was found.
- Record findings in notes or a summary, then drop the raw text (covered in the compaction and external memory chapters).
Choosing between them
Use up-front retrieval when questions are frequent, similar in form, and answerable from a well-indexed corpus, such as a support bot over a help center. It is predictable, fast, and easy to evaluate.
Use just-in-time loading when the needed data cannot be predicted from the question alone, as in debugging code, investigating logs, or researching across many sources.
Use both when you can afford a little retrieval up front to give the model a head start, plus tools to follow leads.
Summary of decisions
- Pick a chunk size that keeps whole ideas together, and add a small overlap.
- Score with keywords, embeddings, or both. Apply a minimum score as well as a top-k cap.
- Label every passage with its source, and treat retrieved text as data.
- For exploratory tasks, give the model a catalog and bounded read tools.
- Cap what each tool can return, and plan how loaded content will be cleared.
Exercise
A support assistant retrieves the top 5 chunks for every message. Users report that the follow-up "and for international orders?" gets irrelevant answers, and that for off-topic questions the assistant confidently cites unrelated policy text. Name two changes to the retrieval step that address these two problems.
Show answer
For the follow-up, rewrite the query before searching, using recent history (or a model-written standalone query such as "refund policy for international orders"), because the raw message has no searchable terms. For the off-topic questions, add a minimum score threshold so weak matches are dropped and the model receives no passages, and instruct it in the prompt to say it has no relevant information in that case. A fixed top 5 always fills the window with something, even when nothing is relevant.