Skip to content

Extraction with review

Real SDK path and PostgreSQL rules; the model's answers are scripted. What is real

How it works

This is a working version of an extraction-with-review task: take each input, pull out the key details, return a strictly structured result, have a person review it before anything goes out, and store the results in PostgreSQL. The inputs are order emails to an invented wholesale supplier. The part that matters is what the code does when the model gets it wrong, so the fourteen messy cases are the centre of it.

What is real, and what is scripted

PartHere
The structured-output pathReal. Every answer goes through the Vercel AI SDK's generateText with Output.object and a Zod schema, on the server. The SDK's own JSON parsing, schema validation and errors run on what the model returns.
Retry, repair and flagsReal. Plain TypeScript, unit tested, run on the server for every email.
The databaseReal PostgreSQL, through PGlite (PostgreSQL built for WebAssembly), running in your browser. Constraints and triggers behave as they do on a server.
The modelScripted. A MockLanguageModelV4 from ai/test answers for the sample emails, so every failure here repeats exactly. No provider is called, there is no network request to one and no API key. Some of its answers are wrong on purpose, each in one specific way. This sample rehearses the handling; it is not evidence of how any provider behaves.
SendingSimulated. Approving writes a row to the outbox table. Nothing is emailed.
Emails, companies, peopleFictional. The sample set carries a sender name and domain instead of a full address, so it contains no contact details.

Swapping in a real provider

The model is one argument. The server route builds it and hands it to the pipeline, which only asks for the SDK's LanguageModel type:

// app/api/extract/route.ts
await runExtraction({
  email,
  // pass a provider's model object
  // here instead:
  model: createSimulatedModel(),
  modelLabel: SIMULATED_MODEL_LABEL,
  promptVersion,
});

The prompt, the schema, the retry rules, the flags, the tables and the review screen stay as they are. Three things would need real work, and this sample does not claim them: the token count here is a rough four characters per token and would become the provider's own count; the budgets below are sized for the sample emails; and how a given provider reports a refusal or a cut-off has to be tested against that provider, since nothing here called one.

The schema, and why it is shaped this way

  • Every key is required; a missing value is null. The model is never pushed to invent a value or to drop a key, and "missing" becomes its own flag instead of a guess.
  • Each extracted value carries a quote: the exact words it was read from. Code looks the quote up in the email. That is the evidence the reviewer sees underlined, and a value whose quote is not in the email is blocked.
  • Nothing the code can copy is asked of the model. Message id, received time, sender, subject and the content hash come from the email record.
  • No field can approve or send. Whatever an email says to the model, the most the model can do is fill in order details that a person then reads.
  • The date is stored twice: as written, and as a calendar date only when it cannot be read two ways. Units are stored as written; code does the converting.
  • Business rules are a second layer, in code. Totals that do not add up, a date in the past or a quantity of zero produce flags for a person, not failed extractions. The same rules run again on anything a reviewer types into the edit form.

Schema version order/s1. This is the JSON Schema that Zod's z.toJSONSchema produces from it, read when this page was built; the SDK passes the schema to the model as the response format.

