AI-assisted development
Keeping AI out of the maths: a validated vision-model pipeline
How I put a vision model behind a validated boundary in MealPath, so the model only suggests foods and portions, the user confirms every item, and exact server-side arithmetic produces the nutrition numbers.
On this page
MealPath is a demo I built to answer one question: how do you put a vision model into a product without letting it decide anything that has to be right? The user analyses a meal photo, the model suggests what is on the plate, the user checks those suggestions, and the app calculates nutrition and builds a three-day plan.
A model is useful for looking at a plate and saying “probably chicken, about 150 g”. It is the wrong tool for the step after that. Nutrient totals have to be repeatable, traceable to reference data and the same on every run. So I drew a hard line: the model proposes, the user confirms, deterministic code decides.
MealPath is an independent engineering showcase. Its reference values are synthetic, and it gives general nutrition information, not medical advice.
What the model is allowed to say
The model receives the photo, short instructions and the food catalogue as id: name pairs. It never sees a nutrient value. The instructions say “Use only food ids from the catalogue below. Never invent ids” and “Do not estimate calories or nutrients.”
Instructions are not guarantees, so the real limit is the response schema. A candidate from the sample dinner bowl fixture:
{
"ref": "c2",
"label": "Rice (brown or white)",
"status": "ambiguous",
"food_id": null,
"alternatives": ["food.rice-brown-cooked", "food.rice-white-cooked"],
"estimated_quantity": { "value": 180, "unit": "g" },
"notes": "Grain colour is unclear under warm lighting"
}
The status is matched, ambiguous or unresolved. The only numeric field the schema allows is a portion estimate: whole grams from 1 to 2,000. The schema sets additionalProperties: false at every level, so there is nowhere to put calories, protein or a confidence score, and a response that adds one is rejected.
The live provider requests strict structured output (response_format: json_schema). Strict modes accept only a subset of JSON Schema, so the provider sends a reduced copy (no uniqueItems, const rewritten as enum), and my own validator then checks the full schema. I don’t rely on the provider’s guarantee.
The validation pipeline
Every response goes through the same parser, whether it came from the model or a fixture:
| Stage | Check | On failure |
|---|---|---|
| Size | raw output ≤ 32 KiB | too_large |
| Parse | json_decode, depth ≤ 8, throw on error |
malformed_json |
| Schema | full JSON Schema v1.0 | schema_violation |
| Semantic | every id exists in the catalogue; status matches food_id and alternatives; no duplicate refs |
unknown_identifier / impossible_value |
The rule I care most about is reject, never repair. If one matched item has an id that is not in the catalogue, the whole response is thrown out. It is not downgraded to “unresolved” or swapped for the nearest match. Silent repair would hide exactly the failures I need to see.
In live mode, a rejected response gets one second chance. The first call uses a cheap, fast model tier. If its output fails validation, the server makes one call to a more capable tier, and the UI labels the result “re-checked with a more capable model”. That is a second analysis, not a verification of the first. If that fails too, the user gets a 422 (“The analysis could not be used safely”) and nothing is stored. There are no further retries. ADR 0003 records why: using the stronger tier for every call would cost about 20× as much at the listed prices.
Provider failures don’t escalate. They map to typed errors, such as 504 for a timeout (the client limit is 30 s) and 422 for a refusal, and each one points the user to the sample analysis.
What the user confirms, and what the server computes
In the sample bowl, the review screen marks the rice “Choose a match” (brown or white) and the sauce “Not in catalogue”, so the user has to resolve both. Editing a portion or a food un-confirms that item.
The server doesn’t trust the browser either. A mandatory rule, nutrition.require-confirmed-inputs@1.0, runs before any calculation. Every item must point to a real catalogue food and be explicitly confirmed, and portions are range-checked again. Otherwise the response is a 422 listing each bad field, and nothing is written.
The arithmetic has no floating point. Reference values are stored as whole tenths per 100 g, and every amount is an exact fraction (simplified from ExactAmount):
// tenths per 100 g × grams / 1000, kept as numerator/denominator
public static function fromTenthsPer100g(int $tenths, int $grams): self
{
return new self($tenths * $grams, 1000);
}
Sums stay exact and are rounded once, half-up to one decimal, for display. One test shows why: two items that each contribute 0.45 g of a nutrient display as 0.5 g each, but their total is exactly 0.9 g, not the 1.0 g you get by adding rounded values. Values are sent as strings like "31.4", so the browser shows the calculated value and never does arithmetic on it. A missing nutrient value makes the total “unknown” and names the food responsible. It never counts as 0.
Recipe ranking works the same way: registered, versioned rule handlers with explanations, recorded in saved plans. ADR 0004 rules out ranking by a language model as neither repeatable nor explainable.
How I tested it
All automated tests use fixtures, not live AI calls. The fixture provider is the default and returns committed JSON for eight sample meals, each with an ambiguous or unresolved item. Fixtures go through the same parser, so a defective fixture fails exactly like a bad model response, and CI needs no API key.
The parser tests start from one valid response and check 11 rejection cases, including an unknown id, a duplicate ref, ounces instead of grams, an extra confidence field and a top-level calories: 500. Separate tests cover malformed JSON and output over 32 KiB.
The live path is tested with a mocked HTTP transport. A valid fast-tier result makes one call. An unknown food id escalates exactly once. Two invalid outputs (not json, then a bare {"schema_version":"1.0"}) give a 422, two calls and zero stored analyses. A non-image upload is rejected before any provider call. Provider unit tests cover timeouts, refusals, truncated output, errors returned with HTTP 200 and a missing key.
On 2026-11-26, the Playwright journey with axe passed 7/7 against production. After review, the sample bowl comes to 546.0 kcal and 71.0 g protein. Live analysis I have only checked by hand: two Creative Commons photos on the fast tier, both schema-valid in 5.4–6.9 s, with foods outside the catalogue returned as unresolved.
Privacy: the app never keeps the photo
ADR 0005 is short: the demo doesn’t need the photo after analysis, so it doesn’t keep it. Live analysis requires a consent checkbox and, on the public demo, an access code. Then:
- The server reads PHP’s upload temp file into memory and deletes the file straight away.
- The type is detected from the content (JPEG, PNG or WebP, up to 5 MB), and oversized dimensions are rejected before decoding, as a guard against decompression bombs.
- GD decodes the image, applies the EXIF orientation, downscales to at most 2,048 px and re-encodes to JPEG in
php://memory. Re-encoding drops EXIF, GPS and other metadata. - The JPEG is sent to the provider and discarded. What the provider does with it is governed by its terms, not by my code.
Only the validated candidate JSON is stored, owned by the anonymous session, which expires after 24 hours. Logs never hold image bytes, prompts or raw model output, and the browser shows the photo from a local object URL. Sessions are isolated by session-owned rows that are deleted with the session, not by PostgreSQL row-level security.
Limitations
- The reference data is synthetic: internally consistent, not real nutrition data.
- I haven’t measured live recognition accuracy systematically. Two photos is a smoke test, not an evaluation.
- Allergen exclusions use catalogue declarations and treat unknown status as unsafe, but they are not an allergy safety guarantee.
- Photos can’t be revisited, and live recognition can only be debugged from outcome codes and counts.
What I’d do next
- Run a real evaluation: fast and smart tiers on 20–30 photos I own, including the escalation rate.
- Grow the catalogue. With 31 foods, many real plates will have
unresolveditems. That is correct behaviour, but it pushes work onto the user.
Takeaways
- Give the model a narrow vocabulary (real ids, a fixed status, a bounded portion) and validate it yourself, even with strict structured output.
- Reject, don’t repair. A rejected response is easier to debug than one that was quietly fixed.
- Make fixtures the default. If the demo and CI depend on a live model, they are only as reliable as that model.
- Keep the maths in code you can test. Integer fractions and one rounding step are boring, and identical every time.
Try the guided demo with the sample meal, or read the MealPath case study for the architecture, decisions and test evidence.