{"slug": "reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model", "title": "Reading a cutting list from a photo with an LLM, without trusting the model", "summary": "A developer built a Cloudflare Pages Function (functions/api/list-ai.js) for SyntaxFlow's glass cutting optimiser that uses a vision LLM to read handwritten cutting lists from photos or PDFs while treating the model's output as untrusted candidates rather than final data. The endpoint enforces a strict JSON schema with unit and confidence enums, re-parses and type-checks output server-side, rejects truncated responses, converts units in code, drops implausible dimensions with a count, and flags every response as needing human review. The design also marks attachments with a random nonce and includes an injectionSeen field to detect prompt-injection attempts embedded in the sheet.", "body_md": "A glazier gets a photo of a handwritten sheet: \"V1 1200 x 800, 2 uds\", a crossed-out line, a phone number. A vision model can read that. The trouble is what happens when it reads it *wrong* and the numbers go straight into a machine that cuts expensive glass. A 1200 mistaken for 1700 is not a typo, it is a pane in the bin.\n\nThis is how the endpoint behind the \"read the list from a photo or PDF\" option of [SyntaxFlow](https://syntaxflow.io/glass/cutting-optimiser/) is built (`functions/api/list-ai.js`, a Cloudflare Pages Function). The design assumption is in one sentence of its header: the model's word is not trusted.\n\nThe model never decides what goes into the list. It returns candidate rows. Then deterministic code validates them, flags the doubtful ones, and the page shows everything for review. Nothing enters the list until the person says so. Every response carries `review: true`, and the header says it plainly: \"ALWAYS needs-review\".\n\nThe system prompt asks for one row per line, in sheet order, with the text of the line *as read*, the sizes as numbers *in the unit written, never converted*, a quantity only if written (0 otherwise), and a confidence of high, medium or low. It forbids inventing rows, adding up or converting. Conversion belongs to code, where it can be tested.\n\nThe file itself is untrusted: a handwritten sheet can contain \"ignore your instructions\". The prompt marks the attachment with a random nonce, says it is data only, and the schema has an `injectionSeen` boolean so the model can report it saw such text.\n\nThe request asks the API for structured output with a JSON schema, and no tools:\n\n``` js\nexport const OUTPUT_SCHEMA = {\n  type: \"object\", additionalProperties: false,\n  required: [\"readable\", \"unit\", \"rows\", \"injectionSeen\"],\n  properties: {\n    readable: { type: \"boolean\" },\n    unit: { type: \"string\", enum: [\"mm\", \"cm\", \"m\", \"in\", \"unknown\"] },\n    injectionSeen: { type: \"boolean\" },\n    rows: { type: \"array\", items: {\n      type: \"object\", additionalProperties: false,\n      required: [\"text\", \"a\", \"b\", \"qty\", \"ref\", \"confidence\", \"unit\"],\n      properties: {\n        text: { type: \"string\" }, a: { type: \"number\" }, b: { type: \"number\" },\n        qty: { type: \"integer\" }, ref: { type: \"string\" },\n        confidence: { type: \"string\", enum: [\"high\", \"medium\", \"low\"] },\n        unit: { type: \"string\", enum: [\"mm\", \"cm\", \"m\", \"in\", \"same\"] } } } } } };\n```\n\nEnums for units and confidence leave the model nothing to improvise, and `\"unknown\"` is allowed so it is never forced to guess a unit. A per-row unit exists because real sheets mix: \"1,20 x 0,80\" and \"60x40\" in one list.\n\nBut a schema constrains the *shape*, not the truth, and I do not rely on it: the server parses the output again by hand (`JSON.parse`, type checks, a cap on the number of rows) and answers \"invalid\" on any deviation. A truncated output (`stop_reason === \"max_tokens\"`) is rejected rather than repaired.\n\nUnits are converted on the server from a table, and each size must land inside what the trade can plausibly cut:\n\n``` js\nconst TO_MM = { mm: 1, cm: 10, m: 1000, in: 25.4 };\nranges: { glass: [10, 6500], panel: [10, 6500], linear: [10, 15000] },\nqty: [1, 999]\n\nconst a = Math.round(r.a * rk * 10) / 10;\nconst okA = isFinite(a) && a >= lo && a <= hi;\nif (!okA || !okB || (r.qty !== 0 && (r.qty < qlo || r.qty > qhi))){\n  dropped++; continue;           // counted in `dropped`\n}\n```\n\nA \"12000 x 800\" glass pane never reaches the list. It is dropped and counted; silently losing a row would be as bad as accepting a wrong one.\n\nWhen the sheet gives no unit, the guess is explicit and flagged (`guessedUnit`): if every size is under 10 and at least one has decimals, it is metres, otherwise millimetres. That mirrors the rule of the same tool's paste reader.\n\nMy favourite check. The model returns both the parsed numbers and the `text` it claims to have read. If the model reads \"1200 x 800\" but outputs `b: 600`, the two disagree, and a disagreement is a hallucination detector that costs nothing.\n\n```\nfunction figures(text){            // every number in the line, both decimal conventions\n  const out = new Set();\n  for (const m of String(text).matchAll(/\\d+(?:[.,]\\d+)*/g)){\n    const t = m[0], digits = t.replace(/[.,]/g, \"\");\n    out.add(String(+digits));                 // \"1.250,5\" → 12505 ...\n    const lastSep = Math.max(t.lastIndexOf(\".\"), t.lastIndexOf(\",\"));\n    if (lastSep > 0){                          // ... and \"1250.5\"\n      out.add(String(+(t.slice(0, lastSep).replace(/[.,]/g, \"\") + \".\" + t.slice(lastSep + 1))));\n    }\n  }\n  return out;\n}\nif (!same(figs, r.a) || !same(figs, r.b)) why.push(\"no-cuadra\");   // does not add up\nif (r.qty === 0) why.push(\"cantidad\");                            // quantity not written\nif (r.confidence === \"low\") why.push(\"legible\");\n```\n\nBoth readings of the separator are collected because `1,25` may be 1.25 m or 125 cm. I ran the real function on five invented rows:\n\n| Row as returned | Result | \n|---|---|\n| `V1 1200 x 800 2 uds` , a=1200, b=800, qty=2 | accepted, no flag | \n| `V2 1200 x 800` , but b=600 | kept, flagged \"does not add up\" | \n| `V3 60x40 x3` , unit cm | converted to 600 × 400 mm, no flag | \n| `V4 12000 x 800` | dropped, counted | \n| `V5 1,25 x 0,8` , qty 0, unit m | 1250 × 800 mm, flagged \"quantity not written\" | \n\nA row whose numbers do not appear in its own transcription is the exact signature of a model that \"improved\" the sheet. The same goes for a quantity above 1 that is not in the line. A flagged row is not discarded: the page asks the person to compare it with the photo.\n\nThe text and reference fields end up in a web page and possibly in a link. They are stripped of control characters, angle brackets, braces, backticks, URLs, and cut to 90 and 40 characters. A model that was fooled by an embedded instruction still cannot smuggle markup or a link through the reference field.\n\nThe cheap checks run first and refuse without spending: the file's real type from its magic bytes (not the declared one), size, pixel dimensions read from its own header, number of PDF pages; then a monthly quota and a euro budget reserved before the call in a single conditional insert. The file is not stored anywhere: it is read from the request, sent to the model provider and dropped. Anonymous visitors are counted by a hash with the month inside it, so one cannot be followed from month to month.\n\nThe tests use a fake provider, so they prove the checks above work, not how often the model reads a messy sheet correctly. In production it has read only a handful of real sheets so far (seven at the time of writing), far too few for an accuracy figure, and I will not invent one. The design is meant so that the answer to \"how accurate is the model?\" matters less: a wrong row is either dropped, flagged, or caught by a person looking at the photo next to the table.\n\nThe optimiser it feeds is at [syntaxflow.io/glass/cutting-optimiser/](https://syntaxflow.io/glass/cutting-optimiser/).\n\n*I'm the author of SyntaxFlow, the set of workshop calculators this article is about.*\n\n*Written with the help of an AI assistant; the code, the figures and the claims were checked against the repository before publishing.*", "url": "https://wpnews.pro/news/reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model", "canonical_source": "https://dev.to/elam_ucedaherrero_0bc02f/reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model-2lg9", "published_at": "2026-11-28 12:09:43+00:00", "updated_at": "2026-11-28 12:14:21.394202+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools", "computer-vision", "ai-safety"], "entities": ["SyntaxFlow", "Cloudflare Pages"], "also_reported_by": [], "takeaway": "Treat vision-model extraction as untrusted candidates: enforce a JSON schema with unit/confidence enums, re-validate and range-check every dimension in code, drop and count implausible rows, and require human review before data reaches downstream machines.", "recommendation": {"advice": "Validate LLM-extracted numbers with deterministic range checks and cross-check parsed values against the model's own quoted source text before letting any row into a production list.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model", "markdown": "https://wpnews.pro/news/reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model.md", "text": "https://wpnews.pro/news/reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model.txt", "jsonld": "https://wpnews.pro/news/reading-a-cutting-list-from-a-photo-with-an-llm-without-trusting-the-model.jsonld"}}