Show the JSON Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "intent": {
      "type": "string",
      "enum": [
        "new_order",
        "change_to_order",
        "cancellation",
        "question_only",
        "not_an_order"
      ]
    },
    "language": {
      "type": "string",
      "enum": [
        "en",
        "fr",
        "other"
      ],
      "description": "The language the email is written in."
    },
    "customer_name": {
      "type": "object",
      "properties": {
        "value": {
          "type": [
            "string",
            "null"
          ]
        },
        "quote": {
          "type": "string",
          "description": "The exact words from the email that support the value. Empty when the value is null."
        }
      },
      "required": [
        "value",
        "quote"
      ],
      "additionalProperties": false
    },
    "po_number": {
      "type": "object",
      "properties": {
        "value": {
          "type": [
            "string",
            "null"
          ]
        },
        "quote": {
          "type": "string",
          "description": "The exact words from the email that support the value. Empty when the value is null."
        }
      },
      "required": [
        "value",
        "quote"
      ],
      "additionalProperties": false
    },
    "stated_total": {
      "type": "object",
      "properties": {
        "value": {
          "description": "The order total the email states. Never calculate it.",
          "type": [
            "number",
            "null"
          ]
        },
        "quote": {
          "type": "string",
          "description": "The exact words from the email that support the value. Empty when the value is null."
        }
      },
      "required": [
        "value",
        "quote"
      ],
      "additionalProperties": false
    },
    "requested_delivery_date": {
      "type": "object",
      "properties": {
        "as_written": {
          "description": "The delivery date exactly as the email writes it.",
          "type": [
            "string",
            "null"
          ]
        },
        "iso": {
          "description": "YYYY-MM-DD, only when the written date cannot be read two ways. Otherwise null.",
          "type": [
            "string",
            "null"
          ]
        },
        "quote": {
          "type": "string",
          "description": "The exact words from the email that support the value. Empty when the value is null."
        }
      },
      "required": [
        "as_written",
        "iso",
        "quote"
      ],
      "additionalProperties": false
    },
    "ship_to": {
      "type": "object",
      "properties": {
        "address": {
          "anyOf": [
            {
              "type": "object",
              "properties": {
                "street": {
                  "type": "string"
                },
                "city": {
                  "type": "string"
                },
                "region": {
                  "type": "string"
                },
                "postal_code": {
                  "type": "string"
                }
              },
              "required": [
                "street",
                "city",
                "region",
                "postal_code"
              ],
              "additionalProperties": false
            },
            {
              "type": "null"
            }
          ]
        },
        "quote": {
          "type": "string",
          "description": "The exact words from the email that support the value. Empty when the value is null."
        }
      },
      "required": [
        "address",
        "quote"
      ],
      "additionalProperties": false
    },
    "currency": {
      "type": "string",
      "enum": [
        "CAD",
        "USD",
        "not_stated"
      ]
    },
    "line_items": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "description": {
            "type": "string",
            "description": "The item as the email names it."
          },
          "sku": {
            "description": "The item code if the email gives one, else null.",
            "type": [
              "string",
              "null"
            ]
          },
          "quantity": {
            "description": "The number ordered, as written. Null if not stated.",
            "type": [
              "number",
              "null"
            ]
          },
          "unit": {
            "type": "string",
            "enum": [
              "each",
              "case",
              "box",
              "pallet",
              "kg",
              "lb",
              "not_stated"
            ],
            "description": "The unit the quantity is in. Do not convert units."
          },
          "unit_price": {
            "description": "Price for one unit if the email states it, else null.",
            "type": [
              "number",
              "null"
            ]
          },
          "quote": {
            "type": "string",
            "description": "The exact words from the email that support the value. Empty when the value is null."
          }
        },
        "required": [
          "description",
          "sku",
          "quantity",
          "unit",
          "unit_price",
          "quote"
        ],
        "additionalProperties": false
      }
    },
    "special_instructions": {
      "description": "Delivery or handling notes for a person at the supplier, in the email's words.",
      "type": [
        "string",
        "null"
      ]
    },
    "conflicts": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "field": {
            "type": "string",
            "description": "Path of the field, for example line_items.0.quantity."
          },
          "values": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "quotes": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "required": [
          "field",
          "values",
          "quotes"
        ],
        "additionalProperties": false
      },
      "description": "Details the email states two different ways. Report both; do not choose."
    }
  },
  "required": [
    "intent",
    "language",
    "customer_name",
    "po_number",
    "stated_total",
    "requested_delivery_date",
    "ship_to",
    "currency",
    "line_items",
    "special_instructions",
    "conflicts"
  ],
  "additionalProperties": false
}

Retry and repair

As of ai@7.0.181, the version installed here, Output.object has no repair hook: when the answer cannot be parsed or does not match the schema, generateText throws NoObjectGeneratedError, which carries the raw text, the cause, the usage and the finishReason. What to do next is the app's job. Here it is one small module, lib/extract/retry.ts, that reads why the attempt ended before it decides anything:

The diagram scrolls sideways.

