AI summary

I tested TypeSafe's Jev against GPT-6 Luna on 500 bank support messages with 77 intent labels. Accuracy was close, and Jev answered several times faster.

Jev is a model from TypeSafe that picks an answer from a list you give it, instead of writing text. TypeSafe calls it “a new class of frontier models”.

I wanted to know what that means for an ordinary job, so I called it through OpenRouter on 500 customer support messages from Banking77.

Banking77 is a public dataset of bank customer messages, sorted into 77 intents. An intent is what a message is asking for, picked from a fixed list: card_arrival for “Where is my new card?”, for example. Every message in the dataset comes with its correct intent attached, so I’ll call these labeled messages.

On the same messages I also ran GPT-6 Luna, a small OpenAI model, plus a Keras classifier and two older zero-shot methods. All the API calls together, repeat runs included, cost me under three dollars.

Jev isn’t a frontier model here. It’s about as accurate as a small, cheap LLM, a model that answers by writing text, like the ones behind ChatGPT. The idea behind Jev is years old. Its real advantage is speed.

Test labThe scripts behind this article's test, its runs step by step, and the raw results
Test labReplaying a recording. No API is called.
"""Paired comparison of the result files in a results folder, all on the same 500 messages.

usage: python -I compare.py RESULTS_DIR

For each pair: accuracy of both, a 95% bootstrap range for the accuracy gap, and an exact
McNemar test on the messages where only one of the two was right.
"""

import json
import random
import statistics
import sys
from math import comb
from pathlib import Path

res = Path(sys.argv[1])


def load(name):
    lines = (res / f"{name}_500.jsonl").read_text(encoding="utf8").splitlines()
    return {r["test_row"]: r for r in map(json.loads, lines)}


def right(run, i):
    return run[i]["pred"] == run[i]["gold"]


def acc(run):
    return sum(right(run, i) for i in run) / len(run)


def mcnemar(b, c):
    # Two-sided exact test: under "no difference", each disagreement is a coin flip.
    n, k = b + c, min(b, c)
    return min(1.0, 2 * sum(comb(n, j) for j in range(k + 1)) / 2**n) if n else 1.0


def pair(a_name, b_name):
    a, b = load(a_name), load(b_name)
    ids = sorted(set(a) & set(b))
    diffs = [right(a, i) - right(b, i) for i in ids]
    rng = random.Random(0)
    boot = sorted(sum(rng.choices(diffs, k=len(diffs))) / len(diffs) for _ in range(5000))
    only_a = sum(d == 1 for d in diffs)
    only_b = sum(d == -1 for d in diffs)
    print(
        f"{a_name} vs {b_name}: n={len(ids)} "
        f"{sum(right(a, i) for i in ids) / len(ids):.3f} vs {sum(right(b, i) for i in ids) / len(ids):.3f} "
        f"gap CI95 [{boot[125]:+.3f},{boot[4875]:+.3f}] "
        f"only_first={only_a} only_second={only_b} mcnemar_p={mcnemar(only_a, only_b):.2f}"
    )


def summary(name):
    run = load(name)
    lat = statistics.median(r["latency_ms"] for r in run.values())
    cost = statistics.mean(float(r["cost_usd"] or 0) for r in run.values())
    print(f"{name}: n={len(run)} acc={acc(run):.3f} p50_ms={lat:.0f} cost_per_call={cost:.6f}")


jev, luna = "jev-1.13", "gpt-6-luna"
seeds = ["examples5", "examples5-seed1", "examples5-seed2"]
for name in [f"{jev}_names", f"{luna}_names"] + [f"{m}_{s}" for m in (jev, luna) for s in seeds]:
    summary(name)
print()
pair(f"{jev}_names", f"{luna}_names")
for s in seeds:
    pair(f"{jev}_{s}", f"{luna}_{s}")
print()
for m in (jev, luna):
    accs = [acc(load(f"{m}_{s}")) for s in seeds]
    print(f"{m} examples5 over 3 draws: mean {statistics.mean(accs):.3f}, min {min(accs):.3f}, max {max(accs):.3f}")
print()
# Option order: the same options, shuffled instead of alphabetical.
for base, shuffled in (
    ("names", "names-shuffle1"),
    ("names", "names-shuffle2"),
    ("examples5", "examples5-shuffle1"),
):
    pair(f"{jev}_{base}", f"{jev}_{shuffled}")
"""Live Jev calls through OpenRouter's decisions endpoint (and GPT-6 Luna through chat completions),
with a global cost cap and resume.

usage: python -I jev_live.py KEYFILE DATA_DIR OUT_DIR {check|smoke|run|luna}
         [--set bench500|rest|full] [--variant names|examplesK] [--model typesafe/jev-1.13]
         [--llm openai/gpt-6-luna] [--limit N] [--cap 0.60] [--workers 8] [--pace 0]
         [--example-seed 0] [--shuffle-options SEED]
`run` calls Jev, `luna` calls the LLM; examplesK puts K training messages per intent in the options.
The key is read from KEYFILE and never printed.
"""

import argparse
import csv
import json
import random
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import requests

ap = argparse.ArgumentParser()
ap.add_argument("keyfile")
ap.add_argument("data")
ap.add_argument("out")
ap.add_argument("mode", choices=["check", "smoke", "run", "luna"])
ap.add_argument("--set", default="bench500", choices=["bench500", "rest", "full"])
ap.add_argument(
    "--variant", default="names", help="names, or examplesK for K training messages per intent"
)
ap.add_argument(
    "--cap",
    type=float,
    default=0.60,
    help="stop when total spend across all runs passes this (USD)",
)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--model", default="typesafe/jev-1.13")
ap.add_argument("--llm", default="openai/gpt-6-luna")
ap.add_argument("--limit", type=int, default=None, help="only the first N messages of the set")
ap.add_argument(
    "--pace", type=float, default=0.0, help="seconds to wait before each call (rate limits)"
)
ap.add_argument(
    "--example-seed", type=int, default=0, help="seed for drawing the K labeled messages per intent"
)
ap.add_argument(
    "--shuffle-options",
    type=int,
    default=None,
    help="shuffle the order of the options with this seed (default: alphabetical)",
)
a = ap.parse_args()

