Measure accuracy, latency and cost before adding retrieval
Score a labelled set for accuracy, schema validity, latency and cost and set success criteria before adding retrieval or tools.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 10 minutes to read.
In short
Before adding retrieval or tools, measure how well the simple version works. Label a small test set, run it through a rule-based baseline and the model-only version, and score accuracy, schema validity, latency and cost per request. Write the success criteria down first, so later changes are judged against numbers rather than impressions.
Think of it like this: It is like weighing yourself before starting a training plan: without the starting number you cannot tell whether the plan worked.
Explained simply
Before making your assistant smarter, find out how good the simple version already is. Otherwise you cannot tell whether retrieval or tools actually help, or just add cost.
Start with a labelled set: a list of test tickets, each with the correct category written down by a person. Thirty to a hundred varied tickets is a fine start. Include easy ones, tricky ones and ones with missing details.
Run the set through two versions: a cheap keyword-rule version and the model-only version from the last topics. For each, record four numbers: how often the category is right, how often the output passes validation, how long each request takes, and what each request costs.
Most important, write your success criteria before you run anything. For example: accuracy at least 85 percent, validity at least 98 percent, p95 latency under 3 seconds, cost under 0.002 per request. Deciding afterwards makes every result look good.
Press Play on a diagram to walk through it one step at a time.
- 1Write success criteria
Targets set before running
- 2Run the labelled set
Same cases for every variant
- 3Score
Accuracy, validity, latency, cost
- 4Read the failures
Group by cause
- 5Change one thing
Prompt, model or settings
- Back to step 1
- Near-zero cost and latency
- Always schema valid
- Misses varied wording
- Cannot write summaries
- Handles varied wording
- Writes summaries and next steps
- Costs tokens and time
- Can produce invalid output
- Setup
- Test set version
- Prompt version
- Model ID and date
- Quality
- Accuracy
- Schema validity
- needs_info accuracy
- Speed and cost
- Median latency
- p95 latency
- Cost per request
- Decision
- Criteria met or not
- Top failure causes
In depth
Building a small labelled set
Write synthetic tickets that look like real ones: short and long, polite and angry, clear and vague. Store them in a JSONL file, one object per line with id, text, expected_category and expected_needs_info. Aim for a mix of categories roughly like real traffic, plus deliberate hard cases. Have a second person label a sample and compare; where you disagree, the category definitions are unclear, so fix the definitions before scoring the model. Freeze the file with a version name such as triage-set-v1. Add new cases in a new version, so earlier scores stay comparable.
- JSONL: id, text, expected_category, expected_needs_info
- Cover every category plus hard and vague cases
- Double-label a sample to test your definitions
- Freeze and version the set
Scoring accuracy and schema validity
Score each run in the same order. First, schema validity: the share of outputs that pass the Pydantic model. Second, accuracy: among all cases, the share where the category matches. Count invalid outputs as wrong for accuracy, so a version cannot look better by failing more often. Third, look at a confusion table showing which categories get mixed up, such as access mislabelled as software. Also score the needs_info flag separately: did the model correctly spot missing details? Summaries and next steps are harder to score automatically; for now, review a random sample by hand with a simple pass or fail rubric.
- 1Load set
triage-set-v1.jsonl
- 2Run variant
Rules or model-only
- 3Validate
Schema validity rate
- 4Compare labels
Accuracy and confusion table
- 5Write report
Numbers plus failure notes
Recording latency and cost per request
Wrap the model in the logging wrapper from the first module so every call records latency and token usage. Report latency as the median and the 95th percentile (p95), because averages hide slow outliers that users notice. Compute cost per request from logged tokens and the dated price table, then report the mean and the total for the run. For the rule-based baseline, latency is close to zero and cost is zero, which is exactly why it is worth comparing against. With the deterministic fake, latency and cost are not meaningful; run the timing part against a real model only if you have one, and label those numbers with the model ID and date.
- Median and p95 latency, never only the mean
- Cost from logged usage and dated prices
- Label numbers with model ID and date
- Fake model numbers prove the harness, not the model
Writing success criteria up front
Success criteria turn opinions into decisions. Write them in a short file committed next to the test set, before running any variant. Each criterion has a metric, a threshold and a reason: accuracy of at least 0.85 because agents re-route about 15 percent today; validity of at least 0.98 because every invalid output costs a manual review; p95 latency under 3 seconds because the help desk form waits for the result. Also write what would make you stop, such as cost per request above a budget. Later modules add retrieval and tools; each must beat this baseline on the same frozen set, or it is not worth its complexity.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Label a small test set~45m
- 2Score accuracy and schema validity~45m
- 3Record latency and cost per request~45m
- 4Write success criteria up front~45m
Key points
- A labelled set of 30 to 100 varied cases is enough to start; include hard and missing-info cases.
- Score schema validity separately from accuracy; a wrong but valid label is a different failure.
- Report latency as median and 95th percentile, not just an average.
- Compute cost per request from logged token usage and dated price assumptions.
- Set pass thresholds before running, and keep the set frozen while comparing variants.
Key terms
Tap a card to flip it. 0/5 known
Examples
import pytest
CASES = [
("I forgot my password", "access"),
("Invoice 4417 charged twice", "billing"),
("Laptop screen flickers", "hardware"),
]
@pytest.mark.parametrize("text,expected", CASES)
def test_triage_label(text, expected):
result = triage(text, model=FakeModel())
assert result.category == expectedpytest.mark.parametrize turns a labelled set into one test per case.
Comparing rules and model-only on 40 tickets
Criteria set first: accuracy at least 0.85, validity at least 0.98, p95 under 3 s. Step 1: the keyword rules score accuracy 0.60, validity 1.00, p95 near 0 ms, cost 0. Step 2: the model-only version scores accuracy 0.88, validity 0.95, p95 2.1 s and an assumed cost of 0.0008 per request. Step 3: model-only beats rules on accuracy but fails the validity target. Step 4: reading the 2 invalid outputs shows both were truncated JSON, so the next change is raising max output tokens, then rerunning on the same frozen set. These numbers are illustrative, not from a real model.
A small scoring harness
This function runs any triage function over the labelled set and returns validity, accuracy and latency percentiles. Invalid outputs count as wrong.
import json, statistics, time
def score(triage_fn, path: str) -> dict:
cases = [json.loads(line) for line in open(path, encoding="utf-8")]
valid = correct = 0
times = []
for c in cases:
start = time.perf_counter()
result = triage_fn(c["text"]) # Triage or Escalation
times.append(time.perf_counter() - start)
if isinstance(result, Triage):
valid += 1
correct += result.category == c["expected_category"]
p95 = statistics.quantiles(times, n=20)[-1]
return {"validity": valid / len(cases), "accuracy": correct / len(cases),
"median_s": statistics.median(times), "p95_s": p95}Quick reference
- Write success criteria before running any variant
- Start with 30 to 100 varied labelled cases in versioned JSONL
- Count invalid outputs as wrong when computing accuracy
- Report median and p95 latency, not just the mean
- Cost per request = logged tokens x dated prices
- Always compare against a cheap rule-based baseline
- Freeze the test set while comparing; add cases in a new version
- Never tune the prompt on the cases you report scores for
Common mistakes
- Changing the test set while comparing versions, so the numbers are not comparable.
- Tuning the prompt on the same few cases you report, which inflates the score.
- Deciding the target after seeing results, so any result looks like success.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write five synthetic labelled tickets as JSONL lines with id, text and expected_category.
- Exercise 2medium
Write success criteria for the triage baseline with a metric, threshold and reason for each of accuracy, validity, latency and cost.
- Exercise 3hard
Write a pytest test that runs the score harness with the keyword-rule triage and fails if accuracy is below a threshold read from a criteria dict.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How big should my first test set be?
- Thirty to a hundred varied cases is enough to spot big differences. Grow it as you find new failure types, and version each change.
- Can I measure cost without a paid model?
- Yes, at design level. Use estimated token counts and a dated price assumption. Label the numbers as estimates until you run a real model.
- Why not jump straight to adding retrieval?
- Without a baseline you cannot tell whether retrieval improves anything. It may add latency and cost for little gain on this task.