The order of the checks after an attempt ends. The finish reason is read first. If the call itself failed: one retry, then a person. If the answer was cut off (length): it is not parsed and not repaired; one retry with the budget raised from 800 to 1,600 tokens, then a person. If the model refused (content-filter): no retry, a person. Only a finished answer (stop) is parsed. Not valid JSON: the syntax is repaired locally with no new call, or the model is asked again once if it cannot be. Enum capitals are compared without regard to case. If the result does not match the schema: the model is asked again once with the validation issues, and if it is still wrong a person takes it. If it matches: accepted, code raises the flags and a person reviews. At most 3 model calls for one email.

The same rules as a table:

How the attempt endedWhat the code does
Cut off (finish reason length)Does not parse it and does not repair it. Retries once with the output budget raised from 800 to 1,600 tokens. Cut off again: stops, stores no result, sends to a person.
Refused (finish reason content-filter)No retry. Stores the attempt and sends to a person.
The call itself failedOne retry, then stops and sends to a person.
Finished, but not valid JSONRepairs the syntax locally (code fence, prose around the object, trailing comma), records that it was repaired, then validates as usual. No new model call.
Valid JSON, enum capitals differCompares enum values without regard to case and stores the schema's spelling. No new call.
Valid JSON, wrong shapeAsks again once with the validation issues listed. Both raw outputs are kept. Still wrong: stops and sends to a person.

The first row is the one that matters most. A JSON fixer will happily close the brackets of a cut-off answer, and the result is a valid-looking order with the last lines missing. So the finish reason is read first, and a cut-off answer never reaches the fixer. At most 3 model calls are made for one email. An email the pipeline cannot process at all is stored as a stopped run for a person; it does not take the rest of its batch down.

Flags, and what clears each

A valid shape says nothing about whether the values are right. After validation, plain code checks each result and raises flags, each with its reason in words. There are no confidence percentages: nothing in a sample has calibrated one, and a model's opinion of its own answer is not evidence.

The two states mean different things on the review screen, and the database holds them apart too.

StateRaised byWhat clears it
BlockedQuoted evidence that is not in the email. A value that is not in its own quote. A value read from text addressed to the model. An order line with no quantity, or one of zero or less. An email that is not an order.An edit: correct the value or clear it. Or reject the item. Enter opens the editor; there is no Confirm, and the trigger on field_flags refuses a confirm as well.
Blocked, the email itselfThe email contains text addressed to the model. It is marked in the source and treated as data.A person opens the note and marks it as read. One key does not do it.
Flagged, needs a choiceA numeric date that reads two ways (01/02/2027, 01/02/27, 01/02). One detail stated two ways in the same email. The model's own pick is discarded in both cases.The reviewer picks one of the two readings in the editor, or types the right value.
FlaggedLines that do not add up to the stated total. A date before the email arrived or more than a year out. A written date the code cannot read. No delivery date, address or customer name. The same PO number on an earlier, different email. The same text from the same sender again, too late to be a re-send.One key: the reviewer looked and confirms it as it stands. Or an edit.

The check for text addressed to the model is a few patterns and catches the obvious; it is not the defence. The defence is that the email goes in as data under a tag it cannot close, that no field can approve or send, that a value read from such text is blocked, and that a person approves.

Every item needs a person. An edit is checked like the model's answer was: a date has to exist, a quantity has to be above zero, and if the lines stop adding up or the date lands in the past, a new flag opens and Approve locks again. What goes out must be an order with a quantity on every line; the database refuses to approve anything else.

On the review screen each value is tied to the words it was read from, and the underline's shape says which state the value is in:

Marks in the email:traced to these wordsflaggedblockeditem already decided

Prompts and versions

The prompt text stays on the server. It lives in one module marked server-only, so the build fails if a browser component imports it, and a script run after every build reads the files sent to the browser and fails if a sentence of the prompt is in them. The browser only ever gets a version id and a label.

The email is wrapped in a tag whose name carries a random token made for that one request, and the system prompt names the tag. An email that contains a closing tag of its own cannot end the data block, and the flag check marks such markup as text addressed to the model.

A run is stored under its input, prompt version and schema version, so processing an email again under a new prompt adds a run beside the old one; nothing is overwritten, and processing it again under the same versions changes nothing. There are two prompt versions here (p1 and p2); try "Re-process" in the attempts drawer of the date case to see a second run appear.

The tables and their rules

