Sub topic 12
Testing and monitoring the pipeline
This chapter assumes you have the TicketTriage model, strip_code_fence, and extract_ticket from the earlier chapters. It also assumes basic pytest knowledge. Validation and retries make one call safe. Testing and monitoring tell you how often the whole pipeline works across many calls.
Why one passing run proves little
Model output varies between runs, and it changes when you edit a prompt, change a schema, or switch model versions. A prompt that worked on three tickets may fail on one in twenty. You need two things:
- A fixed set of examples you run before every change (testing).
- Counters on real traffic that show drift after release (monitoring).
Build a fixed evaluation set
Collect 20 to 50 real inputs with the answer you expect. Include the hard ones: empty text, very long text, mixed languages, tickets that fit two categories, and inputs that previously failed in production. Store them in a file under version control so every change is measured against the same examples.
Track more than one number, because each one catches a different failure:
| Metric | What it catches |
|---|---|
| Valid rate | Output that never passes validation, even after retries |
| First-attempt valid rate | Prompts or schemas that depend on retries to work |
| Field accuracy | Valid output with wrong values (the semantic errors from the previous chapter) |
| Average calls per input | Rising cost and latency from hidden retries |
A small evaluation harness
The harness wraps your model call in a counter. It then runs extract_ticket on each case and compares the result to the expected values. The same code works with a real API call or a fake one.
CASES = [
{"text": "I was charged twice this month.", "category": "billing", "priority": 2},
{"text": "The app crashes when I open settings.", "category": "bug", "priority": 1},
{"text": "Please add a dark mode.", "category": "feature_request", "priority": 3},
]
def run_eval(cases, call_llm):
calls = 0
def counting_llm(prompt):
nonlocal calls
calls += 1
return call_llm(prompt)
valid = first_try = category_ok = priority_ok = 0
for case in cases:
before = calls
try:
result = extract_ticket(case["text"], counting_llm)
except ValueError:
continue
valid += 1
if calls - before == 1:
first_try += 1
category_ok += result.category == case["category"]
priority_ok += result.priority == case["priority"]
n = len(cases)
return {
"valid_rate": valid / n,
"first_try_rate": first_try / n,
"category_accuracy": category_ok / n,
"priority_accuracy": priority_ok / n,
"calls_per_case": calls / n,
}Accuracy here is measured over all cases, so a case that fails validation counts as wrong. Run this against the real model on a schedule or before each release, and save the results so you can compare versions.
Unit tests that need no model
Do not call a live model in your regular test suite. It is slow, costs money, and gives different answers on different runs. Test your own code with a fake call_llm that returns scripted replies.
import pytest
def scripted(replies):
it = iter(replies)
return lambda prompt: next(it)
GOOD = '{"category": "bug", "priority": 1, "summary": "App crashes."}'
def test_code_fence_is_stripped():
result = extract_ticket("t", scripted(["```json\n" + GOOD + "\n```"]))
assert result.category == "bug"
def test_retry_recovers_from_invalid_reply():
bad = '{"category": "urgent", "priority": 1, "summary": "x"}'
result = extract_ticket("t", scripted([bad, GOOD]))
assert result.priority == 1
def test_gives_up_after_max_attempts():
with pytest.raises(ValueError):
extract_ticket("t", scripted(["not json"] * 3))These tests check the parsing, retry, and failure paths. They do not tell you whether the model is accurate. Only the evaluation set does that.
Monitor production
Log one structured record per request. Never log only the failures, because you need the denominator to compute rates.
Use the diagram below as the map of what to record.
Record these fields for each request:
- Prompt version and model name, so a change in rate can be tied to a change you made.
- Attempt count, and the validation error type for each failed attempt.
- Finish reason from the API. A length-based stop means truncation.
- Whether a refusal occurred.
- Latency and token counts.
Then watch these rates over time: validation failure per attempt, final failure after retries, truncation, and refusals. Alert when a rate rises above its baseline, for example when the final failure rate doubles within a day. Also sample a small number of valid outputs for human review each week. Valid output can still be wrong, and only a person reading it will notice.
Send exhausted requests to a fallback, such as a review queue, and keep the raw reply. Add those inputs to your evaluation set so the same failure is tested from then on.
Common mistakes
- Testing only on easy examples, which gives a valid rate near 100% that production never matches.
- Changing the prompt and the schema together, so you cannot tell which change helped.
- Treating a high retry-success rate as good news. It can hide a prompt that fails on the first attempt and doubles your cost.
- Pinning no model version, so results change without any change on your side.
Exercise
Your evaluation shows a valid rate of 98%, a first-attempt valid rate of 71%, and 1.4 calls per case. What does this tell you, and what would you do first?
Show answer
Retries are rescuing about a quarter of the cases, so the prompt or schema often produces invalid output on the first try. The result looks healthy but costs more calls and adds latency. Read the validation errors from the failed first attempts, find the common cause (for example a wrong enum value or a missing field), and fix the prompt or schema. Then re-run the same evaluation set and check that the first-attempt rate rises and calls per case falls toward 1.0.