Skip to content
Tinbox

tutorials

LLM email classification with interpreters: rules + LLMs you can trust

September 21, 2026

#llm#email-classification#interpreters#ai-inbox#evals
Paper-cut highlights reveal intent, identity, and dates within one message.

An inbox that just files mail is dumb. Interpreters make it react, and eval suites make the reactions trustworthy. This is how to do LLM email classification without handing every message to a model and hoping.

If you have shopped for "LLM email classification" you have probably seen the same pattern everywhere: take the subject and body, stuff them into a prompt, ask the model for a label, store the label. It works in a demo. It falls apart in production because you have no idea when it is wrong, the cost scales with your inbound volume, and a prompt tweak that fixes one case quietly breaks five others.

The fix is not a better prompt. It is a better architecture: split the work between cheap deterministic rules and LLM rules, run them at ingest, store the result as structured data, and back every LLM rule with its own eval suite. That is what an interpreter is, and the rest of this article builds them from the ground up. For a quick survey of the categories worth classifying and a grab bag of ready-made rules, see the ways an LLM can classify your incoming email and seven email interpreter recipes for smarter inbound handling.

What is an email interpreter?

An email interpreter is a rule that classifies or reacts to an inbound message and writes structured conclusions onto it. Each interpreter reads a message and returns a verdict: custom extra keys, flags, a category, an optional UI component, and optionally a proposed reply draft. The verdict is stored on the message and becomes structured signal that everything downstream can read.

The important word is structured. A label like "complaint" in a free-text field is almost useless. A verdict like { complaint: true, severity: "high" } plus an important flag and a queued draft is a thing your triage view, your chat agent, and your MCP server can all act on without re-reading the email.

Interpreters are a built feature in Tinbox: an engine that runs them, an ingest consumer that triggers them, a router that lists them, a UI verdict-component registry, and a playground to test them. Everything below uses the real API.

What is the difference between algorithmic and LLM interpreters?

The difference is whether the decision needs judgment. Algorithmic interpreters are pure functions over the message: regex and heuristics. LLM interpreters send the message to a model with instructions and a schema. You pick based on the case:

Use algorithmic whenUse an LLM when
The signal is explicit (a 6-digit code, the word "invoice", a text/calendar part)The decision depends on tone or intent (is this customer angry?)
You need determinism and zero costA heuristic would be a pile of brittle keywords
OTP, receipt, password reset, shipping, calendar invite, unsubscribeComplaint, churn risk, urgency, escalation, intent routing

Algorithmic rules are instant, free, and deterministic. LLM rules cost a model call and a little latency, and crucially they need an eval suite before you trust them. The mistake the naive approach makes is using an LLM for the deterministic cases too, paying tokens to detect a thing a regex nails every time.

In a real config the algorithmic interpreters always run before the LLM ones, so an LLM rule can read what they already extracted. An LLM "urgency" rule can see that the algorithmic OTP rule already fired and skip it.

Why classify email at ingest instead of at read time?

Classify at ingest so the verdict is computed once and stored, not re-derived every time someone (or some agent) looks at the message. Running interpreters on inbound mail means the inbox renders precomputed badges, triage sorts on precomputed flags, and the chat agent and MCP server read a precomputed signal instead of calling a model again on every query.

The flow is one direction:

inbound mail
   │
   ▼
interpreters  ──► algorithmic rules (pure, instant)
   │                LLM rules (one model call, cached)
   ▼
verdict written to message.extra (+ flags, category, draft)
   │
   ├──► inbox UI (badges, components)
   ├──► triage / filters
   ├──► chat agent
   └──► MCP server

This runs on the async projection lane, never on the ingest hot path, so a slow model call cannot delay accepting the message. And because the engine caches LLM results by content hash, re-running the projection is free.

How do you write an algorithmic interpreter?

Define a rule with kind: "algorithmic" and a pure match(ctx) function that returns a verdict or null. Here is a stripped-down OTP detector, the kind that should never be an LLM call:

import type { AlgorithmicInterpreter } from "@tinbox/engine/interpreters";

const CODE_CONTEXT =
  /\b(one[\s-]?time (?:code|password|pin)|verification code|security code|login code|2fa|otp|passcode)\b/i;
const CODE_LABELLED =
  /\b(?:code|otp|passcode|pin)\b[^\d]{0,12}(\d{3}[\s-]?\d{3}|\d{4,8})/i;

export const otp: AlgorithmicInterpreter = {
  id: "otp",
  label: "One-time codes",
  kind: "algorithmic",
  appliesTo: "message",
  match(ctx) {
    const { subject, body } = ctx.message;
    const hay = `${subject}\n${body}`;
    if (!CODE_CONTEXT.test(hay) && !CODE_LABELLED.test(hay)) return null;

    const code = hay.match(CODE_LABELLED)?.[1]?.replace(/[\s-]/g, "");
    if (!code) return null;

    return {
      extra: { otp: true, otp_value: code },
      flags: ["realtime_important"],
      category: "updates",
      component: "otp-quick-copy",
    };
  },
};

