A refund-approval integration I reviewed earlier this year sent $order->load('items', 'customer')->toArray() straight into Jev's state. Eleven kilobytes per decision, most of it foreign keys, created_at columns nobody asked about, and a deleted_at: null on every nested row. It worked. It also cost about four times what it needed to, and the noise was doing nothing good for the answer either.
State is the whole context Jev reads before it decides, and it is the only part of the request you pay for. This is how I build it now.
Map what Jev actually reads as state#
state is the content every question in the request is evaluated against. TypeSafe's State docs accept a plain string, a JSON object, or an array, and an object is the right default: each part gets a descriptive name, and a question's instructions can then point at a field by name in backticks. A string is fine when the decision really is about one piece of text and nothing else.
<?php
declare(strict_types=1);
// One state, three labelled parts. Each question in the request sees all of it.
$state = [
'ticket' => [
'subject' => 'Duplicate charge',
'messages' => [
['from' => 'customer', 'text' => 'I was charged twice for order A-104.'],
],
],
'order' => [
'reference' => 'A-104',
'charges' => [
['amount_gbp' => 49, 'status' => 'captured'],
['amount_gbp' => 49, 'status' => 'captured'],
],
],
'refund_policy' => 'Duplicate charges are eligible for a refund.',
];
Two structural rules are easy to trip over when the payload is generated rather than hand-written. state may nest at most 64 levels of objects and arrays, and numbers must be finite — so send order references, account numbers and anything else that is an identifier rather than a quantity as strings, not integers. Both are in TypeSafe's request rules, and both come back as a 400.
Work out which limit governs your request#
There are two numbers in circulation and they are not the same number. Jev 1.14's documented default is 64k tokens for the whole request — state plus every question combined — with a tighter 32k ceiling on the state plus any single question. Long context raises both to 262k, and on the direct API it is opt-in: you send TypeSafe-Danger-Zone-Long-Context: true with the request. TypeSafe is blunt about the trade in its models docs: long context "is slower and less accurate than staying within the default limits".
Call Jev through OpenRouter instead and the switch is made for you. OpenRouter's Jev guide puts the window at 262,144 tokens and turns long-context mode on automatically for requests carrying more than about 32,000 bytes of text, and for every request containing an image.
So the number that governs your design is 32k either way — 32k tokens for the state plus the longest question on the direct API, roughly 32,000 bytes of text before OpenRouter quietly switches modes. Over the line you get a 400 with max_tokens_exceeded on one route, and a slower, less accurate answer with no error at all on the other. The second failure is the one that hurts, because nothing in your logs says it happened.
I design to the byte count because it is the thing I can assert on cheaply in a test. A rough working rule for English prose is four bytes to the token, which puts 32,000 bytes comfortably inside 32k tokens and leaves room for the questions.
Count the cost of every field you send#
Jev charges per input token and gives output tokens away free — $0.042 per million input tokens on Jev 1.14 at the time of writing. That inverts the habit you brought from LLM work. You cannot trim this bill by asking for a shorter answer, because the answer is free. The only lever is sending less.
Where you read the cost depends on the route. The direct API's usage object carries input_tokens and output_tokens and nothing else, so you multiply by the rate yourself. Responses through OpenRouter add a usage.cost field in USD. Log whichever you have against the decision, the same way you would track token usage and cost in the Laravel AI SDK — a cost per decision is what turns "the state looks a bit big" into a number someone will act on.
Log::withContext(['decision' => 'refund_eligibility'])->info('jev.decision', [
'order_id' => $order->id,
'state_bytes' => strlen(json_encode($state, JSON_THROW_ON_ERROR)),
'input_tokens' => $answers->usage()['input_tokens'],
// Direct API bills input tokens only; output tokens are free.
'cost_usd' => $answers->usage()['input_tokens'] * 0.042 / 1_000_000,
]);
Build a JevState class instead of an inline array#
An inline array in a job is fine for one decision and unmaintainable at five, because there is nowhere to put the trimming. Give each decision a small class that builds its own state. It is the API Resource pattern, shaped for a judgment rather than a client: one place to decide what goes in, one place to assert a budget, and a return value you can snapshot in a test.
<?php
declare(strict_types=1);
namespace App\Support\Jev\States;
use App\Models\Order;
final readonly class OrderRefundState
{
/**
* @return array{order: array<string, mixed>, customer: array<string, mixed>, context: list<string>}
*/
public static function from(Order $order): array
{
return [
'order' => [
// Reference, not id: the decision needs something a human would quote.
'reference' => $order->reference,
'total_gbp' => (float) $order->total_gbp,
'status' => $order->status->label(),
'items' => $order->items
->map(fn ($item): string => "{$item->quantity} x {$item->name}")
->all(),
],
'customer' => [
'country' => $order->customer->country,
'account_age' => $order->customer->created_at->diffForHumans(syntax: true),
],
'context' => [
"The order shipped {$order->shipped_at?->diffForHumans()}.",
"This customer has opened {$order->customer->ticketsThisMonth()} tickets this month.",
],
];
}
}
Compare the two payloads for the same order and the shape of the problem is obvious. $order->load('items', 'customer')->toArray() on the fixture I used came to 11,284 bytes. OrderRefundState::from($order) came to 612. The builder is not clever — it just refuses to send things.
Strip the columns the decision doesn't need#
Work through the model's columns and ask what each one changes about the judgment. Most of them change nothing.
Primary keys and UUIDs go, unless the decision genuinely turns on identity. Foreign keys always go — Jev cannot join them to anything. created_at, updated_at and deleted_at go unless the question is about time, and when it is, send the elapsed time as a sentence rather than an ISO timestamp the model has to subtract. Internal status enums go out as their human labels, because status: 3 means nothing outside your codebase. Serialised blobs, settings JSON and cached counters go. So does anything already implied by another field: if you are sending total_gbp and the line items, you are sending the subtotal twice.
The same discipline applies on the way in. When the state is assembled from retrieved documents rather than a model, filter the passages before they land in it — that is the whole argument for gating RAG passages with Jev before they reach the LLM, and it applies just as well to the state you hand Jev itself.
Add the facts the row doesn't carry#
Trimming is only half the job. The other half is adding the two or three sentences a human reviewer would need and the database row does not contain.
A row knows shipped_at is a timestamp. A reviewer knows the order shipped three days ago and that this matters for the refund window. Pre-compute that into a plain sentence in context rather than making Jev infer it from a date and an implicit "today". The same goes for counts across relations — "this customer has opened four tickets this month" is one short string that replaces an entire eager-loaded relation.
This is where state design earns its keep. You are not compressing the record, you are writing the briefing note.
Enforce a state byte budget in tests and in production#
A trimmed state does not stay trimmed. Someone adds a field, the fixture grows, and nothing fails. Put the budget somewhere it can fail.
<?php
declare(strict_types=1);
use App\Models\Order;
use App\Support\Jev\States\OrderRefundState;
it('keeps refund state well inside the long-context threshold', function (): void {
$order = Order::factory()->has(OrderItem::factory()->count(40))->create();
$bytes = strlen(json_encode(OrderRefundState::from($order), JSON_THROW_ON_ERROR));
// 8KB of the ~32,000-byte threshold, leaving headroom for the questions.
expect($bytes)->toBeLessThan(8_192);
});
it('builds a stable refund state', function (): void {
$order = Order::factory()->refundable()->create();
// Snapshot: any new field in the state shows up as a reviewable diff.
expect(OrderRefundState::from($order))->toMatchSnapshot();
});
Build the fixture at the top of the realistic range, not the middle — forty line items, not three. The snapshot test is the one that pays off six months later, because it turns "someone added a column to the state" into a diff in a pull request rather than a quiet increase in the bill.
In production I log a warning rather than throwing. A state that crossed the line is still a decision worth making; it is just a decision that needs looking at — and if you are already storing probabilities per decision the way confidence-gated ticket triage does, the state size belongs in the same record.
$bytes = strlen(json_encode($state, JSON_THROW_ON_ERROR));
if ($bytes > 32_000) {
Log::warning('jev.state.oversized', ['decision' => 'refund_eligibility', 'bytes' => $bytes]);
}
Treat every image request as long context#
Images change the calculation completely. Every request containing an image runs in long-context mode — there is no version of an image request that stays in the fast, default path — and image tokens are billed at the same per-token rate as text and counted in usage.input_tokens.
That makes image state a deliberate decision rather than a convenience. Downscale before you encode: TypeSafe's images docs cap each side at 1568 pixels and reject anything under 280, and a full-size phone photo is pure waste at both ends. Rotate the pixels upright yourself, because the API strips EXIF and will not apply the orientation flag. Crop to the region you care about when you know where it is — which is exactly what a Box question gives you when you need to locate it first.
use Intervention\Image\Laravel\Facades\Image;
// Longest side 1568px, pixels rotated upright, baseline JPEG — then base64.
$prepared = Image::read($upload->getRealPath())
->orient()
->scaleDown(width: 1568, height: 1568)
->toJpeg(quality: 85);
$reference = (string) Str::uuid();
$payload = [
'model' => 'jev-latest',
'state' => ['photo' => $reference, 'claim' => $claim->summary],
'assets' => [
$reference => ['type' => 'image', 'format' => 'jpg', 'data_base64' => base64_encode((string) $prepared)],
],
'questions' => $questions->toPayload(),
];
And split the work. Questions that do not need to see the picture belong in a separate text-only request that stays in the default mode, rather than riding along in the slow one.
Trim first, then batch#
Once the state is small, batching is the obvious next move: several questions against one state is one round trip, and the marginal cost of question number seven is a handful of tokens. That is the argument for asking Jev every question in one request.
The order matters, though. Batching a bloated state does not save you anything — it just stops you paying for it more than once. And the 32k per-question ceiling covers the state plus the single longest question, so a fat state eats the budget your questions need. Trim, then batch. Doing it the other way round makes the waste harder to see, because the per-decision cost looks reasonable right up until you divide it by the number of questions.
Cache identical state#
The same state answered twice is pure waste. Hash the built state together with the question set and cache the answers for as long as the underlying record is stable.
$key = 'jev:refund:'.hash('xxh128', json_encode([$state, $questions->toPayload()], JSON_THROW_ON_ERROR));
$answers = Cache::remember($key, now()->addMinutes(10), fn (): Answers => $jev->ask($state, $questions));
Keep the TTL short and key on the state itself rather than the model id. Keying on order:123 means an order that changes mid-flight serves a stale decision; keying on the content means a changed order is simply a different key.
Gotchas and Edge Cases#
The two 32k figures are different units. 32k tokens is the direct API's per-question ceiling. ~32,000 bytes is the threshold at which OpenRouter switches you into long-context mode. They are close enough to design against as one rule and different enough that quoting the wrong one in a code comment will mislead whoever reads it next.
Silent degradation is the real risk, not the error. Going over the limit on the direct API without the header gives you a 400 you cannot miss. Going over on OpenRouter gives you a slower, less accurate answer and a 200. If you route through OpenRouter, the byte-budget log line above is the only warning you will get.
toArray() leaks more than you think. Appended accessors, casts that expand into arrays, and eager-loaded relations all come along. Hidden attributes are respected, but "hidden from the API" and "irrelevant to this decision" are different lists, and the model's $hidden was written for the first one.
Image state can breach a limit that text never would. A request body is capped at 32 MiB, and base64 inflates each file by about a third. Each place a reference appears adds another copy of the image to what the model reads, so an image used by three questions counts three times toward the expanded-request limit. Put a shared image in the state once and refer to it by name from each question.
Trimming can go too far. Strip the field a question depends on and confidence collapses rather than the request failing. When you cut aggressively, re-run a labelled sample before and after: a cheaper state that gets the answer wrong is not cheaper.
Wrapping Up#
Give every Jev decision its own state class, assert a byte budget on it in a Pest test, and log the size and cost of what you actually sent. That is an afternoon's work and it holds the line against the slow drift that turns a 600-byte state into an 11KB one over a year of small changes.
From here, batching every question into one request is the next multiplier once the state is small, and screening with a single cheap Noul first is how you avoid building the expensive state at all when the answer was never going to need it.
FAQ#
What is state in a Jev request?
State is the content you want Jev to evaluate, sent in the state field alongside your questions. It can be a plain string, a JSON object, or an array, and every question in the request is evaluated independently against the same state. Think of it as the material you would hand a reviewer before asking them to make a judgment.
What is Jev's context window?
It depends which route you call it through. Jev 1.14's documented defaults are 64k tokens for the whole request and 32k for the state plus any single question, rising to 262,144 tokens when long context is enabled. OpenRouter lists the window as 262,144 tokens because it enables long context for you when a request needs it.
What is long-context mode in Jev and when does it trigger?
Long context raises both the per-request and per-question limits to 262k tokens. On TypeSafe's API it is off by default and you turn it on per request with the TypeSafe-Danger-Zone-Long-Context: true header. Through OpenRouter it switches on automatically for requests over roughly 32,000 bytes of text and for every request containing an image. TypeSafe documents it as slower and less accurate than staying within the default limits, so it is worth avoiding rather than relying on.
Should I send my whole Eloquent model to Jev?
No. toArray() ships primary keys, foreign keys, timestamps, soft-delete columns and appended accessors, none of which help the decision and all of which are billed as input tokens. Build a small state class per decision that includes only the fields the judgment turns on, plus any pre-computed context the row does not carry.
Does sending images to Jev change how the request is processed?
Yes. Every request containing an image runs in long-context mode, so it is slower and less accurate than an equivalent text-only request, and image tokens are billed at the same rate as text. Downscale each image to at most 1568 pixels on its longest side before encoding, and move questions that do not need the picture into a separate text-only request.