All posts
Technical

Turning messy enquiry emails into database rows with an LLM, without trusting what it says

Getting a model to return JSON is the easy part. This is a pipeline that checks every reply before it is saved, repairs or sets aside the ones that fail, survives rate limits and bad keys, and can be run twice safely. Plus the three mistakes a schema could not catch.

Asking a model to read an email and return JSON works in the first five minutes. The email says “boiler banging, EX4 1AB, any day in the next fortnight”, and back comes tidy JSON with a service, a postcode and an urgency.

What decides whether it is usable is the other 5% of replies: the JSON wrapped in friendly chat, the one cut off halfway, the postcode that is not a postcode, the rate limit in the middle of a batch. If those go straight into a database, you do not have a pipeline, you have a source of quiet bad data.

So I built a small one that treats the model’s reply as untrusted input. It is a demo for my own portfolio. The heating firm, its customers and all forty emails are made up.

The rule: nothing is saved until the reply passes

Each email goes to a model through OpenRouter, which is asked for JSON. The reply is then checked against a strict schema before anything touches the database:

  • the service and the urgency must come from fixed lists;
  • the postcode must be a real UK postcode format, and is tidied to the standard form;
  • the budget must be between £0 and £100,000;
  • a preferred date cannot be before the email arrived;
  • an email marked as spam must have the service “other”.

The request does tell the model about this schema, but I treat that as a hint, not a guarantee. The checking happens locally on every reply regardless, in Pydantic, whatever the model was told.

When a reply fails

A failed check is the normal case, so the pipeline has a short ladder for it:

  1. The reply is not valid JSON, or breaks a rule. The model gets one more call that quotes the exact errors back to it. If that second reply passes, it is saved.
  2. It fails again. The record is set aside in a quarantine table with the raw reply and the reason. Nothing half-filled is saved.
  3. The reply was cut off at the length limit. One more call with double the limit. If it is cut off again, it is set aside.

Replies that come back plain, wrapped in a code fence or buried in chat are all parsed the same way, so a model being chatty does not count as a failure.

When the API fails

Failures from the API itself sort into three kinds, and each gets a different answer:

  • Rate limits, server errors, timeouts, dropped connections are retried, up to five attempts, with growing randomised waits. A Retry-After header wins, capped at 60 seconds.
  • A wrong key, no credit left, or a spent budget limit stops the whole run immediately. Every remaining record would fail the same way, so carrying on would only burn time and fill the quarantine with records that were never at fault.
  • One request rejected, for example by a moderation flag, sets that one record aside and the run carries on.

There is one more guard. If three records in a row run out of retries, the run stops, because the API is probably down. Those records wait for a later run with --retry-quarantined.

Safe to run twice

A pipeline you are scared to re-run is a pipeline you stop using. So every record gets a fingerprint built from the email, the prompt version, the schema version, the model, and whether the replies were live or replayed.

The consequences are the ones you would want:

  • Running the same file twice makes no model calls the second time.
  • Editing one email re-processes only that email.
  • Changing the prompt, the schema or the model re-processes everything, because the old answers no longer mean the same thing.
  • A crash or Ctrl+C loses nothing, because everything finished is already saved. The next run carries on from where it stopped.

Every step is also logged: each call’s latency and tokens, each retry and its wait, each validation failure and each repair.

Proving it, with sabotage

I wanted to see it recover, not just trust that it would. The demo has a chaos mode that injects rate limits, timeouts and broken replies on purpose, and a demo mode that replays real model replies recorded from one live run, so anyone can run it without an API key.

The test I care about most is the end-to-end one: a run with injected faults has to save exactly the same rows as a clean run. If recovery changes the data, it is not recovery.

On the recording run, 37 of the 40 lines were saved and 3 were set aside as bad input. The whole run cost about 3 US cents on gpt-5.4-mini, which was cheap and good at structured output. The schema, the retry logic and the repair step are my own code, not a library, because they are exactly the behaviour I did not want hidden.

The part a schema cannot fix

This is the section I most want people to read. Every row that was saved passed the schema. Some of them were still wrong.

In the recording run, the model:

  • filed a smell of gas as a gas safety check (it did at least mark it as an emergency);
  • made up a visit date from the phrase “weekday afternoons”;
  • graded “Boiler broken … ASAP” as this week, not an emergency.

All three are valid values in valid fields. A schema can tell you an answer is shaped correctly. It cannot tell you it is right. A safety-related email filed under the wrong service, with the wrong urgency, is the sort of mistake that matters, and it sails through every check described above.

So the honest limit of a pipeline like this is that its output is safe to store, not safe to act on. Before anyone is sent to a house on the strength of a row, either a person has to look at the rows, or a second check has to, and the second check needs to be tested for its own mistakes.

What it does not do

  • Records run one at a time. This job is not limited by speed, and one at a time is easier to reason about and test.
  • A bad input line with no usable id is keyed by its line number, so if you fix it, the old row stays in the quarantine table. There is no command yet to remove it.
  • It uses SQLite, which runs with no setup. The upserts are standard SQL, so moving to Postgres would change one module.

What I would take from it

  • Treat the model’s reply as untrusted input, and validate it locally every time, whatever you told the model.
  • When a reply fails, send the exact errors back once. If that fails, set the record aside with the raw reply.
  • Split API failures into “wait and retry”, “stop the whole run” and “skip this record”.
  • Fingerprint the work, so re-running is safe and changing the prompt re-does the right things.
  • Test recovery by breaking things on purpose, and check the data comes out identical.
  • Validation proves a row is well-formed, not that it is correct. Plan for who checks the rest.