Notice what the verdict carries: the extracted code in extra.otp_value, a realtime_important flag (you want that code now), a category, and a named UI component so the inbox can render a quick-copy button. No model, no tokens, no latency. The whole thing is testable as a pure function, which matters for the eval suite below.

How do you write an LLM interpreter?

Define a rule with kind: "llm", an instructions string, an output Zod schema, and a pure toVerdict(out) function. The engine runs your tenant-local model with the instructions and schema, validates the output, caches it, and hands the parsed result to toVerdict. You never write the model call yourself. Here is complaint triage:

import { z } from "zod";
import type { LlmInterpreter } from "@tinbox/engine/interpreters";

const output = z.object({
  is_complaint: z.boolean(),
  severity: z.enum(["low", "high"]).optional(),
  issue: z.string().optional(),
});

export const complaint: LlmInterpreter<z.infer<typeof output>> = {
  id: "complaint-triage",
  label: "Complaint triage",
  kind: "llm",
  appliesTo: "thread",
  instructions:
    "Decide whether the customer is expressing a complaint, frustration, or a " +
    "threat to leave. If so, rate severity (high if angry, threatening to churn, " +
    "or escalating; else low) and summarize the specific issue in one short line. " +
    'Respond as JSON { "is_complaint": boolean, "severity"?: "low"|"high", "issue"?: string }.',
  output,
  toVerdict(out) {
    if (!out.is_complaint) return null;
    const high = out.severity === "high";
    return {
      extra: { complaint: true, severity: out.severity ?? "low" },
      flags: high ? ["important", "realtime_important"] : ["important"],
      category: "primary",
      draft: {
        instructions:
          `Write a brief, warm apology acknowledging the specific issue` +
          (out.issue ? ` ("${out.issue}")` : "") +
          `. Take responsibility, state the next step, avoid promising timelines. Under ~120 words.`,
      },
    };
  },
};

Two things to call out. First, the model is yours: the engine uses the tenant-local key (a Worker secret), so the email never leaves your deployment. The interpreter is model-agnostic; you are not hard-wired to one provider. Second, the verdict proposes a draft but never sends it. A complaint draft is queued for a human to review and send. Interpreters can only do reversible things by design.

Why does every LLM interpreter need an eval suite?

Because an LLM classifier with no eval suite is a guess you cannot audit. If you need to be talked into the discipline, the reasons your email AI needs eval tests make the case in full. The eval suite is a table of labeled fixture emails, each with the verdict it should produce, including negative cases that must NOT fire. It is the ground truth for "does this rule catch real complaints and not misfire on a happy customer," and it is the regression guard when you touch the prompt.

You attach cases to an interpreter as an InterpreterWithEvals. For an LLM rule each case carries a stubOutput: the JSON the model would return. The eval feeds that through a stub model, so the run is deterministic and costs zero tokens in CI.

import { runEvals, type InterpreterWithEvals } from "@tinbox/engine/interpreters";

export const complaintEvals: InterpreterWithEvals = {
  interpreter: complaint,
  cases: [
    {
      name: "angry churn threat → high + draft",
      email: {
        from: "angry@customer.com",
        to: ["support@acme.com"],
        subject: "This is unacceptable",
        body: "Third time my order is late. If this isn't fixed today I'm cancelling.",
      },
      stubOutput: { is_complaint: true, severity: "high", issue: "repeatedly late orders" },
      expect: {
        matched: true,
        extra: { complaint: true, severity: "high" },
        flags: ["important", "realtime_important"],
        draft: true,
      },
    },
    // The negative case is the one that saves you.
    {
      name: "happy customer → no fire",
      email: {
        from: "fan@customer.com",
        to: ["support@acme.com"],
        subject: "Love it!",
        body: "Just wanted to say the new feature is fantastic. Keep it up!",
      },
      stubOutput: { is_complaint: false },
      expect: { matched: false },
    },
  ],
};

const report = await runEvals(complaintEvals);
console.log(`${report.passed}/${report.total} passed`);
2/2 passed

For algorithmic interpreters there is no stubOutput; the pure match runs for real against each fixture. Either way you get an EvalReport with per-case pass/fail and the exact reason for a failure, and the same scorer backs the playground's "Run evals" button so the CLI and the UI never diverge.

Failure then fix: an eval catches a regression

Say you tighten the complaint prompt to also flag neutral billing questions as complaints, thinking it will catch more. Run the suite first:

