Skip to content
Vishesh Gubrani
Selected work

AI Triage

An AI triage inbox: an LLM sorts incoming email and documents into schema-checked fields, and anything uncertain waits for a person.

An open-source (MIT) triage inbox for teams that process invoices, support requests and contracts by hand. I'm the sole developer. It runs locally with Docker, and there is no hosted version.

Ingest, classification, extraction, review, signed webhook delivery and evals all run end to end, from recorded model responses so no API key is needed. Google sign-in has landed and connecting a Gmail mailbox is in progress. The test split is 13 items, so its numbers carry wide bounds.

  1. Evals run the production code but hold no queue, action or delivery port, so a run can measure the pipeline and never act on its output.
  2. Nothing is auto-approved by default. A category has to opt in, thresholds are frozen from a calibration run into an immutable config before they can score the test split, and a sample of auto-approvals still goes to a person.
Status
Open source
My role
Sole developer.
Built with
  • TypeScript
  • Hono
  • Next.js
  • PostgreSQL
  • pg-boss
  • Drizzle
  • LLM APIs
The AI Triage evals page: headline test-split results for a frozen config, with category accuracy, auto-approval precision, auto-approved share and recorded cost, each with its count and lower bound, above a list of dev, calib and test runs.
Evals: the frozen config's test-split numbers up top, every run below, each rate with its n and lower bound.

What it is

ai-triage is an inbox for documents a business has to act on: invoices, support requests, contracts. Mail arrives through Postmark inbound, files through uploads or a REST API. An LLM classifies each one and extracts fields checked against a JSON Schema, anything uncertain waits in a human queue, and approved items go out as signed webhooks to the tenant's own systems. An evals page runs the same pipeline over labeled data.

It's MIT-licensed and multi-tenant, for a team that wants a model doing the reading without letting it act unchecked. It runs locally under Docker in replay mode, from recorded model responses, with no API key. There's no hosted version.

The path a document takes

Ingestion is one transaction. The document row, its first processing run and the doc.parse job commit together through pg-boss on the same client, and a duplicate Message-ID or content hash returns 200 and does nothing.

The worker runs four stages. Parse turns email into text with offsets and a PDF into per-page text, and marks scans as unverifiable. Classify returns a category, a self_confidence and a rationale. Extract returns each field with a verbatim evidence quote, plus the fields the model wasn't sure of. Route is pure code.

Each stage calls the model with no transaction open, then commits its result, the status change and the next job together. The response is saved the moment it arrives and reused on retry. That narrows repeat calls without ruling them out: a worker that dies between the answer and the save pays again.

An approval writes a row to an actions outbox with its payload frozen, and a delivery job POSTs it with the action id as Idempotency-Key. Delivery is at least once, so receivers dedupe on that key.

Confidence is not trusted on its own

The score is the classifier's self_confidence and nothing else. Extraction quality isn't multiplied into it. It's checked by gates instead, and any failed gate sends the document to review with the reason recorded.

The gates in gates.ts fail when the output doesn't validate against the full schema, a required field is empty or the model listed it as uncertain, or a quote can't be found in the source text (or on the cited PDF page). They also fail when a category rule breaks, such as invoice line items not summing to the total, when the category is other, when the text matches a short list of patterns that address the triage system, or, where a config requires it, when the sender isn't authenticated. Scans can't be checked against a quote, so they always go to review.

Passing every gate isn't enough. Auto-approval also needs the score at or above the category's threshold and the category set to auto_when_confident. The default is review_all, so automation is opt-in per category, and a run started by a reclassify always goes to a person. Even then, a deterministic draw holds a share of auto-approvals for audit, 10% by default, which gives an unbiased estimate of how often auto-approval is wrong.

Evidence matching proves a quote exists, not that it supports the value, and the injection patterns are regression tests, not proof of resistance.

The review screen

Claim next takes the oldest free task with FOR UPDATE SKIP LOCKED and returns a claim token with a ten-minute lease. The page renews it every minute while the tab is visible, so a hidden tab's claim lapses. An expired lease counts as no claim in every query, so nothing has to reap it.

An approval binds to the exact extraction revision on screen and the claim token. Under lock, the task has to be claimed by this user with a live lease and a matching token, and the revision has to be the document's current one. Anything else returns 409 and nothing is written, so a stale tab can't approve. An edit becomes a new revision that has to validate before it's approved. Reclassify re-extracts with the reviewer's category and brings the task back to a human.

