Sub topic 11
Defining how you will measure quality
This chapter assumes you know how product features are built, have a general sense of what machine learning and large language models do, and can read short Python snippets. It covers how to decide, before you build anything, how you will know whether a feature is good enough to ship.
Why measurement comes before the build
An AI feature gives different answers to similar inputs, and some of those answers are wrong. Rule-based logic can often be checked by reading it. An AI feature can only be judged by looking at its outputs. If you cannot measure those outputs, you cannot compare the AI option with a simpler baseline, and you cannot tell whether a change made the feature better or worse.
Evaluation depends on two earlier decisions in this tutorial:
- The problem definition tells you what "good" means for the user.
- The cost of errors tells you which mistakes matter most and how much of each you can accept.
Measurement turns both into numbers you can check. If you cannot say how you would measure quality, treat that as a reason not to ship. The scorecard in a later chapter uses the same rule: no measurement, no launch.
Start from the success outcome
A metric is useful only if it connects to what the user is trying to do. Write the outcome first, then choose measures that track it.
Suppose a support tool should route incoming messages to the right team. The user outcome is that a customer's problem reaches someone who can fix it quickly. That outcome suggests three kinds of measure:
- Output quality: was the message routed to the right team?
- Task outcome: did the ticket get resolved without being re-routed?
- Business impact: did time to resolution fall?
Output quality is the cheapest to measure and the easiest to test before launch. Task outcome and business impact are closer to what you care about, but they need real users and more time. A good plan uses all three at different stages.
Offline and online evaluation
Offline evaluation runs the feature on a saved set of examples with known correct answers. Online evaluation measures the feature with real users in the live product.
| Aspect | Offline evaluation | Online evaluation |
|---|---|---|
| Data | A fixed labeled set | Live traffic |
| Speed | Minutes | Days or weeks |
| Risk to users | None | Real, so limit exposure |
| What it shows | Output quality | User behavior and business impact |
| Typical tools | Scripts, test sets | A/B tests, dashboards |
Use offline evaluation to decide whether a candidate deserves a pilot. Use online evaluation to decide whether the pilot should become a full launch. Offline numbers often look better than online results, because the saved set does not capture everything real users do.
Build an evaluation set
An evaluation set is a collection of realistic inputs, each paired with the answer you consider correct. It is the most valuable evaluation asset you will create.
Good evaluation sets share these properties:
- Realistic. Draw examples from real user inputs, not from what the team imagines users will type.
- Representative. Include the common cases in the proportions users produce them.
- Covers edge cases. Add rare but important cases: empty input, very long input, other languages, ambiguous requests, and inputs where a wrong answer is costly.
- Labeled consistently. If two people disagree on the right answer, the task is ambiguous, and that is itself a finding about the problem.
- Kept separate. Do not use the same examples to tune the feature and to judge it. Otherwise you measure how well you memorized the set, not how well the feature works.
Size matters. With 20 examples, one change in a single answer moves accuracy by 5 percentage points, so small differences are noise. A few hundred examples is a common starting point for a first decision, and more for rare categories. Treat any result from a tiny set as a rough signal only.
Pick metrics that match the error cost
Accuracy, the share of correct answers, is the simplest metric. It can mislead when the classes are unbalanced or when errors have different costs.
Consider a feature that flags fraudulent payments, where 1 in 100 payments is fraud. A rule that never flags anything is 99% accurate and completely useless. For this kind of task, use two measures:
- Precision: of the items the feature flagged, how many were truly positive. Low precision means many false alarms.
- Recall: of the truly positive items, how many the feature found. Low recall means missed cases.
Which one to favor depends on error cost. If a missed fraud case is expensive and a false alarm only means a quick human check, favor recall. If a false alarm blocks a legitimate customer, favor precision.
The code below computes precision and recall from predictions, and it runs as written.
def precision_recall(predicted, actual, positive):
true_pos = sum(1 for p, a in zip(predicted, actual) if p == positive and a == positive)
flagged = sum(1 for p in predicted if p == positive)
real = sum(1 for a in actual if a == positive)
precision = true_pos / flagged if flagged else 0.0
recall = true_pos / real if real else 0.0
return precision, recall
actual = ["fraud", "ok", "ok", "fraud", "ok", "ok", "ok", "fraud"]
predicted = ["fraud", "fraud", "ok", "ok", "ok", "ok", "ok", "fraud"]
p, r = precision_recall(predicted, actual, "fraud")
print(f"precision={p:.2f} recall={r:.2f}")Here the feature flagged three payments and two were real fraud, so precision is 0.67. It found two of the three real fraud cases, so recall is 0.67.
For generated text, such as summaries or answers, there is often no single correct string. Common options are:
- Rubric scoring: reviewers rate each output on a few criteria, such as correctness, completeness, and tone, using a written scale.
- Pairwise comparison: reviewers choose the better of two outputs, which is often easier and more consistent than assigning a score.
- Automated checks: rules that test hard requirements, such as valid format, required fields, or banned content.
- Model-based grading: another model scores the output against a rubric. This scales well, but check it against human ratings first, because the grader can be biased or wrong.
Compare against the baseline
The evaluation must include the non-AI option. The second example in the topic's code samples does this with one shared scoring function:
def accuracy(predict, examples):
correct = sum(1 for text, label in examples if predict(text) == label)
return correct / len(examples)
examples = [
("please refund my order", "billing"),
("the app crashes on launch", "bug"),
("my invoice amount is wrong", "billing"),
]
def keyword_baseline(text):
if "refund" in text or "invoice" in text:
return "billing"
return "bug"
print(accuracy(keyword_baseline, examples))Because both options use the same accuracy function and the same examples, any AI candidate can be passed in as another predict function and scored the same way. The comparison is fair only when the data, the metric, and the conditions are identical.
Report more than the headline number. Break results down by category and by input type, because an average can hide a group where the feature fails badly. Also measure the extra cost: if AI improves accuracy by two points but costs ten times as much per request and adds seconds of delay, the gain may not be worth it.
Set thresholds before you look at results
A threshold is the minimum result that counts as good enough. Decide it first, using the cost of errors and the baseline as guides. If you choose the threshold after seeing the numbers, it is easy to talk yourself into whatever result you got.
A useful threshold has these parts:
- A metric and a value, such as "recall of at least 0.90 on fraud cases."
- A guardrail, a measure that must not get worse, such as "median response time stays under two seconds."
- A comparison, such as "beats the keyword baseline by at least five points."
- A critical-case rule, such as "zero unsafe outputs on the high-risk test cases."
Averages do not protect against rare severe failures. A feature with 95% accuracy can still be unacceptable if the 5% that fail are the cases that cause harm. That is why a critical-case rule sits alongside the average.
Common errors
- Measuring only what is easy. Output quality is simple to compute, but if it does not track the user outcome, a high score means little.
- Testing on the tuning data. Results look excellent and then fall in production.
- Leakage. Examples in the evaluation set also appear in training data or prompts, so the feature has effectively seen the answers.
- A set that is too clean. Hand-written examples lack the typos, slang, and odd formats of real input.
- One number for everything. A single average hides weak segments and rare failures.
- No baseline. A score of 85% sounds good until a keyword rule scores 84%.
- Ignoring label disagreement. If reviewers cannot agree, a metric will not fix it. Clarify the task first.
Connecting to the decision
The result of this chapter is a written evaluation plan with five parts: the user outcome, the evaluation set and where it comes from, the metrics, the thresholds, and the baseline to beat. This plan feeds the scorecard directly. In the sample scorecard from earlier, the can_evaluate answer is true only when you have such a plan and the means to run it. If the answer is false, the rule returns "do not ship until quality can be measured."
The same plan is reused after launch. The evaluation set becomes a regression check when you change a prompt, model, or rule. The metrics become the monitoring signals, and the thresholds tell you when to revisit the decision.
Exercise
A feature flags abusive comments for a human moderator to review. About 2% of comments are abusive. A candidate model has 98% accuracy on the evaluation set. A teammate says this proves it is ready. Explain why this is not enough, and name two metrics and one threshold you would set instead.
Show answer
With 2% abusive comments, a model that flags nothing also scores 98% accuracy, so the number says little. Use recall (the share of abusive comments found) and precision (the share of flagged comments that are truly abusive). Because a human moderator reviews every flag, false alarms are cheap and missed abuse is costly, so favor recall. A sample threshold: recall of at least 0.90 on abusive comments, precision of at least 0.50 so moderators are not flooded, and a comparison showing it beats the current keyword filter on both. Also report results by comment type, since an average can hide a weak category.
Exercise
You have 25 labeled examples and an AI candidate scores 84% while a keyword rule scores 80%. Should you conclude the AI option is better? What would you do next?
Show answer
No. On 25 examples, one answer is worth 4 percentage points, so the 4-point gap is a single example and is within noise. Collect a larger, realistic evaluation set (a few hundred examples, with edge cases), score both options on it with the same metric, and look at results by category. Also compare cost and latency before deciding that the gain is worth it.