Sub topic 12
Testing and monitoring the pipeline
This chapter assumes you can write a Pydantic model, call an LLM API, and have read the earlier chapters on validation and retry loops. Those chapters gave you an extraction step that validates output and retries on failure. Here you will check that the step works, and keep checking after it ships.
Why a pipeline that "worked once" is not tested
A structured-output step can pass your first five manual tries and still fail on a few percent of real inputs. Model replies vary from call to call. Providers also update models, and your inputs drift over time. A test and monitoring setup gives you three things:
- A number for how often the pipeline fails, rather than a feeling.
- A way to notice when a prompt, schema, or model change makes that number worse.
- Records of real failures that you can turn into new test cases.
Keep two kinds of failure apart, because they need different checks.
| Failure kind | Example | How to detect it |
|---|---|---|
| Structural | Invalid JSON, missing field, `priority` of 7 | Schema validation. Fully automatic. |
| Semantic | Valid JSON, but `category` is `bug` for a billing complaint | Comparison to known-correct labels. Needs examples with answers. |
Validation catches the first kind in production. Only a labeled test set catches the second kind.
Building a fixed evaluation set
An evaluation set (often called an eval set) is a fixed list of inputs, each paired with the output you expect. You run the pipeline over the whole list and score the results. Because the list does not change between runs, a change in score points to a change in your system.
Start with 20 to 50 cases. Cover these groups:
- Typical inputs, which make up most of your real traffic.
- Boundary inputs, such as a very short ticket, a very long one, or one with several topics.
- Ambiguous inputs, where two labels are defensible. Decide the expected answer and write it down.
- Hostile or odd inputs: empty text, text in another language, text that contains JSON or a Markdown code fence, text that tries to instruct the model.
- Past failures. Every bug you find in production becomes a case.
Store the set in a plain file so it can be reviewed and versioned with your code. JSON Lines works well, with one case per line.
{"id": "t001", "text": "I was charged twice for my March invoice.", "expected": {"category": "billing", "priority": 2}}
{"id": "t002", "text": "The export button crashes the app on Safari.", "expected": {"category": "bug", "priority": 2}}
{"id": "t003", "text": "", "expected": null}Note that expected holds only the fields you can state with confidence. The summary field is free text, so you cannot compare it with ==. Score exact-match fields such as enums and integers automatically. Check free-text fields with looser rules, such as a length limit, or review a sample by hand.
Two layers of tests
Split your tests by whether they call a real model.
Layer 1: deterministic tests with a fake model
The extract_ticket function from the retry chapter takes call_llm as a parameter. That design lets you test your own logic without a network call or any randomness. You pass a fake function that returns scripted replies.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
def strip_code_fence(raw: str) -> str:
text = raw.strip()
if text.startswith("```"):
text = text.split("\n", 1)[1] if "\n" in text else ""
text = text.rstrip()
if text.endswith("```"):
text = text[:-3]
return text.strip()
def extract_ticket(ticket_text, call_llm, max_attempts=3):
prompt = (
"Triage this support ticket. Reply with a single JSON object with keys "
"category, priority, summary and nothing else.\n\n" + ticket_text
)
for _ in range(max_attempts):
raw = strip_code_fence(call_llm(prompt))
try:
return TicketTriage.model_validate_json(raw)
except ValidationError as err:
prompt = (
"Your previous reply was invalid.\n"
f"Reply:\n{raw}\n\nErrors:\n{err}\n\n"
"Return a corrected JSON object only.\n\nTicket:\n" + ticket_text
)
raise ValueError(f"No valid output after {max_attempts} attempts")
def scripted(*replies):
"""Return a fake call_llm that yields each reply in order and records prompts."""
queue = list(replies)
prompts = []
def call_llm(prompt):
prompts.append(prompt)
return queue.pop(0)
call_llm.prompts = prompts
return call_llm
GOOD = '{"category": "bug", "priority": 2, "summary": "App crashes on export."}'
BAD_PRIORITY = '{"category": "bug", "priority": 7, "summary": "App crashes."}'
def test_accepts_fenced_json():
result = extract_ticket("x", scripted("```json\n" + GOOD + "\n```"))
assert result.category == "bug"
def test_retries_and_sends_error_back():
fake = scripted(BAD_PRIORITY, GOOD)
result = extract_ticket("x", fake)
assert result.priority == 2
assert len(fake.prompts) == 2
assert "priority" in fake.prompts[1]
def test_gives_up_after_max_attempts():
fake = scripted("not json", "not json", "not json")
try:
extract_ticket("x", fake)
except ValueError:
assert len(fake.prompts) == 3
else:
raise AssertionError("expected ValueError")
if __name__ == "__main__":
test_accepts_fenced_json()
test_retries_and_sends_error_back()
test_gives_up_after_max_attempts()
print("all tests passed")This file runs as shown with python, and also works under pytest. These tests are fast and never flaky. Run them on every commit. They prove that the fence stripping, the validation, the feedback prompt, and the attempt limit all behave as designed.
Layer 2: evaluation runs against the real model
Fake-model tests say nothing about whether the real model fills in category correctly. For that you run the eval set through the real API. These runs cost money and vary between runs, so run them on a schedule or before changing a prompt, schema, or model. They are not a per-commit check.
Scoring an evaluation run
The runner below walks the eval set and records, for each case, whether the output was valid, how many attempts it took, and whether the fields matched. It reuses extract_ticket, TicketTriage, and the other definitions from the previous example, and counts attempts by wrapping call_llm.
import json
def run_eval(path, call_llm):
rows = []
with open(path, encoding="utf-8") as f:
cases = [json.loads(line) for line in f if line.strip()]
for case in cases:
calls = 0
def counted(prompt):
nonlocal calls
calls += 1
return call_llm(prompt)
row = {"id": case["id"], "attempts": 0, "valid": False, "correct": False}
try:
result = extract_ticket(case["text"], counted)
row["valid"] = True
expected = case["expected"]
if expected is not None:
row["correct"] = all(
getattr(result, key) == value for key, value in expected.items()
)
except ValueError:
pass
row["attempts"] = calls
rows.append(row)
total = len(rows)
return {
"cases": total,
"valid_rate": sum(r["valid"] for r in rows) / total,
"first_try_rate": sum(r["valid"] and r["attempts"] == 1 for r in rows) / total,
"accuracy": sum(r["correct"] for r in rows) / total,
"failures": [r["id"] for r in rows if not r["valid"] or not r["correct"]],
}Each metric answers a different question.
- valid_rate is the share of cases that ended in a valid object, retries included. It measures what your users see.
- firsttryrate is the share that were valid on the first call. It measures the model's raw reliability. If it falls while valid_rate stays flat, the retry loop is hiding a problem and your costs are rising.
- accuracy is the share with correct field values. It is the only metric that exposes semantic errors.
- failures lists the case ids to read by hand.
Notice that a case with expected: null, like t003 above, counts as correct only if you define it that way. Decide per case what the right behavior is for empty or unusable input: raising an error, or returning other. Encode that decision in the eval set so the score reflects it.
Handling run-to-run variation
Real models do not return identical output each time, even at low temperature. A 90% score on 30 cases is 27 correct, and one case flipping changes the score by about 3 points. Use these habits so you do not chase noise:
- Run the set more than once and compare averages when a decision depends on a small difference.
- Compare changes on the same set, with the same settings, and change one thing at a time.
- Read the individual failures. A list of three failing ids tells you more than a percentage.
What to monitor in production
An eval set describes the inputs you imagined. Production shows you the inputs you did not. Log one record for every extraction, and keep sensitive content out of it where policy requires.
import json
import logging
import time
logger = logging.getLogger("extraction")
def logged_extract(ticket_text, call_llm, model_name, prompt_version):
attempts = 0
def counted(prompt):
nonlocal attempts
attempts += 1
return call_llm(prompt)
start = time.monotonic()
outcome = "ok"
try:
return extract_ticket(ticket_text, counted)
except ValueError:
outcome = "invalid_after_retries"
raise
finally:
logger.info(json.dumps({
"event": "extraction",
"outcome": outcome,
"attempts": attempts,
"model": model_name,
"prompt_version": prompt_version,
"input_chars": len(ticket_text),
"latency_s": round(time.monotonic() - start, 3),
}))The record carries the model name and a prompt version, so you can tell which change caused a shift. It stores the input length rather than the input text, which keeps personal data out of the logs. If you need the raw text to debug, store it in a separate, access-controlled place with a short retention period.
From these records, track the following.
| Metric | What it tells you | Typical alert |
|---|---|---|
| Failure rate (`invalid_after_retries`) | Requests that produced no usable data | Above a threshold you set from eval results |
| Retry rate (attempts above 1) | Hidden unreliability and extra cost | Sudden rise from your baseline |
| Latency | Retries and long outputs both add time | 95th percentile above your limit |
| Category distribution | Semantic drift | One label's share moves sharply |
| Truncation or refusal count | Output cut off or declined | Any sustained increase |
The category distribution row deserves attention. Semantic errors raise no exception, so the only sign may be that other suddenly makes up 40% of results when it used to be 10%. Either the inputs changed or the model's behavior did. Both are worth a look.
Common mistakes
- Testing only with valid replies. Your fake model should also return invalid JSON, fenced JSON, extra keys, and truncated text. Those are the replies that break code.
- Measuring only the final result. A pipeline with a 99% final success rate and a 60% first-try rate is working through retries. Track both numbers.
- Never updating the eval set. An eval set frozen at launch stops representing your traffic. Add real failures to it as they occur.
- Changing several things at once. If you change the prompt, schema, and model together, you cannot tell which change moved the score.
- Pinning nothing. Provider model aliases can point to new versions over time. Where the provider offers dated model versions, pin one, and record it in your logs so that a score change can be tied to a change you made.
- Logging full inputs by default. Tickets, emails, and documents often hold personal data. Log metadata first.
Putting it together
A workable minimum setup has four parts:
- Fake-model unit tests that run on every commit.
- A labeled eval set of at least 20 cases, run before any prompt, schema, or model change.
- One structured log record per extraction, with outcome, attempts, model, and prompt version.
- A recurring review of logged failures, with each real failure added to the eval set.
With these in place you can answer the question the whole tutorial leads to: how often does this step fail, and is that rate getting better or worse?
Exercise
Your eval run shows validrate of 0.98 and firsttry_rate of 0.71 on the same set that earlier gave 0.98 and 0.93. Nothing changed in the code except a provider model update. What does this tell you, and what would you check next?
Show answer
The retry loop is masking a drop in raw reliability. Users still see valid output, but the model now fails validation on the first call far more often, which costs extra calls and latency. Check the logged or recorded validation errors on first attempts to find the common pattern, such as a new code fence, an extra key, or a changed enum value. Then adjust the prompt or schema, or switch to schema-constrained output, and rerun the eval. Also consider pinning the earlier model version if the provider allows it.
Exercise
Write one fake-model test for extract_ticket that checks the function raises ValueError when the model replies with a valid JSON object that has an unknown category, on every attempt. What should the test assert about the number of calls?
Show answer
Use scripted with three identical replies such as '{"category": "praise", "priority": 1, "summary": "Thanks"}'. Call extractticket("x", fake) inside a try block, expect ValueError, and assert len(fake.prompts) == 3, because the default maxattempts is 3 and each reply fails the Literal check. You can also assert that the second prompt contains the word "category" to confirm the error was sent back.
Exercise
Why can a monitoring dashboard show a healthy failure rate of 0% while the pipeline is producing wrong results, and which two measures help you find the problem?
Show answer
The failure rate counts only structural failures, meaning output that did not validate. Semantic errors, such as a wrong but allowed category, pass validation and raise no exception. Two measures help: the distribution of output values over time, which shows shifts such as a surge in other, and accuracy on a labeled eval set or a human-reviewed sample of production outputs.