A review task for Invoice NCS-3494 showing score 0.88, a claim expiry, reasons uncertain:total and below_threshold, the email text with highlighted quotes on the left, Approve, Reclassify, Reject and Skip buttons with key hints, and the extraction form on the right.
The reasons line says why this invoice didn't auto-approve, and each highlighted line in the source is a quote the model gave as evidence for a field.

Email HTML is sanitized by the API and shown in a sandboxed iframe with a CSP that blocks remote loads. Every decision writes an insert-only row, which the task page shows as history.

Evals that cannot act

An eval run uses production's parsing, request builders, gates and routing, but gets no way to act. A type test in wiring.test.ts pins EvalDeps to the pool, storage, the model gateway, limits, the LLM mode and a clock. The same test scans the evals sources and fails on createAction, any enqueue call or a delivery import. Behind both, an action needs a documents row and eval items never create one, so the database would refuse it anyway.

Datasets have three splits. You iterate on dev, run the candidate on calib, and read a per-category threshold sweep and a reliability table that asks whether a 0.95 score is right 95% of the time. Freeze writes a new, immutable config version with the chosen thresholds. Only frozen versions run on test or can be activated. The API refuses a test run on an unfrozen config, and a trigger in 0008_eval_guards.sql refuses the insert if the API is ever wrong.

The Freeze form for a calib run with threshold, automation and audit rate per category, above sweep charts of auto-approved rate, precision and precision lower bound against threshold for invoice and support_request, each with a table.
At 0.9, support_request auto-approves 3 of 5 items but only 1 of those 3 is right, and the lower bound of 6% is what the Freeze decision has to read.

Every rate is shown as k/n with a 95% Wilson lower bound. A correct auto-approval means the right category and every required field correct under its comparator: exact, normalized text, parsed date, amount within a cent, set F1 for lists, presence for free text. Category accuracy alone never counts.

Replay cassettes are keyed by a hash of the exact wire request, and eval requests are byte-identical to production's. A missing cassette is a hard error, never a quiet fallback to a paid call.

Tenants and untrusted input

Every tenant table has row-level security, and the api and worker refuse to start as a role that can bypass it. Child tables reference parents by (tenant_id, id), so a cross-tenant reference fails at the database even if the code has a bug.

A tenant admin chooses the webhook URL, which on a shared instance is an SSRF risk. The URL must be https, carry no credentials and use port 443, 8443 or above 1023, and the API resolves it when it's saved and rejects private, loopback and metadata addresses. A hostname can resolve differently later, so the worker's fetch goes through a guarded DNS lookup that checks every address again at each connection.

The signature covers the timestamp, the idempotency key and the body. Secrets are encrypted at rest with AES-256-GCM, with the tenant id as associated data. After a rotation the header carries one signature per secret for 24 hours, so receivers can switch over without dropping deliveries.

Live calls reserve budget first. One conditional update adds the worst-case cost only if spent plus reserved still fits the tenant's daily cap, then settles to the actual cost, so concurrent workers can't overshoot it.

What it costs to run

Replay costs nothing. Recording the demo's cassettes took 110 live calls to GPT-6.1 Terra at low effort across the 60 fixtures, for $0.1813. Recording DeepSeek Flash at high effort for the eval comparison took another 110 calls for $0.0758. The seeded DeepSeek price is its peak rate, so that figure is an upper bound.

Live mode draws on that per-tenant daily budget, $5 unless an admin changes it. Replayed figures are labeled as recorded.

What works and what does not

The MVP is complete, from ingestion through signed delivery and evals.

The demo replays GPT-6.1 Terra. Configs can use Claude, OpenAI, DeepSeek, OpenRouter or a local server, but only Terra and DeepSeek Flash have recorded cassettes. Changing a config's model or prompt in replay fails as cassette_missing until someone records it.

The eval numbers rest on small samples. The fixtures split into 32 dev, 15 calib and 13 test items, two to five per category on calib, and they're synthetic and easier than real mail. The Wilson bounds are wide because they should be.

Sign in with Google has landed. Gmail mailbox connection is in progress and the sync worker comes after it, so for now mail arrives through Postmark. There's no hosted demo.

What is next

The rest of the Google Workspace phase: mailbox connections, a read-only Gmail sync worker, Workspace domain auto-join, sender authentication on synced mail, and a fake Google for the demo. After that comes reliability: real mail volume and variety, per-tenant fairness, observability and backpressure.

Need help solving a problem like this? See ai workflow integration, view all consulting services, or email me ().