Papa Programmer
Lesson 04 of 11

Choosing useful context

8 min read

Optional

More material is not better

When an answer is wrong, the first instinct is to add more. Add the whole manual, the whole conversation, every record about the customer. This usually makes things worse. The correct sentence is now one among thousands, the model has more chances to follow the wrong one, and each extra token costs money and time.

The aim is the opposite. Find the smallest set of text that is enough. A good selection step answers one question for every candidate piece of material: does this change the answer? If the answer is no, the piece stays out.

Where candidates come from

For a support assistant the candidates come from several places at once.

  • Documents. Policies and guides, found by search as in How retrieval works. This is the Retrieval-augmented generationA method where an app searches sources at question time and adds selected passages to the model's context. Updated information can inform later answers once it is available to retrieval, but the results and answers still need checking. part of the context.
  • Records. The customer's profile and orders, fetched by an exact lookup, not a search.
  • History. Earlier turns of this conversation.
  • Tool results. Output from calls made during the task.

Each candidate arrives with facts about itself: where it came from, how old it is, who may read it and how well it matches the question. The selection step uses those facts.

Three tests, in this order

The order is deliberate. The cheapest and most serious test comes first.

  1. PermissionIf this user may not read it, it never enters the context.
  2. FreshnessA rule that has been replaced is removed or marked as old.
  3. RelevanceOf what is left, keep the pieces that bear on this question.
The three tests

Permission is first because it is a rule, not a preference. A relevant record that the user may not see must still be left out, and no score can outvote that. The Metadata filterA rule on stored facts about a chunk, such as its date or audience, that removes chunks before ranking. It keeps results current and limits users to text they may read. in Metadata, filters and permissions in RAG is the usual tool, and it works before ranking, so private text is never even scored.

Freshness is second because old text can look very relevant. A 2023 policy matches the question about returns as well as the 2026 one does. If both enter the context, the model must guess which to believe.

Relevance is last, and it is the only test that is a matter of degree.

A selector that explains itself

The program below runs the three tests over five candidate pieces and keeps a log with a reason for every decision. It ignores small words and compares the first four letters of each word, so "bikes" matches "bike". That is crude, but enough to show the method. A piece counts as related when it shares at least two such words with the question.

python
STOP = {"a", "can", "i", "the", "to", "of", "has", "for", "is"}

def stems(text):
	return {word[:4] for word in text.lower().replace("?", "").split() if word not in STOP}

candidates = [
	{"name": "returns 2026", "text": "unused bikes can be returned within 30 days", "audience": "public", "year": 2026},
	{"name": "returns 2023", "text": "unused bikes can be returned within 14 days", "audience": "public", "year": 2023},
	{"name": "staff refunds", "text": "staff may refund 500 euros without approval", "audience": "staff", "year": 2026},
	{"name": "shipping", "text": "standard shipping takes 3 to 5 business days", "audience": "public", "year": 2026},
	{"name": "warranty", "text": "the frame has a 5 year warranty", "audience": "public", "year": 2025},
]

def choose(question, groups, minimum_year):
	asked = stems(question)
	log = []
	for piece in candidates:
		if piece["audience"] not in groups:
			log.append(f"drop {piece['name']}: not allowed")
		elif piece["year"] < minimum_year:
			log.append(f"drop {piece['name']}: out of date")
		elif len(asked & stems(piece["text"])) < 2:
			log.append(f"drop {piece['name']}: unrelated")
		else:
			log.append(f"keep {piece['name']}")
	return log

for line in choose("can I return a bike within 30 days?", {"public"}, 2025):
	print(line)

It prints:

text
keep returns 2026
drop returns 2023: out of date
drop staff refunds: not allowed
drop shipping: unrelated
drop warranty: unrelated

Three things stand out. The staff-only record was dropped before anything else was asked of it. The 2023 policy was dropped for its age, even though its words match the question almost exactly. And the shipping and warranty pieces were dropped because they have nothing to do with returns. Only the current returns policy is kept.

The log matters as much as the result. When a user reports a wrong answer, you can read why each piece was in or out, instead of guessing.

Cap the size of what you keep

A relevant piece can still be too long. If a 40-page policy matches, do not send all 40 pages. Send the passage that answers the question, with its heading, as the How to chunk documents Lesson explains. Give each source a size limit and cut at a sentence boundary with a marker such as "(shortened)", so the model knows text is missing.

Be careful with what is trusted

Everything that enters the context is read by the model, and the model cannot always tell data from instructions. A web page, an email or a customer's message can contain text such as "ignore your rules". Selection is a chance to reduce that risk. Prefer sources you control, label every piece with where it came from, and keep untrusted text out of the instructions. The Lesson Putting retrieved passages in a prompt shows how to mark the boundaries.

A rule of thumb

If you cannot say why a piece of material is in the context, remove it and test again. Often the answer does not change, and you have saved space and money. Sometimes it does change, and you have learned what that piece was doing. Either way you know more than before.

Permission firstA rule decides what the user may read, and no relevance score overrides it.
Smallest sufficient setKeep only what changes the answer, because every extra piece is a chance to mislead.
Log every choiceA reason for each keep or drop turns a wrong answer into something you can trace.

Your reading position is saved

0%

0 of 11 complete

Contents

Learning tools