Sub topic 16
Testing Your Pipeline
This chapter assumes you have read the earlier chapters. You should know how to build an image or PDF request, preprocess inputs, and extract structured data. You should also be able to write basic pytest tests. The goal is to show which parts of a visual input pipeline you can test exactly, and how to measure the parts that depend on the model.
Why visual pipelines need a different test plan
A pipeline that sends images and PDFs has two kinds of behavior.
- Deterministic code includes media type detection, resizing, page rendering and request building. Normal unit tests cover it, and it needs no API key.
- Model behavior includes whether the model reads a small number correctly or invents a field that is not on the page. The output can vary between runs, and a single passing run proves little. You measure it with an evaluation, called an eval here: a fixed set of documents with known answers, scored the same way every time.
Keep the two kinds separate. If a deterministic bug, such as a wrong media type, is mixed into a model eval, it looks like "the model got worse" and wastes debugging time.
| Layer | What it catches | Needs the API? | When to run |
|---|---|---|---|
| Unit tests | Wrong media type, images not shrunk, bad base64 | No | Every commit |
| Request-shape tests | Content blocks in the wrong order or format | No | Every commit |
| Golden-set eval | Wrong values, hallucinated fields, regressions | Yes | Before releases and on model or prompt changes |
| Cost and latency checks | Token growth, slow requests | Yes | Same as the eval |
Layer 1: unit tests for preprocessing
The examples assume the helper functions from earlier chapters live in pipeline.py. These tests build their own images, so they need no fixture files.
import base64
import pytest
from PIL import Image
from pipeline import downscale, load_as_base64
def make_png(path, size):
Image.new("RGB", size, "white").save(path, format="PNG")
def test_base64_round_trip(tmp_path):
path = tmp_path / "a.png"
make_png(path, (10, 10))
media_type, data = load_as_base64(str(path))
assert media_type == "image/png"
assert base64.b64decode(data) == path.read_bytes()
def test_unknown_extension_raises(tmp_path):
path = tmp_path / "mystery.unknownext"
path.write_bytes(b"data")
with pytest.raises(ValueError):
load_as_base64(str(path))
def test_downscale_limits_longest_side(tmp_path):
src, dst = tmp_path / "big.png", tmp_path / "small.jpg"
make_png(src, (3000, 2000))
downscale(str(src), str(dst), max_side=1568)
with Image.open(dst) as img:
assert max(img.size) == 1568
def test_downscale_never_enlarges(tmp_path):
src, dst = tmp_path / "tiny.png", tmp_path / "tiny.jpg"
make_png(src, (200, 100))
downscale(str(src), str(dst))
with Image.open(dst) as img:
assert img.size == (200, 100)The "never enlarges" test matters. Upscaling adds tokens and no information, so a regression there raises cost without improving results.
For PDF rendering, test with a one-page PDF you generate or keep in the repo. Assert that len(render_pages(path)) equals the page count and that each result starts with the PNG signature b"\x89PNG".
Layer 2: request-shape tests
Most request errors come from a wrong structure. Put request building in its own function so you can test it without a network call.
def build_image_message(media_type, data, question):
"""Image block first, then the text block."""
return [
{
"role": "user",
"content": [
{
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data},
},
{"type": "text", "text": question},
],
}
]
def test_image_precedes_question():
messages = build_image_message("image/png", "AAAA", "What is the total?")
blocks = messages[0]["content"]
assert [b["type"] for b in blocks] == ["image", "text"]
assert blocks[0]["source"]["media_type"] == "image/png"Add similar tests for your multi-image builder (labels stay next to their images) and for PDF requests (type is document and the media type is application/pdf).
Also test error handling with a fake client that raises the errors you expect: payload too large, unsupported media type and rate limiting. Assert that your code resizes and retries, retries with backoff, or fails with a clear message. Do not wait for the provider to produce these errors in production.
Layer 3: a golden-set eval
A golden set is a folder of representative inputs plus a JSON file of the correct answers. Start with 20 to 50 documents. Choose them to cover the failure modes from earlier chapters:
- small or dense text
- rotated or skewed scans
- low-resolution photos
- multi-page PDFs
- charts with no printed values
- documents where a requested field is missing
The last category is the most useful one. When the expected value is null, the test checks whether the model admits the field is absent or invents one.
Score at the field level, not the document level. A document with 9 of 10 fields right is much better than one with 2 of 10 right, and exact document match hides that. Normalize values before comparing, so "$1,200.50" and 1200.5 count as equal.
from decimal import Decimal, InvalidOperation
def normalize(field, value):
if value is None:
return None
if field == "total":
try:
return Decimal(str(value).replace(",", "").replace("$", "").strip())
except InvalidOperation:
return None
return str(value).strip().lower()
def score_case(expected, actual):
return {
field: normalize(field, actual.get(field)) == normalize(field, want)
for field, want in expected.items()
}
def evaluate(extract, cases):
per_field, failures = {}, []
for case in cases:
results = score_case(case["expected"], extract(case["path"]))
for field, ok in results.items():
hits, total = per_field.get(field, (0, 0))
per_field[field] = (hits + ok, total + 1)
bad = [f for f, ok in results.items() if not ok]
if bad:
failures.append((case["path"], bad))
return per_field, failures
cases = [
{"path": "inv1.png", "expected": {"vendor": "Acme", "total": "1200.50", "po": None}},
{"path": "inv2.png", "expected": {"vendor": "Globex", "total": "89.00", "po": "PO-7"}},
]
fake_outputs = {
"inv1.png": {"vendor": "ACME", "total": "$1,200.50", "po": "PO-1"}, # invented po
"inv2.png": {"vendor": "Globex", "total": 89, "po": "PO-7"},
}
per_field, failures = evaluate(lambda p: fake_outputs[p], cases)
for field, (hits, total) in per_field.items():
print(f"{field}: {hits}/{total}")
print(failures)Running this prints vendor: 2/2, total: 2/2, po: 1/2, then [('inv1.png', ['po'])]. In your real eval, replace the lambda with a function that calls the model and parses its JSON. The fake extractor lets you test the scoring code itself before it judges the model.
Slice results and measure variance
An overall accuracy of 94% can hide a 40% rate on rotated scans. Tag each case with a category and report accuracy per tag.
Run each case several times, for example three to five, and note fields whose answers change between runs. Unstable fields are the ones most likely to be misread, such as small digits. For those fields, consider sending a higher-resolution crop or asking for a second read.
Layer 4: cost and latency checks
Record the token usage and wall-clock time of every eval request. Most providers return input token counts in the response, for example message.usage.input_tokens in the Anthropic SDK. Save the median and the worst case per category.
Set budgets from your first good run, such as "a typical page image costs no more than N input tokens". Fail the eval when a change pushes a category over its budget. This catches a preprocessing change that quietly stops resizing, or a switch from rendered pages to native PDF input that doubles the bill.
Regression discipline
- Pin the exact model identifier in the eval config. Rerun the full eval when you change the model, the prompt, the resize limit or the render DPI.
- Store each run's per-field scores in version control or a results table. Compare against the last accepted baseline, and fail on a drop larger than your tolerance, for example 2 percentage points on any field.
- When production produces a bad result, add that document to the golden set. The set then grows to match real failures.
- Use the eval to decide between native PDF, rendered pages and text extraction. Run the same golden set through each route and compare accuracy and cost.
Exercise
Your eval shows the total field at 97% accuracy, but production users report wrong totals on photographed receipts. Give two likely reasons the eval missed this, and one change to the golden set.
Show answer
First, the golden set probably holds mostly clean scans and few phone photos, so the eval does not represent production input. Second, a single overall score hides weak categories, and photographed receipts may be a small slice that scored badly. Add photographed receipts to the golden set, including blurred, angled and dim ones, tag them by category, and report accuracy per tag so a weak slice cannot hide behind a high average.