Choosing Jev Confidence Thresholds in Laravel: Tune Them From a Labelled Sample, Not a Guess

Pick a Jev confidence threshold in Laravel from a labelled sample: replay rows through an artisan command, read precision and recall, then price the mistakes.

Steven Richardson
Steven Richardson
· 12 min read

Every Jev article I have written, including the companion Noul one, tells you to act above 0.9 and send anything lower to a human. Nobody — me included — ever said where 0.9 came from. It came from nowhere. A Jev confidence threshold you cannot defend to a stakeholder is a number you will quietly change the first time somebody complains, and this is the hundred-row process that replaces it with one you can justify.

Separate Jev's calibration from your confidence threshold#

Calibration and threshold are two different things, and conflating them is what produces the 0.9 habit. Calibration is a property of the model: of the answers Jev returns at roughly 0.8, roughly 80% should be correct. TypeSafe trains for that explicitly, and independent write-ups broadly agree it holds up on familiar data while drifting on data the model has not seen. Your threshold is a property of your workflow: it is the point where the cost of acting on a wrong answer exceeds the cost of asking a human.

Those costs are almost never symmetrical. Auto-tagging a support ticket wrongly costs a re-route. Auto-refunding wrongly costs the refund. Auto-suspending an account wrongly costs a customer. Same model, same calibration, three different thresholds — and no amount of reading the TypeSafe docs will hand you any of them.

Two more things follow from that. Calibration is a statement about groups of predictions, so it never promises that a particular 0.84 answer is right. And a Noul has no confidence field at all — the probability is the signal — so "threshold" means the Noul value itself, while on a Choice it means confidence.

Build a labelled sample from your own data#

Pull 100 to 200 rows out of production with a seeded query so the sample is reproducible, then have a human label them. This is the only step that costs real time, and it is the step everyone skips.

<?php

// A one-off artisan command, or a seeder for your local copy.
use App\Models\Enquiry;

$sample = Enquiry::query()
    // Seeded so re-running the tuner pulls the same rows.
    ->inRandomOrder(seed: 20261126)
    ->limit(200)
    ->get(['id', 'subject', 'body', 'channel']);

Stratify if your positive class is rare. A flat random draw on a 2% spam rate gives you four spam rows in two hundred, and a precision figure computed on four rows is noise. Take 100 rows of each class and keep the real prevalence in a config value so you can weight the results later.

Store the labels in a plain table rather than a CSV that someone will reformat in Excel. The migration is small:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('jev_judgements', function (Blueprint $table): void {
            $table->id();
            $table->string('question_key');            // 'is_spam', 'category', ...
            $table->morphs('subject');                 // whatever you are judging
            $table->string('human_label');             // the ground truth
            $table->string('jev_label')->nullable();   // what Jev picked
            $table->float('confidence');               // Noul value, or Choice confidence
            $table->json('probabilities')->nullable(); // the full Choice distribution
            $table->string('model_version');           // 'jev-1.14.0', never the alias
            $table->unsignedInteger('input_tokens');
            $table->timestamps();

            $table->index(['question_key', 'model_version']);
        });
    }
};

The two columns that matter in six months are probabilities and model_version. Keeping the raw distribution means re-tuning a threshold is a SELECT, not another paid run against the API.

Replay the sample through an artisan command#

The tuner is one command that reads the labelled rows, sends each one to Jev, and persists every raw probability. Batch the questions that share state into a single request — the state dominates the input tokens, which is the argument I worked through in batching Jev questions into one request, and it applies just as much to a tuning run as to production.

<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\JevJudgement;
use App\Models\JevSample;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

final class TuneJevThreshold extends Command
{
    protected $signature = 'jev:tune {question} {--sample=200}';

    protected $description = 'Replay a labelled sample through Jev and store every raw probability.';