TableWhat it holds
inputsThe raw email and the fields the code copies. One first input per sender and text; never changed.
attemptsOne row per model call: raw output, finish reason, parse result, issues, what the code did next. Append-only.
extractionsOne row per run (input, prompt version, schema version): the outcome and, when there is one, the result. Append-only.
field_flagsEach flag with its reason, and the confirm or edit that resolved it.
reviewsOne per run. Starts open; approved or rejected is final.
field_editsEvery confirm and every edit, per field, with the value before and after.
outboxWhat goes out. Each row needs an approved review; the foreign key enforces it. Append-only.
audit_eventsAppend-only trail of everything that happened to an input.

These rules are constraints and triggers in the database, so they hold whatever the application code does, and for the table owner as well as the application role:

Nothing goes out without an approved review. The outbox row points at the review and at its status, and the status it points at can only be approved:

CREATE TABLE outbox (
  id            integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  review_id     integer NOT NULL,
  review_status text NOT NULL DEFAULT 'approved' CHECK (review_status = 'approved'),
  kind          text NOT NULL DEFAULT 'order_confirmation',
  payload       jsonb NOT NULL,
  created_at    timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT outbox_one_per_review UNIQUE (review_id),
  CONSTRAINT outbox_review_must_be_approved
    FOREIGN KEY (review_id, review_status) REFERENCES reviews (id, status)
);

A review cannot be approved with an open flag, or when there is nothing to send. A trigger on reviews refuses an approval while any flag is open, when the result is not an order, when it has no lines, and when a line has no quantity above zero. A decision is final, and a review cannot be inserted as already approved.

A flag is resolved once, on its own review and field. A trigger on field_flags lets only resolved_by change, only once, and only to a confirm or an edit made on the same review and the same field. A blocked flag needs an edit:

CREATE FUNCTION field_flags_guard() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE
  edit_path text;
  edit_action text;
BEGIN
  IF TG_OP = 'DELETE' THEN
    RAISE EXCEPTION 'flags are never deleted' USING ERRCODE = 'restrict_violation';
  END IF;
  IF (NEW.id, NEW.extraction_id, NEW.field_path, NEW.kind, NEW.severity, NEW.reason, NEW.detail)
     IS DISTINCT FROM (OLD.id, OLD.extraction_id, OLD.field_path, OLD.kind, OLD.severity, OLD.reason, OLD.detail) THEN
    RAISE EXCEPTION 'a flag cannot be rewritten; it can only be resolved' USING ERRCODE = 'restrict_violation';
  END IF;
  IF OLD.resolved_by IS NOT NULL THEN
    RAISE EXCEPTION 'flag % is already resolved', OLD.id USING ERRCODE = 'restrict_violation';
  END IF;
  IF NEW.resolved_by IS NULL THEN
    RETURN NEW;
  END IF;

  SELECT e.field_path, e.action INTO edit_path, edit_action
    FROM field_edits e JOIN reviews r ON r.id = e.review_id
   WHERE e.id = NEW.resolved_by AND r.extraction_id = OLD.extraction_id;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'flag % can only be resolved by a confirm or an edit on its own review', OLD.id
      USING ERRCODE = 'check_violation';
  END IF;
  -- The totals flag sits on the total and is also cleared by fixing the line that was wrong.
  IF edit_path <> OLD.field_path AND NOT (OLD.kind = 'totals_mismatch' AND edit_action = 'edited') THEN
    RAISE EXCEPTION 'flag % is on %; a change to % does not resolve it', OLD.id, OLD.field_path, edit_path
      USING ERRCODE = 'check_violation';
  END IF;
  IF OLD.severity = 'blocked' AND OLD.kind <> 'instruction_like_text' AND edit_action <> 'edited' THEN
    RAISE EXCEPTION 'flag % is blocked: the value has to be corrected or cleared, not confirmed', OLD.id
      USING ERRCODE = 'check_violation';
  END IF;
  RETURN NEW;
END;
$$;

Emails, attempts, runs, the outbox and the audit trail are never rewritten. One trigger function refuses update and delete on the append-only tables for everyone; on inputs only the received counter may move. The application role has no such privilege in the first place:

