Dev.to Security 🔐 Cybersecurity 👁 0 📖 5 min read

Reading a cutting list from a photo with an LLM, without trusting the model

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 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.

This is how the endpoint behind the "read the list from a photo or PDF" option of SyntaxFlow 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.

Principle: the model transcribes, the code decides

The 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".

1. The prompt asks for transcription, not interpretation

The 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.

The 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.

2. A strict schema

The request asks the API for structured output with a JSON schema, and no tools:

export const OUTPUT_SCHEMA = {
  type: "object", additionalProperties: false,
  required: ["readable", "unit", "rows", "injectionSeen"],
  properties: {
    readable: { type: "boolean" },
    unit: { type: "string", enum: ["mm", "cm", "m", "in", "unknown"] },
    injectionSeen: { type: "boolean" },
    rows: { type: "array", items: {
      type: "object", additionalProperties: false,
      required: ["text", "a", "b", "qty", "ref", "confidence", "unit"],
      properties: {
        text: { type: "string" }, a: { type: "number" }, b: { type: "number" },
        qty: { type: "integer" }, ref: { type: "string" },
        confidence: { type: "string", enum: ["high", "medium", "low"] },
        unit: { type: "string", enum: ["mm", "cm", "m", "in", "same"] } } } } } };

Enums 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.

But 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.

3. Validate in code: convert, range-check, drop

Units are converted on the server from a table, and each size must land inside what the trade can plausibly cut:

const TO_MM = { mm: 1, cm: 10, m: 1000, in: 25.4 };
ranges: { glass: [10, 6500], panel: [10, 6500], linear: [10, 15000] },
qty: [1, 999]

const a = Math.round(r.a * rk * 10) / 10;
const okA = isFinite(a) && a >= lo && a <= hi;
if (!okA || !okB || (r.qty !== 0 && (r.qty < qlo || r.qty > qhi))){
  dropped++; continue;           // counted in `dropped`
}

A "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.

When 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.

4. Cross-check the number against the transcribed line

My 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.

function figures(text){            // every number in the line, both decimal conventions
  const out = new Set();
  for (const m of String(text).matchAll(/\d+(?:[.,]\d+)*/g)){
    const t = m[0], digits = t.replace(/[.,]/g, "");
    out.add(String(+digits));                 // "1.250,5" → 12505 ...
    const lastSep = Math.max(t.lastIndexOf("."), t.lastIndexOf(","));
    if (lastSep > 0){                          // ... and "1250.5"
      out.add(String(+(t.slice(0, lastSep).replace(/[.,]/g, "") + "." + t.slice(lastSep + 1))));
    }
  }
  return out;
}
if (!same(figs, r.a) || !same(figs, r.b)) why.push("no-cuadra");   // does not add up
if (r.qty === 0) why.push("cantidad");                            // quantity not written
if (r.confidence === "low") why.push("legible");

Both 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:

Row as returned Result
V1 1200 x 800 2 uds, a=1200, b=800, qty=2 accepted, no flag
V2 1200 x 800, but b=600 kept, flagged "does not add up"
V3 60x40 x3, unit cm converted to 600 × 400 mm, no flag
V4 12000 x 800 dropped, counted
V5 1,25 x 0,8, qty 0, unit m 1250 × 800 mm, flagged "quantity not written"

A 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.

5. Sanitise everything that is text

The 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.

6. Limits before spending, and privacy by omission

The 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.

What I have not verified

The 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.

The pattern

  1. Ask for transcription plus the raw text, never for interpretation.
  2. Strict schema, then re-validate by hand anyway.
  3. Convert and range-check in code.
  4. Cross-check every number against the model's own transcription.
  5. Count what you drop and show it.
  6. Human review is the last gate, not a feature.

The optimiser it feeds is at syntaxflow.io/glass/cutting-optimiser/.

I'm the author of SyntaxFlow, the set of workshop calculators this article is about.

Written with the help of an AI assistant; the code, the figures and the claims were checked against the repository before publishing.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.