    public function handle(): int
    {
        $rows = JevSample::forQuestion($this->argument('question'))
            ->limit((int) $this->option('sample'))
            ->get();

        $this->withProgressBar($rows, function (JevSample $row): void {
            $response = Http::withToken(config('services.typesafe.key'))
                ->timeout(30)
                // A 429 part way through a paid run should not cost you the row.
                ->retry(3, 200, throw: false)
                ->post('https://api.typesafe.ai/v1/systemone', [
                    // Pin the version. An alias re-points and invalidates the run.
                    'model' => config('jev.model'),
                    'state' => ['subject' => $row->subject, 'body' => $row->body],
                    'questions' => [
                        'is_spam' => [
                            'type' => 'noul',
                            'instructions' => 'This enquiry is unsolicited commercial mail or spam.',
                            'criteria' => [
                                'true' => 'Bulk marketing, SEO or link-building offers, crypto pitches, recruiter spam.',
                                'false' => 'A genuine customer enquiry, complaint, invoice query or supplier message.',
                            ],
                        ],
                    ],
                ])->throw()->json();

            JevJudgement::create([
                'question_key' => 'is_spam',
                'subject_type' => $row::class,
                'subject_id' => $row->getKey(),
                'human_label' => $row->human_label,
                // A Noul carries only `noul`. There is no confidence key on it.
                'confidence' => (float) $response['answers']['is_spam']['noul'],
                // What actually answered, not what you asked for.
                'model_version' => $response['model'],
                'input_tokens' => (int) $response['usage']['input_tokens'],
            ]);
        });

        return self::SUCCESS;
    }
}

Two deliberate choices there. The retry keeps a rate limit from throwing away rows you have already paid for. And storing $response['model'] rather than config('jev.model') means the record says which version produced the number, which is the thing that makes the run reproducible later.

Read the precision and recall table#

Sweep candidate thresholds from 0.50 to 0.99 over the stored judgements and print the counts. The shape of the curve is the whole output — a single number tells you nothing about what you give up to get it.

<?php

declare(strict_types=1);

namespace App\Support\Jev;

final readonly class ThresholdReport
{
    /** @param iterable<object{confidence: float, human_label: string}> $judgements */
    public function __construct(private iterable $judgements, private string $positive) {}

    /** @return list<array{threshold: float, tp: int, fp: int, fn: int, precision: ?float, recall: ?float}> */
    public function sweep(float $from = 0.50, float $to = 0.99, float $step = 0.05): array
    {
        $rows = [];

        for ($t = $from; $t <= $to + 1e-9; $t += $step) {
            $tp = $fp = $fn = 0;

            foreach ($this->judgements as $judgement) {
                $predicted = $judgement->confidence >= $t;
                $actual = $judgement->human_label === $this->positive;

                match (true) {
                    $predicted && $actual => $tp++,
                    $predicted && ! $actual => $fp++,
                    ! $predicted && $actual => $fn++,
                    default => null,
                };
            }

            $rows[] = [
                'threshold' => round($t, 2),
                'tp' => $tp,
                'fp' => $fp,
                'fn' => $fn,
                // Undefined, not zero, when nothing was predicted positive.
                'precision' => $tp + $fp === 0 ? null : $tp / ($tp + $fp),
                'recall' => $tp + $fn === 0 ? null : $tp / ($tp + $fn),
            ];
        }

        return $rows;
    }
}

Returning null rather than 0.0 for an undefined precision matters. A threshold that predicts no positives has no precision, and printing 0% there sends you off tuning a number when the real answer is "label more rows".

A real run looks like this — a spam Noul over 180 enquiries, 41 of them genuinely spam:

threshold  precision  recall   tp   fp   fn
0.50       0.68       0.98     40   19    1
0.60       0.76       0.95     39   12    2
0.70       0.86       0.90     37    6    4
0.80       0.92       0.85     35    3    6
0.90       0.97       0.71     29    1   12
0.95       1.00       0.54     22    0   19

Precision climbs, recall falls, and between 0.80 and 0.90 you are trading fourteen points of recall for five points of precision. That sentence is what the table exists to produce.

Pick the Jev confidence threshold from a business constraint#

Work backwards from a constraint somebody outside engineering recognises, not from a round number. "No more than one wrongly auto-binned enquiry per 200" is a constraint. "0.9" is not.

On the table above, one false positive in 180 is the 0.90 row. If the business instead says "we cannot afford to miss more than 10% of spam", recall of 0.90 or better puts you at 0.70 and six false positives. You cannot have both, and the table turns that from an argument into a choice.

Write the chosen number down where a human can find it, with the run that produced it:

<?php

// config/jev.php
return [
    'model' => env('JEV_MODEL', 'jev-1.14.0'),

    'thresholds' => [
        // Tuned 2026-11-26 on 180 labelled enquiries, jev-1.14.0.
        // 0.90 => precision 0.97, recall 0.71, 1 false positive in 180.
        'is_spam' => (float) env('JEV_IS_SPAM_THRESHOLD', 0.90),
    ],
];