CREATE FUNCTION append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  RAISE EXCEPTION '% is append-only: % is not allowed', TG_TABLE_NAME, TG_OP
    USING ERRCODE = 'restrict_violation';
END;
$$;

CREATE ROLE review_app NOLOGIN;
GRANT SELECT, INSERT ON inputs, attempts, extractions, field_flags, field_edits, outbox, audit_events TO review_app;
GRANT SELECT, INSERT, UPDATE ON meta, reviews TO review_app;
GRANT UPDATE (times_received, last_message_id, last_received_at) ON inputs TO review_app;
GRANT UPDATE (resolved_by) ON field_flags TO review_app;

A re-sent email is recognised, and a repeat order is not thrown away. The content hash is a SHA-256 of the body with line endings and trailing spaces normalised, unique per sender. The same text from the same sender within 72 hours, while the first copy is still waiting for a decision, bumps a counter in one atomic INSERT ... ON CONFLICT ... DO UPDATE and starts no run. The same text later, after a decision, or from another sender is a new input with its own review; from the same sender it carries a "possible duplicate" flag, so a person decides.

What the database does not check: that the result stored with an approval is the one the reviewer saw (the application writes it in the same transaction), or who the reviewer was (there is no sign-in here). The page Outbox and audit has four buttons that try to break these rules with real statements and show the error PostgreSQL returns.

Where the data lives

Each visitor gets a private database. It is PGlite running in your browser tab, saved to IndexedDB, so it survives a reload, nobody else sees your changes, and "Reset demo" deletes it and builds a new one from the sample emails. I chose this because a public sample on a shared hosted database is either read-only or gets filled with other visitors' edits, and a per-visitor database on the server does not survive on serverless hosting without an external store.

What that changes compared with a production build:

  • The first visit downloads PostgreSQL, about 5.5 MB, before the queue can open: a few seconds on a fast line, around half a minute on a slow one. A production build has no such download.
  • The extraction runs on the server, as it would. The database writes run in the browser, which they would not: in a real build they move behind server actions, against a hosted PostgreSQL, using the same SQL file and the same repository functions.
  • In PGlite the session is the database owner, so the role privileges are declared but it is the triggers that do the refusing. On a server the application connects as the restricted role and both apply. The integration tests run the whole review as that role and check each refusal.
  • If the sample is open in two tabs, the second tab gets a temporary in-memory database and says so, rather than two tabs writing to one store.

Keyboard

The review screen is built for someone clearing a queue. Tab and Shift+Tab move between fields. Enter confirms a flagged field and moves on; on a blocked field, or one that needs a choice, it opens the editor instead. N jumps to the next flag, E edits, A approves and R rejects. Focusing a field scrolls its evidence into view in the email. The four letter keys can be switched off from the bar that lists them.

Tests

The tests are in the source. They cover:

  • Unit: the retry and repair rules for each way an attempt can end, the schema, each flag rule, evidence matching, date reading, and what a reviewer may and may not save.
  • Integration, against PGlite: one input per sender and text, the outbox constraint, the review and flag triggers, the append-only tables, the whole review run as the restricted role, and that re-processing adds a run.
  • The fourteen messy cases: the checks the cases page runs are the same functions the test suite runs.
  • End to end in a browser: reviewing with the keyboard, Approve disabled while a flag is open, a blocked field that cannot be confirmed, an email that is not an order kept out of the outbox, rejecting with a reason, the refused statements, a phone-width check and an accessibility scan of every page.
  • After every build: a script that reads the browser files and fails if the prompt text is in them.

What a production version would add

  • Real inputs and their schema in place of the sample set, and the messy cases they actually contain.
  • A real provider behind the same pipeline, with its key in the server environment only.
  • Sign-in and a rate limit in front of the extraction route before that key goes in. The route here is open because nothing behind it costs money.
  • An evaluation set built from real inputs, so there is a number for wrong values that passed without a flag, not only for the ones that were caught.
  • A hosted PostgreSQL, with these tables as migrations, and the writes moved to the server.
  • Sign-in for reviewers, so the audit trail names who confirmed, edited, approved or rejected.
  • A worker that sends from the outbox once, and a way to key in an order by hand when the model refuses.
  • Splitting very long item lists into batches, which this sample does not do; it raises the budget once and then stops.