raw = Path(a.keyfile).read_text(encoding="utf8").strip()
key = next(
    (t for t in raw.replace("=", " ").split() if t.startswith("sk-or-")),
    raw.splitlines()[0].strip(),
)
H = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
S = requests.Session()
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
LEDGER = out / "spend.jsonl"  # every paid call across every run, for the global cap

if a.mode == "check":
    r = S.get("https://openrouter.ai/api/v1/key", headers=H, timeout=30)
    d = r.json().get("data", {})
    print(
        "status",
        r.status_code,
        {k: d.get(k) for k in ("label", "usage", "limit", "limit_remaining", "is_free_tier")},
    )
    r = S.get("https://openrouter.ai/api/v1/credits", headers=H, timeout=30)
    print("credits", r.status_code, r.json().get("data"))
    sys.exit()

data = Path(a.data)
with open(data / "test.csv", encoding="utf8") as f:
    rows = list(csv.DictReader(f))
with open(data / "train.csv", encoding="utf8") as f:
    train = list(csv.DictReader(f))
texts, gold = [r["text"] for r in rows], [r["category"] for r in rows]
labels = sorted(set(gold))

# Fixed sample: shuffle all test indices with seed 42 and keep the first 500.
idx = list(range(len(texts)))
random.Random(42).shuffle(idx)
sets = {"bench500": idx[:500], "rest": idx[500:], "full": idx}
todo = [1] if a.mode == "smoke" else sets[a.set][: a.limit]

if a.variant == "names":
    criteria = {l: l.replace("_", " ") for l in labels}
else:  # K training messages per intent appended to the description
    k = int(a.variant.removeprefix("examples"))
    rng = random.Random(a.example_seed)
    by = {}
    for r in train:
        by.setdefault(r["category"], []).append(r["text"])
    criteria = {
        l: l.replace("_", " ") + ". Examples: " + " | ".join(rng.sample(by[l], k)) for l in labels
    }
if a.shuffle_options is not None:  # same options, different order
    order = labels[:]
    random.Random(a.shuffle_options).shuffle(order)
    criteria = {l: criteria[l] for l in order}
Q = {
    "intent": {
        "type": "choice",
        "instructions": "Which banking customer-support intent does this message express?",
        "criteria": criteria,
    }
}
LUNA_SYS = (
    "Classify a bank customer's message into exactly one intent from the allowed list. "
    'Answer with JSON only: {"label": "<intent>", "confidence": <probability from 0 to 1 that the label is right>}.'
)

# Same options and, for examplesK, the same example messages Jev gets; the shared prefix lets the provider cache it.
LUNA_OPTIONS = (
    "Allowed intents: " + ", ".join(criteria)
    if a.variant == "names"
    else "Allowed intents, each with example messages:\n"
    + "\n".join(f"- {l}: {d}" for l, d in criteria.items())
)
tag = {
    "run": f"{a.variant}_{a.set}",
    "luna": "luna_" + ("" if a.variant == "names" else a.variant + "_") + a.set,
}.get(a.mode, "smoke")
if a.example_seed and a.variant != "names":
    tag += f"_seed{a.example_seed}"
if a.shuffle_options is not None:
    tag += f"_shuffle{a.shuffle_options}"
if a.mode == "run" and a.model != "typesafe/jev-1.13":
    tag = a.model.split("/")[-1] + "_" + tag
pred_file = out / f"jev_{tag}.jsonl"
done = {}
if pred_file.exists():
    for l in pred_file.read_text(encoding="utf8").splitlines():
        if l.strip():
            r = json.loads(l)
            done[r["i"]] = r
lock = threading.Lock()
spent = (
    sum(json.loads(l)["cost"] for l in LEDGER.read_text(encoding="utf8").splitlines() if l.strip())
    if LEDGER.exists()
    else 0.0
)
print(
    f"already spent {spent:.4f} USD across runs; cap {a.cap}; todo {len(todo) - len(done)}",
    flush=True,
)
stop = threading.Event()


def call_luna(i):
    body = {
        "model": a.llm,
        "temperature": 0,
        "reasoning": {"effort": "minimal"},
        "response_format": {"type": "json_object"},
        "usage": {"include": True},
        "messages": [
            {"role": "system", "content": LUNA_SYS},
            {"role": "user", "content": LUNA_OPTIONS + "\n\nMessage:\n" + texts[i]},
        ],
    }
    for attempt in range(6):
        time.sleep(a.pace)
        t0 = time.perf_counter()
        r = S.post(
            "https://openrouter.ai/api/v1/chat/completions", headers=H, json=body, timeout=120
        )
        lat = (time.perf_counter() - t0) * 1000
        if r.status_code in (429, 500, 502, 503) and attempt < 5:
            time.sleep(15 if r.status_code == 429 else 2**attempt)
            continue
        if r.status_code != 200:
            return {"i": i, "error": f"{r.status_code} {r.text[:300]}"}
        d = r.json()
        u = d.get("usage") or {}
        try:
            c = d["choices"][0]["message"]["content"]
            o = json.loads(c[c.find("{") : c.rfind("}") + 1])
            pred, conf = o.get("label"), min(max(float(o.get("confidence", 0.5)), 0.0), 1.0)
        except Exception:
            pred, conf = None, 0.0
        if pred not in labels:
            pred = "__invalid__"
        return {
            "i": i,
            "gold": gold[i],
            "pred": pred,
            "conf": conf,
            "latency_ms": lat,
            "cost": u.get("cost"),
            "usage": u,
            "model": d.get("model"),
        }