1/2 passed
✗ neutral question → no fire
    matched: expected false, got true
    draft: expected false, got true

The eval caught a false positive before it shipped: a plain "do you offer annual plans?" is now being flagged important and drafting an apology. You walk the instructions back so the model only fires on actual frustration, re-run, and get 2/2. That loop, prompt change then re-run the labeled suite, is the entire reason interpreters are trustworthy where a bare prompt is not. You never ship an LLM rule whose evals you have not run.

Where do classification verdicts go?

Verdicts live on the message, in its extra JSON field. There are no dedicated AI or label columns in the schema. The OTP verdict writes extra.otp and extra.otp_value; the complaint verdict writes extra.complaint and extra.severity, plus flags, a category, and a queued draft. This is deliberate: keeping verdicts in extra means a new interpreter never needs a migration, and the data the inbox already renders as badges is the same data your agent and MCP read.

That single storage decision is what makes the downstream consumers cheap. The chat agent that acts on these verdicts reads extra and flags rather than re-classifying the thread. The interpreter verdicts feed MCP triage for any AI assistant you connect, again with no extra model calls. And because everything is structured columns and JSON, you can search across classified mail by category or flag. Interpreters produce the signal; the agent and MCP consume it.

Failure modes to design against

The eval suite removes most of the danger, but three failure modes are worth naming so you build against them:

  • Over-trusting the LLM. A model that returns confident JSON is still wrong sometimes. Keep LLM verdicts to reversible actions (flags, drafts), never auto-sends, and keep severity-scaled flags so a low-confidence call does not page a human.
  • A prompt that passes evals but fails in production. Your eval set is only as good as its coverage. When a real email misclassifies, add it as a new case before you fix the prompt, so the fix is permanent and the next regression is caught.
  • Regex false positives. The dangerous algorithmic failure is a normal email that looks like an OTP (an order number, a year, an invoice amount). That is exactly why the OTP suite carries negative cases asserting matched: false. Write the negatives first.

The through-line: interpreters are code, so you validate them like code. Algorithmic rules with unit-style cases, LLM rules with stubbed eval cases, both behind a pass/fail report you run on every change.

Putting it together

Register your interpreters in app/interpreters.config.ts and they run at ingest:

import { defineInterpreters, builtinInterpreters } from "@tinbox/engine/interpreters";

export const interpretersConfig = defineInterpreters([
  ...builtinInterpreters, // OTP, password reset, receipt, complaint, calendar, …
  // your own algorithmic and LLM rules here
]);

defineInterpreters validates the whole config at module init, so a malformed rule throws at build time and the deploy fails rather than misbehaving at runtime. From there, every inbound message gets classified once, the verdict lands in extra, and your inbox, triage, agent, and MCP server all read the same precomputed signal. Interpreters are part of the full stack covered in interpreters in the context of the whole email stack.

LLM email classification done well is not a single prompt. It is cheap rules where the signal is explicit, LLM rules where it is not, classification at ingest, verdicts as structured data you own, and an eval suite per LLM rule so you can change a prompt without flying blind.

Deploy this yourself: npx tinbox init <domain>. The interpreter engine, the built-in rules, their eval suites, and the playground come with the box; the full interpreter guide ships in the repo docs.

Frequently asked questions

Should I classify email with rules or an LLM?

Both, split by the kind of decision. Use deterministic algorithmic rules (regex/heuristics) for cases with a clear signal: OTP codes, receipts, password resets, calendar invites. Use an LLM for judgment cases where wording matters: complaint, churn risk, urgency, escalation. Algorithmic rules are instant, free, and deterministic; LLM rules cost a model call and need an eval suite to stay trustworthy.

How do you trust an LLM email classifier?

Give it an eval suite: a table of labeled fixture emails, each with the verdict it should produce, including negative cases that must NOT fire. Run the suite whenever you change the prompt or model. In Tinbox, every interpreter ships a per-interpreter eval suite, and LLM cases feed a stubbed model output so the eval is deterministic and costs no tokens in CI.

Where are classification verdicts stored?

On the message, in its `extra` JSON field. There are no dedicated AI or label columns in the schema. A verdict writes structured keys (for example `{ otp: true, otp_value: "123456" }`), flags, a category, and optionally a proposed draft. Downstream consumers (inbox UI, triage, the chat agent, MCP) read `extra` instead of re-classifying.

When does classification run?

At ingest, on the async projection lane, not on the read path and not on the ingest hot path. The verdict is precomputed once and stored, so reading a message or asking the agent about it does not trigger a fresh model call.

Can an email interpreter send email or take destructive actions?

No. An interpreter can only do reversible things: write `extra`, set flags or a category, name a UI component, and propose a draft reply. It can never send. Widening that is a git change you review. An admin can turn an interpreter off live but can never turn on one the config does not declare.