Sub topic 7
Retrieval and loading data just in time
This chapter assumes you have read the earlier chapters on tokens, token budgets, and selecting relevant information. You should also be comfortable reading short Python functions.
Why load data just in time
A context window has a fixed size. If you paste every possibly useful document into it before the model starts, most of that text goes unused. It still costs tokens, and it can distract the model.
Just-in-time loading takes the opposite approach. The context starts with lightweight references, such as file paths, document titles, or search queries. The model, or your code, loads the full content only when a step needs it.
| Approach | What goes in the context up front | Main risk |
|---|---|---|
| Preload everything | Full text of all candidate documents | Wasted budget, distraction |
| Just-in-time | Short index or identifiers | Extra calls, possible missed lookups |
How retrieval works
Retrieval is the step that finds candidate content for the current question. The usual pipeline has four stages:
- Split source documents into chunks, which are pieces small enough to fit several in one context.
- Index the chunks so you can search them. Search can be keyword-based, embedding-based (similarity of meaning), or both.
- At question time, search with the user's question or a rewritten query, and rank the results by relevance.
- Insert the top results into the context, within the budget you set for documents.
The loop at the bottom matters. A single search is often not enough, so the model can issue a new query after seeing the first results.
Loading in stages
Loading everything at full size is rarely necessary. Load in stages, from cheap to expensive:
- Load a short listing, such as titles and one-line descriptions.
- Load a summary or the best-matching chunks for the items that look relevant.
- Load the full document only if the chunks are not enough.
The following code shows the idea. It keeps a catalog of short descriptions in context and fetches a full document only on request.
DOCS = {
"billing.md": "Refund rules: refunds are allowed within 30 days of purchase.",
"shipping.md": "Shipping: orders ship in 2 business days.",
}
DESCRIPTIONS = {
"billing.md": "Refund and payment policy",
"shipping.md": "Delivery times and costs",
}
def catalog():
# Cheap listing that stays in context.
return "\n".join(f"- {name}: {desc}" for name, desc in DESCRIPTIONS.items())
def load_document(name, max_chars=2000):
# Expensive content, loaded only when requested.
if name not in DOCS:
return f"Error: no document named {name}"
return DOCS[name][:max_chars]
print(catalog())
print(load_document("billing.md"))The max_chars cap protects the budget. Without it, one large file could fill the window.
Common errors
- Retrieving too many chunks. Adding more results past the point of usefulness raises cost and lets weak matches distract the model.
- Chunks that are too small or too large. Tiny chunks lose the surrounding explanation. Huge chunks waste budget on unrelated text.
- Searching only with the raw question. A vague follow-up such as "what about the second one?" retrieves nothing useful. Rewrite it into a standalone query first.
- No fallback when nothing matches. If the top result has a low score, say so in the context. Otherwise the model may build an answer from an irrelevant chunk.
- Stale indexes. If documents change and the index does not, the model cites outdated facts with full confidence.
Choosing between preloading and retrieval
Preload when the content is small, always needed, and stable, such as a short style guide. Retrieve when the corpus is large, only a few parts matter per question, or the relevant part is unknown until the model starts working. Retrieval adds latency and a new failure mode, which is missing the right chunk. Weigh that against the budget it saves.
Exercise
A support assistant has 500 policy documents. Each question needs about two of them. Name one reason to use just-in-time loading here, and one risk you must then guard against.
Show answer
Reason: loading all 500 documents would exceed or waste the token budget, while loading about two per question keeps the context small and focused. Risk: the search may miss the right document, so you should check retrieval quality, handle low-score results explicitly, and let the model search again.
Exercise
A user asks "and what about international orders?" after a question on shipping. Why might retrieval fail if you search with that text alone, and what fixes it?
Show answer
The text depends on earlier conversation, so it has no standalone meaning for the search index. Rewrite it into a self-contained query, such as "shipping times and costs for international orders", before searching.