Sub topic 14
Measuring whether a context change helped
This chapter assumes you have called a model through an API, you know what a system prompt and a token are, and you can read short Python. You should also have seen the earlier techniques in this tutorial: selection, trimming, compaction, retrieval, and caching. Each one is a context change. This chapter shows how to decide whether a change was an improvement or only felt like one.
Why intuition is not enough
You change the retrieval step so it returns five documents instead of ten. You run three questions by hand. The answers look good. Do you ship it?
Three things make that decision unreliable:
- Model output varies from run to run, so three samples can look good by luck.
- A change that fixes the question you were staring at can break questions you did not check.
- A smaller context is cheaper and faster. That is a real gain, but it can hide a drop in quality.
The fix is the same as in any engineering work. Fix a test set, define a metric, measure a baseline, change one thing, and measure again.
The evaluation loop
The rest of the chapter covers each step.
Build a test set
A test set is a list of cases. Each case holds the inputs you give the model and a way to judge the output. Cover the situations your context has to handle:
- Typical requests that make up most of your traffic.
- Hard cases, such as questions where the answer sits in a long document or needs two sources.
- Cases built to expose the failures from earlier chapters: a stale fact that clashes with a fresh one, an irrelevant document that could distract, a long history where an early instruction must still hold.
- Cases where the correct behavior is to say the information is not available.
Start with 20 to 50 cases. That is enough to catch large regressions. Small differences need more cases, and the section on noise explains why. Keep the set fixed while you compare variants. If you edit cases between runs, the scores are no longer comparable. When you add cases, record the date and re-score the baseline.
Take cases from real failures when you can. A bug report that says "the assistant forgot the user's budget after a long chat" becomes a test case, and it stays in the set so the bug cannot return unnoticed.
Choose metrics
Use several metrics, because context changes trade one thing against another.
| Kind | Example metric | How to measure |
|---|---|---|
| Quality | Fraction of answers that are correct | Compare with a known answer, or use a rubric |
| Grounding | Answer cites facts that appear in the context | Check that quoted facts exist in the supplied documents |
| Retrieval | Did the needed document make it into the context? | Check for a known document ID in the chosen set |
| Cost | Input tokens per call | Read the usage field of the API response |
| Latency | Seconds per call | Time the call end to end |
| Cache | Share of input tokens served from cache | Read the cache fields of the API response, if your provider reports them |
Separate retrieval metrics from answer metrics. If an answer is wrong, you need to know which stage failed. If the needed document was never in the context, the fault lies in selection. If it was there and the model ignored it, the fault lies in ordering, distraction, or the instructions.
Scoring answers
You have three common ways to score an answer.
- Exact or programmatic checks. Compare to an expected string, parse a number, or confirm that required fields exist. These are cheap, repeatable, and objective. Use them wherever the answer is short and well defined.
- Rubric scoring by a person. A person reads the answer and marks each rubric item pass or fail. This is slow but reliable for open-ended answers.
- Model-as-judge. A second model call grades the answer against a rubric. It scales well but has its own biases, such as favoring longer answers. Check it against a sample of human scores before trusting it, and keep the judge's own context fixed so it does not become a second variable.
A small harness
The harness below runs a test set against a context-building function and reports accuracy and average input size. The build function and the answer function are passed in, so you can swap a baseline context builder for a variant. The answer function here is a stand-in for a real model call.
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
def run_suite(cases, build, answer):
# cases: list of dicts with "question", "docs", and "expected".
# build(case) returns the context string for that case.
# answer(context, question) returns the model's answer string.
results = []
for case in cases:
context = build(case)
reply = answer(context, case["question"])
results.append({
"correct": case["expected"].lower() in reply.lower(),
"tokens": estimate_tokens(context),
})
n = len(results)
return {
"accuracy": sum(r["correct"] for r in results) / n,
"avg_tokens": sum(r["tokens"] for r in results) / n,
"n": n,
}
def build_all_docs(case):
return "\n".join(case["docs"])
def build_top_one(case):
return case["docs"][0]
def fake_answer(context, question):
# Stand-in for a model call: "knows" a fact only if it appears in the context.
return "Paris" if "capital of France is Paris" in context else "unknown"
cases = [
{
"question": "What is the capital of France?",
"docs": ["The capital of France is Paris.", "Berlin is in Germany."],
"expected": "Paris",
},
{
"question": "What is the capital of France?",
"docs": ["Berlin is in Germany.", "The capital of France is Paris."],
"expected": "Paris",
},
]
baseline = run_suite(cases, build_all_docs, fake_answer)
variant = run_suite(cases, build_top_one, fake_answer)
print("baseline", baseline)
print("variant ", variant)Running it prints:
baseline {'accuracy': 1.0, 'avg_tokens': 14.0, 'n': 2}
variant {'accuracy': 0.5, 'avg_tokens': 8.0, 'n': 2}The variant uses about 43% fewer tokens, but accuracy fell from 1.0 to 0.5. In the second case the relevant document was not first, so "keep only the top document" dropped it. A hand check of the first case alone would have approved the change. The suite caught the regression because it included a case where ranking order differed.
Handle noise
Real models do not return the same answer twice. This affects how you read differences.
- Set temperature low, or to zero where the API allows it, during evaluation. This reduces variation but does not remove it.
- Run each case several times and average, if a case is cheap enough to repeat.
- Treat small differences with suspicion. On 20 cases, one case flipping moves accuracy by 5 points. A 5-point gain on 20 cases is one case, which can easily be noise.
- Look at which cases changed, not only the total. Two cases fixed and two cases broken gives the same accuracy as no change, but it is a different system.
A useful habit is to write the comparison as a list of flips: cases that went from fail to pass, and cases that went from pass to fail. Read every case in the second list.
def flips(baseline_correct, variant_correct):
# Both arguments map case id to True or False.
fixed = [k for k in baseline_correct if not baseline_correct[k] and variant_correct[k]]
broken = [k for k in baseline_correct if baseline_correct[k] and not variant_correct[k]]
return fixed, broken
base = {"a": True, "b": False, "c": True, "d": True}
var = {"a": True, "b": True, "c": False, "d": True}
fixed, broken = flips(base, var)
print("fixed:", fixed)
print("broken:", broken)This prints fixed: ['b'] and broken: ['c']. Accuracy is 0.75 in both runs, yet the change swapped one failure for another.
Isolate one variable
Change one thing per comparison. If you reorder documents, shrink the history budget, and rewrite the system prompt together, you will not know which change caused a gain or a loss. Gains from one change can cancel losses from another.
Some changes interact. A shorter history budget may only hurt when documents are also trimmed. When you suspect this, test each change alone first, then the combination.
Weigh quality against cost and latency
Quality is not the only axis. Decide ahead of time how much of each you will trade.
- A change that keeps quality equal and cuts input tokens is a clear win.
- A change that raises quality and raises cost needs a judgment. Compute the cost per correct answer, not only the cost per call.
- A change that restructures the prompt for caching should leave quality unchanged. Verify that, then check that the cached share of input tokens rose and the latency fell.
Common errors
- Tuning to the test set. If you adjust the context until the suite passes, the suite stops measuring generalization. Keep a held-out set that you run only before you adopt a change.
- Testing only short contexts. Many context failures appear only when the context is long. Include cases with realistic length, including long histories.
- Scoring only the final answer in an agent. For multi-step tasks, also record which tool calls were made and how many tokens each step used. A correct answer reached through ten wasted calls is a cost problem.
- A judge that shares your blind spots. If the same model writes and grades answers, errors may go unnoticed. Spot-check with people.
- No baseline. A score of 80% means little without the previous score on the same cases.
Keep the process running
Treat the suite as part of the codebase. Run it when you change the system prompt, the tool descriptions, the retrieval settings, the summarizer prompt, or the model. Store each run's results with the change that produced them, so you can see when a regression began. When a production failure appears, add a case for it before you fix it. The fix is then proven by the suite, and the case guards against a repeat.
Exercise
Your suite has 20 cases. A context change moves accuracy from 14/20 to 15/20 and cuts input tokens by 30%. Your colleague wants to ship it. What do you check before agreeing, and why?
Show answer
Check which cases flipped. A one-case gain on 20 cases (5 points) can be noise, so first confirm whether the change fixed some cases and broke others, and read every case that went from pass to fail. Re-run the suite several times at low temperature to see whether the gain holds. Run a held-out set that was not used while tuning. If the broken cases are none and the gain holds, the change is a quality-neutral-or-better win with lower cost, and shipping is reasonable. If cases broke, decide whether the 30% saving is worth them.
Exercise
A retrieval change drops answer accuracy. Which two metrics let you tell whether selection or ordering is at fault, and how do you read them?
Show answer
Measure retrieval (whether the known needed document ID is in the chosen context) separately from answer correctness. If the needed document is missing from the context in the failing cases, selection is at fault. If it is present but the answer is wrong, the cause lies elsewhere, such as ordering, distracting content, or the instructions.