def call(i):
    if stop.is_set():
        return None
    if a.mode == "luna":
        return call_luna(i)
    body = {"model": a.model, "state": texts[i], "questions": Q}
    for attempt in range(4):
        t0 = time.perf_counter()
        r = S.post("https://openrouter.ai/api/alpha/decisions", headers=H, json=body, timeout=60)
        lat = (time.perf_counter() - t0) * 1000
        if r.status_code in (429, 500, 502, 503) and attempt < 3:
            time.sleep(2**attempt)
            continue
        if r.status_code != 200:
            return {"i": i, "error": f"{r.status_code} {r.text[:300]}"}
        d = r.json()
        ans = d["answers"]["intent"]
        probs = ans.get("probabilities") or {ans["choice"]: ans.get("confidence", 1.0)}
        probs = {k: float(v) for k, v in probs.items()}
        u = d.get("usage") or {}
        pred = max(probs, key=probs.get)
        return {
            "i": i,
            "gold": gold[i],
            "pred": pred,
            "conf": probs[pred],
            "latency_ms": lat,
            "cost": u.get("cost", u.get("total_cost")),
            "usage": u,
            "model": d.get("model"),
            **({"raw": d} if a.mode == "smoke" else {}),
        }


errors = 0
with (
    ThreadPoolExecutor(a.workers) as ex,
    open(pred_file, "a", encoding="utf8") as pf,
    open(LEDGER, "a", encoding="utf8") as lf,
):
    futs = [ex.submit(call, i) for i in todo if i not in done]
    for n, fu in enumerate(as_completed(futs), 1):
        r = fu.result()
        if r is None:
            continue
        if "error" in r:
            errors += 1
            print("error", r["error"], flush=True)
            if errors >= 10:
                stop.set()
            continue
        with lock:
            c = float(r["cost"] or 0)
            spent += c
            lf.write(json.dumps({"tag": tag, "i": r["i"], "cost": c}) + "\n")
            lf.flush()
            pf.write(json.dumps(r) + "\n")
            pf.flush()
            done[r["i"]] = r
            if spent > a.cap and not stop.is_set():
                print(f"cost cap reached at {spent:.4f} USD, stopping", flush=True)
                stop.set()
        if n % 100 == 0:
            print(f"{n}/{len(futs)} spent {spent:.4f}", flush=True)

rs = [done[i] for i in todo if i in done]
if a.mode == "smoke":
    print(json.dumps(rs[0], indent=1)[:3000]) if rs else print("no result")