A threshold without that comment is a magic number again within a quarter.

Set two thresholds and a human band#

One cut-off forces every item into act-or-ignore. Two cut-offs give you a middle band that goes to a person, and the same sweep table picks both: an upper bound where precision on the positive class is acceptable, and a lower bound where precision on the negative class is acceptable.

<?php

declare(strict_types=1);

namespace App\Support\Jev;

enum Verdict: string
{
    case AutoBin = 'auto_bin';
    case Review = 'review';
    case Deliver = 'deliver';
}

final readonly class SpamGate
{
    public function __construct(private float $high, private float $low) {}

    public function decide(float $noul): Verdict
    {
        return match (true) {
            $noul >= $this->high => Verdict::AutoBin,
            $noul <= $this->low => Verdict::Deliver,
            default => Verdict::Review,
        };
    }
}

Check the width of the band before you ship it. A 0.15/0.90 pair on that sample leaves 23 of 180 items in the middle — 13% going to a human, which is survivable. If your band swallows 40% of traffic the thresholds are not the problem; the question wording is, and the fix is to rewrite the false criteria rather than squeeze the band. The same routing shape drives confidence-gated intent routing, and when several answers have to combine into one verdict, weighted composite scoring is the step up from a single gate.

Work out cost per 1,000 items#

Sum the tokens from the same run, divide by the row count, scale to a thousand. Jev bills input tokens and gives output tokens away free, so cost tracks state size and nothing else.

<?php

$judgements = JevJudgement::query()
    ->where('question_key', 'is_spam')
    ->where('model_version', config('jev.model'))
    ->get(['input_tokens']);

$tokensPerItem = $judgements->avg('input_tokens');

// Rate in dollars per token — published Jev pricing is around $0.042 per million.
$costPerThousand = $tokensPerItem * 1_000 * config('services.typesafe.input_price_per_token');

TypeSafe's own /v1/systemone response carries input_tokens and output_tokens only, so on the direct integration you apply the rate yourself. Calling Jev through OpenRouter's Decisions API instead returns a usage.cost figure in dollars on every response, which skips the arithmetic — one published run there came out at roughly $0.026 per 1,000 short items at about 610 input tokens each. Measure your own sample rather than quoting anyone's blog post, mine included, and put the per-thousand figure directly next to the precision figure in whatever you show the business. The general shape of that logging is the one in tracking token usage and cost.

Re-tune when the model version or the data moves#

A threshold is tuned against one model version and one distribution of inputs, and both move. The jev-latest alias was re-pointed from 1.13.0 to 1.14.0 about a week after that release, which silently invalidates every number above for anyone who pinned the alias instead of the version.

Gate it in CI next to your existing eval suite. The judgements table already holds everything needed: replay the stored sample against the configured version, recompute precision at the configured threshold, and fail the build when it drops below the documented figure. That is the same mechanism as golden-dataset LLM evals in Pest and CI, with a far cheaper model underneath.

Re-run the full tuner on three triggers: the pinned model version changes, the CI precision check fails, or the upstream data shifts — a new acquisition channel, a new language, a new product line.

Test the tuner with Http::fake()#

The maths in ThresholdReport is the part that must never be wrong, and it has no business touching the network to be tested. Fake the API, feed in a fixture, assert the counts.

<?php

use App\Models\JevJudgement;
use App\Support\Jev\ThresholdReport;
use Illuminate\Support\Facades\Http;

it('does not raise true positives as the threshold rises', function (): void {
    $judgements = collect([
        (object) ['confidence' => 0.95, 'human_label' => 'spam'],
        (object) ['confidence' => 0.82, 'human_label' => 'spam'],
        (object) ['confidence' => 0.74, 'human_label' => 'ham'],
        (object) ['confidence' => 0.12, 'human_label' => 'ham'],
    ]);

    $rows = (new ThresholdReport($judgements, positive: 'spam'))->sweep(0.70, 0.90, 0.10);

    // Monotonicity: tp and fp can only fall as the threshold rises.
    expect(collect($rows)->pluck('tp')->all())->toBe([2, 2, 1])
        ->and(collect($rows)->pluck('fp')->all())->toBe([1, 0, 0]);
});

it('replays a sample without spending money', function (): void {
    Http::fake(['api.typesafe.ai/*' => Http::response([
        'model' => 'jev-1.14.0',
        'answers' => ['is_spam' => ['type' => 'noul', 'noul' => 0.93]],
        'usage' => ['input_tokens' => 412, 'output_tokens' => 11],
    ])]);

    $this->artisan('jev:tune is_spam --sample=1')->assertSuccessful();

    $judgement = JevJudgement::sole();

    expect($judgement->confidence)->toBe(0.93)
        ->and($judgement->model_version)->toBe('jev-1.14.0');
});

The monotonicity assertion is the one that catches real bugs. If raising a threshold ever raises tp or fp, a comparison operator is the wrong way round.

Gotchas and Edge Cases#

Tuning on the same rows you measure on. Pick the threshold from all 180 rows and then quote the precision from those same 180 rows and the figure is optimistic. Hold back a third, pick on two thirds, quote the held-back number.

A Noul of exactly 0.5. It is the most uncertain answer the model can give, and round() turns it into a yes. Keep it inside the human band and never derive bands from rounding.

Treating a Choice confidence like a Noul probability. A Choice confidence describes how concentrated the distribution is across the options you supplied; it says nothing about whether any option fits at all. If "none of these" is possible, you need a companion Noul, not a higher threshold.

One threshold for every question. The cut-off that gives 98% precision on a spam Noul will be wrong for a category Choice on the same state. Tune per question key and store the key on every judgement.

Low precision at every threshold. When no cut-off gives an acceptable number, the threshold is not the problem — the question is. Rewrite the false criteria from your own misclassifications and re-run the sample before shipping that question at all.

A sample with three positives. Precision computed from a handful of rows swings wildly between runs. If your rare class is under about twenty examples, go and label more before you believe the curve.

Wrapping Up#

Label 150 rows this week, run jev:tune once, and replace the 0.9 in your config with a number that has precision and recall figures in the comment above it. The run costs pennies, and the stored probabilities make every future re-tune free.

From here, the gate itself is the next thing to get right: screening with a Noul before expensive work is where a tuned threshold earns its money, and golden-dataset evals in CI is where you stop it drifting.

FAQ#

What is a good confidence threshold for Jev?

There is no universal figure, and the 0.9 that appears in most tutorials — mine included — is a placeholder rather than a finding. The right threshold is the point where the cost of acting on a wrong answer exceeds the cost of asking a human, which differs enormously between auto-tagging a ticket and auto-refunding an order. Derive it from a hundred or so labelled rows of your own data, and write the precision and recall figures next to it in config so the next person knows where it came from.

Is Jev's confidence calibrated?

TypeSafe trains Jev for calibrated probabilities, so across a group of answers returned at roughly 0.8, roughly 80% should be correct. Independent write-ups broadly support that on familiar data while reporting noticeably larger calibration error on data the model has not seen before. Calibration is a property of groups of predictions, so it never promises that any individual answer at 0.84 is right — which is exactly why you still need a threshold of your own.

How many labelled examples do I need to pick a threshold?

Between 100 and 200 rows is enough for a usable precision/recall curve on a binary question, provided both classes are well represented. The real constraint is the rare class rather than the total: with fewer than about twenty positive examples, precision figures swing too much between runs to trust. If your positive rate is low, stratify the sample and keep the true prevalence recorded separately rather than drawing flat at random.

Should I use one threshold for every Jev question?

No. Thresholds belong to questions, not to models, because each question carries its own error asymmetry and its own wording quality. A spam Noul might reach 98% precision at 0.90 while a category Choice over the same state needs 0.75 to be useful at all. Store the question key on every judgement and tune each one separately.

How do I work out what Jev costs per 1,000 items?

Sum the input tokens across your replay run, divide by the number of items, and multiply by your rate — Jev bills input tokens and gives output tokens away free, so state size is the only lever you have. TypeSafe's own /v1/systemone response returns input_tokens and output_tokens, so you apply the rate yourself; calling Jev through OpenRouter's Decisions API returns a usage.cost field in dollars instead. Published rates sit around $0.042 per million input tokens, but measure your own sample before quoting anyone a budget.

Steven Richardson
Steven Richardson

CTO at Digitonic. Writing about Laravel, architecture, and the craft of leading software teams from the west coast of Scotland.