acc = sum(r["pred"] == r["gold"] for r in rs) / max(len(rs), 1)
cs = [float(r["cost"] or 0) for r in rs]
lats = sorted(r["latency_ms"] for r in rs) or [0]
print(
    json.dumps(
        {
            "tag": tag,
            "n": len(rs),
            "of": len(todo),
            "errors": errors,
            "accuracy": round(acc, 4),
            "cost_this_set": round(sum(cs), 5),
            "cost_per_call": (sum(cs) / len(cs)) if cs else None,
            "p50_ms": round(lats[len(lats) // 2]),
            "total_spent_all_runs": round(spent, 5),
        }
    )
)
"""Banking77 benchmark: Keras classifiers (with and without exact/fuzzy layers) and local zero-shot models.

Usage: BENCH_ROOT=. python keras_bench.py <stage>, where stage is one of
  keras | only | curve | cosine | bart | laya | vega
Each stage writes its own JSON to out/, so one failure doesn't lose the others.

The original run read the 500 messages from a file; this version draws the same 500
(seed-42 shuffle of the test set, the same draw jev_live.py uses).
"""

import json
import os
import random
import re
import sys
import time
import zipfile
from pathlib import Path

os.environ.setdefault("KERAS_BACKEND", "torch")

import numpy as np
import pandas as pd

ROOT = Path(os.environ["BENCH_ROOT"])
DATA, OUT = ROOT / "data", ROOT / "out"
SEED = 42

train_df = pd.read_csv(DATA / "banking77/train.csv")
test_df = pd.read_csv(DATA / "banking77/test.csv")
LABELS = sorted(test_df.category.unique())
L2I = {l: i for i, l in enumerate(LABELS)}

_order = list(range(len(test_df)))
random.Random(SEED).shuffle(_order)
SAMPLE = [test_df.text[i] for i in _order[:500]]
GOLD = {test_df.text[i]: test_df.category[i] for i in _order[:500]}


def norm(t):
    return " ".join(re.findall(r"[a-z0-9']+", t.lower()))


def split_train():
    """Stratified 90/10 split; the 10% only tunes the fuzzy threshold."""
    rng = random.Random(SEED)
    fit, val = [], []
    for _, g in train_df.groupby("category"):
        idx = list(g.index)
        rng.shuffle(idx)
        n = max(1, round(len(idx) * 0.1))
        val += idx[:n]
        fit += idx[n:]
    return train_df.loc[fit].reset_index(drop=True), train_df.loc[val].reset_index(drop=True)


def k_shot(df, k, seed):
    if k == "all":
        return df
    return (
        df.groupby("category", group_keys=False)
        .sample(n=k, random_state=seed)
        .reset_index(drop=True)
    )


def steps_to_epochs(n, target, batch=32):
    return max(1, min(600, int(np.ceil(target * batch / n))))


# ---- layers -----------------------------------------------------------------


class Rules:
    """Exact then fuzzy lookup against the training messages."""

    def __init__(self, df):
        from rapidfuzz import fuzz, process

        self.fuzz, self.process = fuzz, process
        self.exact = {}
        for t, c in zip(df.text, df.category):
            self.exact.setdefault(norm(t), c)
        self.keys = list(self.exact)
        self.threshold = None

    def lookup(self, text):
        q = norm(text)
        if q in self.exact:
            return self.exact[q], 1.0, "exact"
        if self.threshold is not None:
            m = self.process.extractOne(
                q, self.keys, scorer=self.fuzz.ratio, score_cutoff=self.threshold
            )
            if m:
                return self.exact[m[0]], m[1] / 100, "fuzzy"
        return None

    def tune(self, val):
        # Pick the lowest threshold whose fuzzy hits are at least 90% precise on validation.
        q = [norm(t) for t in val.text]
        best = [self.process.extractOne(x, self.keys, scorer=self.fuzz.ratio) for x in q]
        rows = [(m[1], self.exact[m[0]] == g) for m, g in zip(best, val.category)]
        table = {}
        for th in range(70, 100):
            hits = [ok for s, ok in rows if s >= th]
            table[th] = (len(hits), float(np.mean(hits)) if hits else None)
        chosen = next((t for t in range(70, 100) if table[t][1] and table[t][1] >= 0.9), 99)
        self.threshold = chosen
        return chosen, table


# ---- keras models -----------------------------------------------------------


def dense_head(input_dim, hidden=256, dropout=0.3):
    import keras

    m = keras.Sequential(
        [
            keras.Input(shape=(input_dim,)),
            keras.layers.Dense(hidden, activation="relu"),
            keras.layers.Dropout(dropout),
            keras.layers.Dense(len(LABELS), activation="softmax"),
        ]
    )
    m.compile(
        optimizer=keras.optimizers.Adam(1e-3),
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return m


def embed(texts, cache={}):
    from sentence_transformers import SentenceTransformer

    if "m" not in cache:
        cache["m"] = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu")
    return cache["m"].encode(
        list(texts), batch_size=128, normalize_embeddings=True, show_progress_bar=False
    )


class Glove:
    def __init__(self, df, max_len=40, dim=100):
        toks = [norm(t).split() for t in df.text]
        counts = {}
        for s in toks:
            for w in s:
                counts[w] = counts.get(w, 0) + 1
        self.vocab = {w: i + 2 for i, w in enumerate(sorted(counts))}
        self.max_len, self.dim = max_len, dim
        self.matrix = np.zeros((len(self.vocab) + 2, dim), dtype="float32")
        path = DATA / "glove/glove.6B.zip"
        with zipfile.ZipFile(path) as z, z.open(f"glove.6B.{dim}d.txt") as f:
            for raw in f:
                parts = raw.decode("utf8").rstrip().split(" ")
                if parts[0] in self.vocab:
                    self.matrix[self.vocab[parts[0]]] = np.asarray(parts[1:], dtype="float32")

    def encode(self, texts):
        out = np.zeros((len(texts), self.max_len), dtype="int32")
        for i, t in enumerate(texts):
            ids = [self.vocab.get(w, 1) for w in norm(t).split()][: self.max_len]
            out[i, : len(ids)] = ids
        return out

    def model(self):
        import keras

        emb = keras.layers.Embedding(self.matrix.shape[0], self.dim, trainable=False)
        m = keras.Sequential(
            [
                keras.Input(shape=(self.max_len,), dtype="int32"),
                emb,
                keras.layers.Bidirectional(keras.layers.LSTM(128, return_sequences=True)),
                keras.layers.GlobalMaxPooling1D(),
                keras.layers.Dense(64, activation="relu"),
                keras.layers.Dropout(0.5),
                keras.layers.Dense(len(LABELS), activation="softmax"),
            ]
        )
        emb.set_weights([self.matrix])
        m.compile(
            optimizer=keras.optimizers.Adam(1e-3),
            loss="sparse_categorical_crossentropy",
            metrics=["accuracy"],
        )
        return m


def train(kind, df, seed, target_steps, glove=None):
    """Returns (predict_fn(texts)->proba, seconds)."""
    import keras

    keras.utils.set_random_seed(seed)
    y = df.category.map(L2I).to_numpy()
    t0 = time.perf_counter()
    if kind == "minilm":
        x = embed(df.text)
        m = dense_head(x.shape[1])
        fn = lambda ts: m.predict(embed(ts), verbose=0, batch_size=256)
    elif kind == "tfidf":
        from sklearn.feature_extraction.text import TfidfVectorizer
        from sklearn.pipeline import make_union

        tf = make_union(
            TfidfVectorizer(ngram_range=(1, 2), max_features=6000, sublinear_tf=True),
            TfidfVectorizer(
                analyzer="char_wb", ngram_range=(3, 5), max_features=6000, sublinear_tf=True
            ),
        )
        x = tf.fit_transform(df.text).toarray().astype("float32")
        m = dense_head(x.shape[1], hidden=512, dropout=0.5)
        fn = lambda ts: m.predict(
            tf.transform(ts).toarray().astype("float32"), verbose=0, batch_size=256
        )
    elif kind == "glove":
        x = glove.encode(list(df.text))
        m = glove.model()
        fn = lambda ts: m.predict(glove.encode(list(ts)), verbose=0, batch_size=256)
    else:
        raise ValueError(kind)
    m.fit(x, y, epochs=steps_to_epochs(len(x), target_steps), batch_size=32, verbose=0)
    return fn, time.perf_counter() - t0


def accuracy(fn, df):
    return float((fn(list(df.text)).argmax(1) == df.category.map(L2I).to_numpy()).mean())


def layered_predict(rules, fn, texts):
    """Exact, then fuzzy, then the model for whatever is left."""
    res, rest = {}, []
    for t in texts:
        hit = rules.lookup(t)
        if hit:
            res[t] = hit
        else:
            rest.append(t)
    if rest:
        for t, p in zip(rest, fn(rest)):
            i = int(p.argmax())
            res[t] = (LABELS[i], float(p[i]), "model")
    return res


def latency(call, texts):
    out = []
    for t in texts:
        t0 = time.perf_counter()
        call(t)
        out.append((time.perf_counter() - t0) * 1000)
    return {"p50_ms": float(np.percentile(out, 50)), "p95_ms": float(np.percentile(out, 95))}


def dump(name, preds, **extra):
    """preds: text -> (label, confidence[, layer])"""
    rows = {
        t: {"pred": p[0], "conf": float(p[1]), "layer": p[2] if len(p) > 2 else None}
        for t, p in preds.items()
    }
    (OUT / f"{name}.json").write_text(
        json.dumps({"name": name, "preds": rows, **extra}, indent=0), encoding="utf8"
    )
    print(name, "saved", extra, flush=True)


# ---- stages -----------------------------------------------------------------


def stage_keras():
    fit, val = split_train()
    rules = Rules(fit)
    th, table = rules.tune(val)
    print("fuzzy threshold", th, {k: table[k] for k in sorted(table) if k % 5 == 0}, flush=True)
    glove = Glove(fit)
    all_test = list(test_df.text)
    for kind, steps in (("tfidf", 4000), ("minilm", 4000), ("glove", 4000)):
        fn, secs = train(kind, fit, SEED, steps, glove)
        p = layered_predict(rules, fn, SAMPLE)
        full = layered_predict(rules, fn, all_test)
        full_acc = float(np.mean([full[t][0] == c for t, c in zip(test_df.text, test_df.category)]))
        layers = {k: sum(1 for t in SAMPLE if p[t][2] == k) for k in ("exact", "fuzzy", "model")}
        lat = latency(lambda t: layered_predict(rules, fn, [t]), SAMPLE[:200])
        dump(
            f"layered_{kind}",
            p,
            train_seconds=secs,
            full_test_acc=full_acc,
            layers=layers,
            latency=lat,
            fuzzy_threshold=th,
            train_examples=len(fit),
            val_acc_model_only=accuracy(fn, val),
        )


def stage_only():
    """Same seed and data as stage_keras, without the exact/fuzzy layers."""
    fit, _ = split_train()
    glove = Glove(fit)
    for kind, steps in (("tfidf", 4000), ("minilm", 4000), ("glove", 4000)):
        fn, secs = train(kind, fit, SEED, steps, glove)
        proba = fn(SAMPLE)
        p = {t: (LABELS[int(r.argmax())], float(r.max()), "model") for t, r in zip(SAMPLE, proba)}
        full_acc = accuracy(fn, test_df)
        lat = latency(lambda t: fn([t]), SAMPLE[:200])
        dump(
            f"only_{kind}",
            p,
            train_seconds=secs,
            full_test_acc=full_acc,
            latency=lat,
            train_examples=len(fit),
        )
        lay = json.loads((OUT / f"layered_{kind}.json").read_text(encoding="utf8"))["preds"]
        for layer in ("exact", "fuzzy", "model"):
            ts = [t for t in SAMPLE if lay[t]["layer"] == layer]
            if ts:
                print(
                    kind,
                    layer,
                    "n",
                    len(ts),
                    "layered_acc",
                    round(float(np.mean([lay[t]["pred"] == GOLD[t] for t in ts])), 3),
                    "model_only_acc",
                    round(float(np.mean([p[t][0] == GOLD[t] for t in ts])), 3),
                    flush=True,
                )


def stage_curve():
    fit, _ = split_train()
    glove = Glove(fit)
    rows = []
    for kind, seeds, steps in (
        ("tfidf", (0, 1, 2), 4000),
        ("minilm", (0, 1, 2), 4000),
        ("glove", (0,), 2000),
    ):
        for k in (1, 3, 5, 10, 30, "all"):
            accs, secs = [], []
            for s in seeds:
                sub = k_shot(fit, k, s)
                fn, t = train(kind, sub, s, steps, glove)
                preds = fn(SAMPLE).argmax(1)
                accs.append(float(np.mean([LABELS[i] == GOLD[t2] for i, t2 in zip(preds, SAMPLE)])))
                secs.append(t)
            rows.append(
                {
                    "model": kind,
                    "k": k,
                    "acc_mean": float(np.mean(accs)),
                    "acc_all": accs,
                    "train_seconds": float(np.mean(secs)),
                    "n_train": int(len(k_shot(fit, k, 0))),
                }
            )
            print(rows[-1], flush=True)
            (OUT / "curve.json").write_text(json.dumps(rows, indent=1), encoding="utf8")


def stage_cosine():
    names = [l.replace("_", " ") for l in LABELS]
    lv = embed(names)
    tv = embed(SAMPLE)
    sims = tv @ lv.T
    from scipy.special import softmax

    probs = softmax(sims * 20, axis=1)
    p = {t: (LABELS[int(r.argmax())], float(r.max())) for t, r in zip(SAMPLE, probs)}
    lat = latency(lambda t: embed([t]) @ lv.T, SAMPLE[:200])
    dump("zero_minilm_cosine", p, latency=lat)


def stage_bart():
    import torch
    from transformers import AutoModelForSequenceClassification, AutoTokenizer

    name = "facebook/bart-large-mnli"
    tok = AutoTokenizer.from_pretrained(name)
    model = AutoModelForSequenceClassification.from_pretrained(name).eval()
    ent = model.config.label2id.get("entailment", 2)
    hyps = [f"This message is about {l.replace('_', ' ')}." for l in LABELS]

    @torch.inference_mode()
    def score(text):
        scores = []
        for i in range(0, len(hyps), 77):
            enc = tok(
                [text] * len(hyps[i : i + 77]),
                hyps[i : i + 77],
                return_tensors="pt",
                padding=True,
                truncation=True,
            )
            scores.append(model(**enc).logits[:, ent])
        return torch.softmax(torch.cat(scores), 0).numpy()

    t0 = time.perf_counter()
    p = {}
    for n, t in enumerate(SAMPLE):
        r = score(t)
        p[t] = (LABELS[int(r.argmax())], float(r.max()))
        if n % 50 == 0:
            print("bart", n, flush=True)
    dump("zero_bart_mnli", p, seconds=time.perf_counter() - t0, latency=latency(score, SAMPLE[:30]))


def laya_like(name, make_agent):
    q = {
        "intent": {
            "type": "choice",
            "instructions": "Which banking customer-support intent does this message express?",
            "criteria": {l: l.replace("_", " ") for l in LABELS},
        }
    }
    agent = make_agent()

    def call(t):
        return agent.predict(t, q)["answers"]["intent"]

    t0 = time.perf_counter()
    p = {}
    for n, t in enumerate(SAMPLE):
        a = call(t)
        probs = a["probabilities"]
        p[t] = (a["choice"], float(max(probs.values())))
        if n % 50 == 0:
            print(name, n, round(time.perf_counter() - t0, 1), flush=True)
    dump(name, p, seconds=time.perf_counter() - t0, latency=latency(call, SAMPLE[:100]))


def stage_laya():
    import laya

    laya_like("zero_laya", lambda: laya.Agent("convaiinnovations/laya"))


def stage_vega():
    import laya

    laya_like("zero_vega", lambda: laya.Agent(vegaml=True))


if __name__ == "__main__":
    globals()[f"stage_{sys.argv[1]}"]()
ConsoleReplaying a recording. No API is called.
Run a step and its output streams here.

Replaying a recording. No API is called.

Step 1 · jev_live.py · lines 88–91

Pick the messages

Banking77's test set is shuffled with seed 42 and the first 500 messages are kept. Every model below sees the same 500.

Step 2 · jev_live.py · lines 94–95, 209–212

Jev with intent names only

Each option is just the intent's name, for example "card arrival". One call per message to the decisions endpoint.

$ python jev_live.py openrouter.txt data/banking77 out run --set bench500 --variant names
already spent 0.0001 USD across runs; cap 0.6; todo 500
100/500 spent 0.0072
200/500 spent 0.0143
300/500 spent 0.0213
400/500 spent 0.0284
500/500 spent 0.0355
{"tag": "names_bench500", "n": 500, "of": 500, "errors": 0, "accuracy": 0.818, "cost_this_set": 0.03546, "cost_per_call": 7.0912716e-05, "p50_ms": 253, "total_spent_all_runs": 0.03553}

What came out: 81.8% right. $0.00007 a call, median 253 ms.

Step 3 · jev_live.py · lines 96–104

Add five examples per intent

Same call, but each option now carries five real training messages for that intent. The request gets longer, so it costs more.

$ python jev_live.py openrouter.txt data/banking77 out run --variant examples5 --cap 1.00
…
400/500 spent 0.5178
500/500 spent 0.5489
{"tag": "examples5_bench500", "n": 500, "of": 500, "errors": 0, "accuracy": 0.93, "cost_this_set": 0.15539, "cost_per_call": 0.000310774716, "p50_ms": 496, "total_spent_all_runs": 0.54886}

The first lines of this output weren't kept, only the last ones.

What came out: 93% right. The call now costs $0.00031, about four times more, and the median is 496 ms.

Step 4 · jev_live.py · lines 98

Draw the five examples again

Which five messages land in each option is a random draw. Two more draws with different seeds show how much that choice moves the result.

$ python jev_live.py openrouter.txt data/banking77 out run --set bench500 --variant examples5 --example-seed 1 --cap 8
…
{"tag": "examples5_bench500_seed1", "n": 500, "of": 500, "errors": 0, "accuracy": 0.898, "cost_this_set": 0.15734, "cost_per_call": 0.00031468071600000003, "p50_ms": 317, "total_spent_all_runs": 0.15734}

The first lines of this output weren't kept, only the last ones.

What came out: 89.8% with the second draw. The third, --example-seed 2, gave 91.6%. With the first draw's 93%, that's a mean of 91.5%.

Step 5 · jev_live.py · lines 105–108

Shuffle the order of the options

TypeSafe's docs say Jev leans toward the option that comes first. The same options in a random order instead of alphabetical show whether that matters here.

$ python jev_live.py openrouter.txt data/banking77 out run --set bench500 --variant names --shuffle-options 1 --cap 8
…
{"tag": "names_bench500_shuffle1", "n": 500, "of": 500, "errors": 0, "accuracy": 0.816, "cost_this_set": 0.03546, "cost_per_call": 7.0912716e-05, "p50_ms": 251, "total_spent_all_runs": 0.34518}

The first lines of this output weren't kept, only the last ones.

What came out: 81.6%, against 81.8% in alphabetical order. A second shuffle gave 83.2%, and five examples in shuffled order 92.8% against 93%.

Step 6 · jev_live.py · lines 158–169

Ask a small LLM the same thing

GPT-6 Luna gets the same options and examples as a chat message, at temperature 0 with minimal reasoning, and answers in JSON. It runs on all 500 messages, once with intent names only and once per example draw.

$ python jev_live.py openrouter.txt data/banking77 out luna --set bench500 --variant examples5 --workers 4 --cap 5
…
{"tag": "luna_examples5_bench500", "n": 500, "of": 500, "errors": 0, "accuracy": 0.91, "cost_this_set": 0.40875, "cost_per_call": 0.0008175004999999999, "p50_ms": 1536, "total_spent_all_runs": 0.44698}

The first lines of this output weren't kept, only the last ones.

What came out: 91% with the first draw. $0.00082 a call, median 1,536 ms. With intent names only, 84.2% and a median of 2,615 ms.

Step 7 · compare.py · lines 32–45

Compare them on the same messages

Every pair is scored on the same 500 messages. A bootstrap, which resamples the 500 messages 5,000 times, gives a 95% range for the gap. An exact McNemar test looks only at the messages where one model was right and the other wrong, and its p says how often chance alone would give a gap this big.

$ python compare.py results
jev-1.13_names vs gpt-6-luna_names: n=500 0.818 vs 0.842 gap CI95 [-0.050,+0.000] only_first=15 only_second=27 mcnemar_p=0.09
jev-1.13_examples5 vs gpt-6-luna_examples5: n=500 0.930 vs 0.910 gap CI95 [+0.002,+0.038] only_first=16 only_second=6 mcnemar_p=0.05
jev-1.13_examples5-seed1 vs gpt-6-luna_examples5-seed1: n=500 0.898 vs 0.904 gap CI95 [-0.024,+0.012] only_first=8 only_second=11 mcnemar_p=0.65
jev-1.13_examples5-seed2 vs gpt-6-luna_examples5-seed2: n=500 0.916 vs 0.912 gap CI95 [-0.014,+0.022] only_first=11 only_second=9 mcnemar_p=0.82
jev-1.13 examples5 over 3 draws: mean 0.915, min 0.898, max 0.930
gpt-6-luna examples5 over 3 draws: mean 0.909, min 0.904, max 0.912

Only the part of the log that belongs to this step.

What came out: With intent names only, Luna is 2.4 points ahead, a borderline gap (p = 0.09, about one time in eleven by chance). With five examples, the winner depends on the draw, and the means over three draws are 91.5% and 90.9%.

Step 8 · keras_bench.py · lines 344–350

Train Keras on a few labels

A small Keras head on MiniLM embeddings, trained with 1 to all labelled messages per intent, three seeds each, scored on the same 500.

$ BENCH_ROOT=. python keras_bench.py curve
{'model': 'minilm', 'k': 1, 'acc_mean': 0.554, 'acc_all': [0.554, 0.574, 0.534], 'train_seconds': 13.229416999998648, 'n_train': 77}
{'model': 'minilm', 'k': 3, 'acc_mean': 0.7373333333333333, 'acc_all': [0.754, 0.746, 0.712], 'train_seconds': 18.042697266667044, 'n_train': 231}
{'model': 'minilm', 'k': 5, 'acc_mean': 0.8153333333333332, 'acc_all': [0.818, 0.826, 0.802], 'train_seconds': 17.44797103333379, 'n_train': 385}
{'model': 'minilm', 'k': 10, 'acc_mean': 0.8713333333333333, 'acc_all': [0.876, 0.882, 0.856], 'train_seconds': 17.30311070000001, 'n_train': 770}
{'model': 'minilm', 'k': 30, 'acc_mean': 0.908, 'acc_all': [0.902, 0.916, 0.906], 'train_seconds': 19.115395966667467, 'n_train': 2310}
{'model': 'minilm', 'k': 'all', 'acc_mean': 0.9306666666666668, 'acc_all': [0.936, 0.926, 0.93], 'train_seconds': 30.014623000001546, 'n_train': 9000}

Only the part of the log that belongs to this step.

What came out: Five labeled messages per intent give 81.5%, about Jev with names only. All 9,000 labeled messages give 93.1%, a little above Jev's five-example mean of 91.5%.

Step 9 · keras_bench.py · lines 233–246

Put fuzzy matching in front

Exact match first, then fuzzy matching against the training messages, and the model only for what's left. Then the same model again without those layers.

$ BENCH_ROOT=. python keras_bench.py only
only_minilm saved {'train_seconds': 35.51382620000004, 'full_test_acc': 0.9253246753246753, 'latency': {'p50_ms': 25.145650000922615, 'p95_ms': 29.16941000130464}, 'train_examples': 9000}
minilm exact n 5 layered_acc 1.0 model_only_acc 1.0
minilm fuzzy n 224 layered_acc 0.871 model_only_acc 0.96
minilm model n 271 layered_acc 0.919 model_only_acc 0.919

Only the part of the log that belongs to this step.

What came out: On the 224 messages fuzzy matching caught, it was right 87.1% of the time. The model alone got 96% of them. The layer made things worse.

Scripts

Results

Paths in the commands are shortened. The scripts expect Banking77's train.csv and test.csv, and an OpenRouter key for Jev and Luna.

The first 200 of the 500 messages, one after anotherEach dot lands at the response time I measured for that message through OpenRouter, as if the messages were sent one after another. These are the first 200 of the 500 messages, with intent names only and no labeled messages. The first few Jev calls were slower.

Real time8 min 39 s

  • Jev 1.13163 / 200 right · 55 s
  • GPT-6 Luna165 / 200 right · 8 min 39 s

A filled dot is a right answer, an empty ring a wrong one.

What Jev does

You send some text and a list of options, and Jev returns a probability for each option. It doesn’t write text.

TypeSafe calls the text you send the state, the state field in the code further down. One call can ask several questions about the same text, each with its own list of options. TypeSafe’s docs say every question “is evaluated in parallel and in isolation against the same state in one go”.

TypeSafe hasn’t said which model Jev is built on, how big it is or what it was trained on, and it hasn’t published a paper. The training method has a name, Reinforcement Learning for Calibrated Decisions (RLCD), but no details on how it works.

My calls added a few details. I counted about 300 tokens for the message plus the 77 option names, but each call was billed about 1,690 input tokens. So TypeSafe probably wraps the request in something larger. Output tokens are free, and one call cost $0.00007.

TypeSafe’s launch post says Jev “can’t hallucinate”, that is, it can’t make up an answer. In practice that means it can’t return an option you didn’t list. It can still pick the wrong one.

An old idea, a new API

  • 2019: Yin, Hay and Roth framed zero-shot classification as entailment: does the text imply each label? Every label got a score against the text, and the open model bart-large-mnli still works this way out of the box.
  • 2020: The GPT-3 paper answered multiple-choice questions by comparing how likely each option was, not by generating an answer.
  • 2021: Calibrate Before Use showed that GPT-3, given a few examples in the prompt, favors labels that appear often or last among the prompt’s examples. TypeSafe’s docs report a related order effect: “Jev leans toward the option that comes first”.
  • 2023: Constrained generation, for example Outlines, made it cheap to stop an LLM from returning a label that isn’t on the list.

What’s new is the packaging: a fast API that does only this and is trained to return probabilities.

About as accurate as a small LLM

With only the intent names, on all 500 messages, Jev 1.13 got 82% and Jev 1.14, released in October, got 81%. The rest of the test uses Jev 1.13.

The two older zero-shot methods were far behind: 66% for embeddings from MiniLM, a small open model, matched to the closest intent name, and 56% for bart-large-mnli entailment.

Banking77’s test set has 3,080 messages, and my 500 come from it. On the whole test set Jev 1.13 got 80%, close to the 79.7% an independent evaluation reports.

I ran GPT-6 Luna on the same 500 messages, at temperature 0 with minimal reasoning, and asked it to answer in JSON with one intent from the list.

I tried two settings. In the first, each option is just an intent name. In the second, each option also carries five labeled messages for that intent. For the second, I drew the five messages three times with different random seeds and ran both models on each draw.

  • Intent names only: Luna 84.2%, Jev 81.8%. Luna took about 2.6 seconds per answer, Jev a quarter of a second. Both cost under $0.0001 a call.
  • Five labeled messages per intent, averaged over the three draws: Luna 90.9%, Jev 91.5%. Luna took 1.4 to 2.1 seconds and $0.0008 a call, Jev a third to half a second and $0.0003.

With intent names only, Luna is about two points ahead. That gap is borderline. If the two models were equally accurate, chance alone would produce a gap this big about one time in eleven. The real gap is most likely between zero and five points in Luna’s favor.

With labeled messages there’s no winner. Which five messages I drew mattered more than which model I used: Jev went from 89.8% to 93% across the three draws, Luna from 90.4% to 91.2%. On the first draw Jev was two points ahead, about as borderline as Luna’s lead with intent names only. On the other two, the models were within a point of each other.

So Jev has no accuracy edge over a small LLM. It’s several times faster, and with labeled messages it’s also about 2.6 times cheaper. The times are per call, measured while I sent Jev eight calls at a time and Luna four. They also moved between runs, so read them as rough sizes, not exact figures.

TypeSafe’s docs say Jev leans toward the option that comes first, so I also sent the same options in two random orders instead of alphabetical. With intent names only, accuracy went from 81.8% to 81.6% and 83.2%. With five labeled messages, from 93% to 92.8%. On this task the order didn’t change the result beyond noise.

How many labeled messages Keras needs

Since labeled messages made such a difference for Jev, I gave a small Keras classifier the same number of labeled messages per intent. It works on MiniLM embeddings of the messages. It’s the same kind of intent classifier as in my simple Keras chatbot, except that MiniLM makes the embeddings instead of the model learning its own.

The classifier trains on a CPU in about half a minute.

Labeled messages per intentAccuracy on the same 500 Banking77 messages. Jev 1.13 with five labeled messages is the mean of three draws, its other values are one run each. Keras values are the mean of three runs. I didn't run Jev with 30 or more labeled messages per intent.
  1. Labeled messages per intent: 0

    Intent names only. Keras can't train on nothing.

    • Jev82 / 100 %
  2. Labeled messages per intent: 1

    One labeled message per intent already helps Jev a lot.

    • Jev87 / 100 %
    • Keras + MiniLM55 / 100 %
  3. Labeled messages per intent: 3

    231 labeled messages in total.

    • Jev89 / 100 %
    • Keras + MiniLM74 / 100 %
  4. Labeled messages per intent: 5

    385 labeled messages. Jev stops improving here.

    • Jev91.5 / 100 %
    • Keras + MiniLM82 / 100 %
  5. Labeled messages per intent: 10

    770 labeled messages.

    • Jev92 / 100 %
    • Keras + MiniLM87 / 100 %
  6. Labeled messages per intent: 30

    2,310 labeled messages.

    • Keras + MiniLM91 / 100 %
  7. Labeled messages per intent: About 117

    All 9,000 labeled messages I used.

    • Keras + MiniLM93 / 100 %

With five labeled messages per intent, Jev averaged 91.5% on the 500 messages over three draws. Keras needed all 9,000 labeled messages to reach 93%. The five labeled messages per intent aren’t free for Jev, though. Every call carries them, so a call costs over four times as much as one with intent names only: $0.31 per thousand messages instead of $0.07.

This is the call. It needs train.csv from the Banking77 repository and an OpenRouter key, and it printed card_arrival 0.83 when I ran it:

python
import os

import pandas as pd
import requests

train = pd.read_csv("train.csv")
labels = sorted(train.category.unique())

# Five labeled messages per intent go into each option's description.
criteria = {}
for label in labels:
    examples = train[train.category == label].text.sample(n=5, random_state=0)
    criteria[label] = label.replace("_", " ") + ". Examples: " + " | ".join(examples)

response = requests.post(
    "https://openrouter.ai/api/alpha/decisions",
    headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
    json={
        "model": "typesafe/jev-1.13",
        "state": "I ordered a card last week and it still hasn't come.",
        "questions": {
            "intent": {
                "type": "choice",
                "instructions": "Which banking customer-support intent does this message express?",
                "criteria": criteria,
            }
        },
    },
    timeout=60,
)
answer = response.json()["answers"]["intent"]
print(answer["choice"], answer["confidence"])

The Jev, Luna and Keras steps, with their scripts and raw results, are in the test lab at the top. So are the repeat draws, the shuffled option orders and the comparison script. The two older zero-shot methods come from keras_bench.py, the script behind the Keras steps, but their result files aren’t in the lab.

I also put the layers from my old FAQ bot in front of the Keras model: exact match, then fuzzy match, which accepts text spelled almost the same, then the model. At the fuzzy-match cutoff I tuned, the extra layers cost about four points of accuracy. Banking intents often differ by a word or two, and comparing characters can’t see that.

Jev, a small LLM or Keras

  • Few labeled messages and the answer has to be fast: Jev, with about five labeled messages per intent. A new intent is a new entry in the list, with no retraining. Try more than one set of examples: in my test, which ones I drew moved Jev by about three points.
  • Few labeled messages and speed doesn’t matter: a small LLM does about as well, and you can use it for other jobs too.
  • Thousands of labeled messages and a lot of traffic: the Keras classifier. It’s as accurate, runs locally and has no per-call price.

This is one dataset. Different draws of the labeled messages moved Jev by about three points, so treat a gap of a point or two from a single run as noise. I also tried only one small LLM, at minimal reasoning. A larger model or more reasoning might close the gap with intent names only.

References

  1. TypeSafe: Introducing System One models and Jev
  2. TypeSafe docs
  3. TypeSafe docs: System One API reference
  4. TypeSafe docs: Jev 1.13 known weaknesses
  5. Yin, Hay, Roth (2019): Benchmarking Zero-shot Text Classification
  6. facebook/bart-large-mnli model card
  7. Brown et al. (2020): Language Models are Few-Shot Learners
  8. Zhao et al. (2021): Calibrate Before Use
  9. Willard, Louf (2023): Efficient Guided Generation for Large Language Models
  10. Casanueva et al. (2020): Efficient Intent Detection with Dual Sentence Encoders
  11. Deußer et al. (2026): Evaluating and Benchmarking the System One Model Jev
  12. all-MiniLM-L6-v2 model card
  13. OpenRouter docs: Jev on OpenRouter
  14. OpenRouter API reference: Submit a Decisions request
  15. OpenRouter: OpenAI GPT-6 Luna (openai/gpt-6-luna)

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.