A client's invoice pipeline fell over on a Tuesday. The code had worked for months on 200KB receipt photos, then someone uploaded a 9 MiB scan of an A3 delivery note and the queue worker died on memory_limit. The culprit was one line: base64_encode(file_get_contents($path)). This is the Jev image upload Laravel developers write first, because it's the shape every quickstart shows — and it's the wrong transport for anything bigger than an avatar.
Choose multipart over base64 for every Jev image upload#
Jev's assets map takes each image one of two ways. Either data_base64 plus a format, or part — the name of a file part in a multipart/form-data request. If an asset has both, the API uses part.
Base64 is the expensive one, and not only on the wire.
// The version that OOMs. Four copies of the same photo.
$raw = file_get_contents($path); // 9 MiB string
$encoded = base64_encode($raw); // 12 MiB string
$body = json_encode([ // ~12 MiB more
'assets' => ['photo' => ['type' => 'image', 'format' => 'jpg', 'data_base64' => $encoded]],
// ...
]);
// Guzzle then holds the serialised body too: ~12 MiB again.
Base64 encodes three bytes as four characters, so the encoded string is about a third larger than the file. That growth counts against the API's 32 MiB request body limit. The memory arithmetic is worse than the wire arithmetic: the raw bytes, the encoded string, the encoded JSON and the request body all exist at once, so a 9 MiB photo can reach roughly 45 MiB resident. On a worker with memory_limit=128M that is one upload away from a fatal error, and it fails at the exact moment someone sends you a big file rather than during testing.
A multipart part sends the bytes as they are. With a stream it never materialises the file in PHP memory at all.
Build the multipart body Jev expects#
The shape is specific and the API returns a flat 400 when you get it wrong. The JSON request is the first part, named request, with content type application/json. Each image follows as its own file part, and the asset's part field names it.
Here's the raw curl equivalent, so you can see what you are aiming at before Laravel abstracts it:
curl https://api.typesafe.ai/v1/systemone \
-H "Authorization: Bearer $TYPESAFE_API_KEY" \
-H "TypeSafe-Danger-Zone-Images: true" \
-F 'request={"model":"jev-1.14.0","state":{"invoice":"a3f1c2e8-inv"},"assets":{"a3f1c2e8-inv":{"type":"image","part":"invoice-scan"}},"questions":{"is_invoice":{"type":"noul","instructions":"Is `invoice` an invoice?"}}};type=application/json' \
-F 'invoice-scan=@delivery-note.jpg;type=image/jpeg'
Four rules govern the parts. request is reserved for the JSON body and must come first. Every image part name is unique and non-empty. Each file part belongs to exactly one asset — a part no asset names, two assets naming the same part, and an asset whose part is missing are all 400. And each image part carries image/png, image/jpeg, image/jpg, application/octet-stream, or no content type at all; anything else is rejected.
Attach the JSON and the image with Laravel's HTTP client#
Http::attach() takes a name, the contents, an optional filename and an optional headers array. That fourth argument is what lets you set application/json on the JSON part, which is the piece most people miss. Attachments are sent in the order you call attach(), so calling it for request first satisfies the ordering rule for free.
<?php
declare(strict_types=1);
namespace App\Support\Jev;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
final readonly class JevImageClient
{
public function __construct(
private string $apiKey,
// Pin the version. Images are dreamer-ready and the format can move.
private string $model = 'jev-1.14.0',
) {}
/**
* @param resource|string $image Raw bytes or, better, a stream.
* @param array<string, array<string, mixed>> $questions
* @return array<string, mixed>
*/
public function ask(mixed $image, array $questions, string $field = 'subject'): array
{
// A fresh UUID per image, per request. See the references section below.
$reference = (string) Str::uuid();
$payload = [
'model' => $this->model,
'state' => [$field => $reference],
'assets' => [$reference => ['type' => 'image', 'part' => 'upload']],
'questions' => $questions,
];
return $this->request()
// Part one: the JSON body, explicitly typed as JSON.
->attach('request', json_encode($payload, JSON_THROW_ON_ERROR), headers: ['Content-Type' => 'application/json'])
// Part two: the bytes. A stream resource is never copied into memory.
->attach('upload', $image, 'upload.jpg', ['Content-Type' => 'image/jpeg'])
->post('/systemone')
->throw()
->json('answers');
}
private function request(): PendingRequest
{
return Http::baseUrl('https://api.typesafe.ai/v1')
->withToken($this->apiKey)
->withHeaders(['TypeSafe-Danger-Zone-Images' => 'true'])
->timeout(60)
->connectTimeout(10);
}
}
Note what is not there: no second argument to post(). attach() switches the body format to multipart, and anything you then pass as post($url, $array) is merged in as additional multipart fields — your carefully built JSON becomes a pile of form fields and the API rejects it. Pass the payload through attach() or not at all. For the same reason, don't chain asForm() or asJson() after attach(); they overwrite the body format attach() just set.
Send a Jev image upload from a Laravel controller#
A request-scoped upload is the easy case: validate it, normalise it, send it. Validate before you spend an API call, because the API rejects images outside its limits rather than resizing them, and one bad image fails the whole request — there are no partial answers.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Support\Jev\JevImageClient;
use App\Support\Jev\PreparedImage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rules\File;
final class InvoiceCheckController
{
public function __invoke(Request $request, JevImageClient $jev): JsonResponse
{
$validated = $request->validate([
'scan' => [
'required',
File::image()
->types(['jpeg', 'jpg', 'png']) // The only formats Jev accepts.
->max('16mb') // Jev's per-file ceiling.
// Under 280px on either side is rejected outright.
->dimensions(fn ($d) => $d->minWidth(280)->minHeight(280)),
],
]);
// Re-encode to a baseline JPEG inside Jev's size window.
$prepared = PreparedImage::fromContents($validated['scan']->get());
$answers = $jev->ask($prepared->contents, [
'is_invoice' => [
'type' => 'noul',
'instructions' => 'Is `subject` a supplier invoice or delivery note?',
],
'legible' => [
'type' => 'score',
'instructions' => 'How legible is the text in `subject`?',
'criteria' => ['Unreadable', 'Partly readable', 'Fully legible'],
],
], field: 'subject');
return response()->json($answers);
}
}
PreparedImage is the small Intervention Image v3 wrapper from the Box question walkthrough — it auto-orients, scales the longest side down to 1568 pixels and re-encodes as a baseline JPEG. Skipping it is the most common reason a file that opens perfectly on your Mac comes back as a 413. The same upload hygiene applies whether the file arrives through a plain form or through direct-to-S3 temporary uploads.
Stream an image already on a disk#
Most real work happens in a queue, against a file already in object storage. This is where the transport choice stops being academic: Storage::readStream() hands you a resource, attach() accepts it, and Guzzle reads it in chunks. Peak memory stays flat whether the file is 200KB or 15 MiB.
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Document;
use App\Support\Jev\JevImageClient;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
final class ClassifyDocument implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public function __construct(public Document $document) {}
public function handle(JevImageClient $jev): void
{
// A stream, not a string: the bytes never land in PHP memory in one piece.
$stream = Storage::disk('s3')->readStream($this->document->path);
try {
$answers = $jev->ask($stream, [
'category' => [
'type' => 'choice',
'instructions' => 'What kind of document is `subject`?',
'criteria' => [
'invoice' => 'A supplier invoice requesting payment.',
'delivery_note' => 'A delivery or packing note, no amounts due.',
'receipt' => 'Proof of a payment already made.',
'other' => 'Anything else.',
],
],
]);
} finally {
// readStream hands you an open resource. Close it yourself.
if (is_resource($stream)) {
fclose($stream);
}
}
$this->document->update([
'category' => $answers['category']['choice'],
'category_confidence' => $answers['category']['confidence'],
]);
}
}
One caveat on streaming straight from a disk: you are sending the stored file untouched, so it has to already be inside Jev's limits and already upright. If your pipeline stores originals, prepare a derivative at upload time and stream that instead. The broader pattern — what to keep, what to derive, which disk to put it on — is the subject of the file storage and uploads guide.
Turn on images and pick a vision model#
Two things must be true or the request fails before the model ever sees your picture. The TypeSafe-Danger-Zone-Images: true header must be on every request carrying an image, and the model must be vision-capable. Images work on Jev 1.13 and 1.14; Box questions need 1.14.
Put the header in the client, as above, not at the call site. Missing it returns a 400 that says images are not enabled, which reads like a billing problem and sends people to the dashboard instead of their code. And pin the model string rather than using jev-latest — images are explicitly dreamer-ready, meaning the request format, the answers and the limits can change between releases.
Images are billed as input tokens at the same per-token rate as text, and usage.input_tokens in the response includes them. That makes a photo meaningfully more expensive than a paragraph, which is worth wiring into whatever you already use for tracking token spend.
Use UUID references so nothing collides#
The key you give an asset is a reference, and references are matched as plain text anywhere in the request's strings — in state, in a question's instructions, in its criteria. That's the feature: you write the reference in a sentence and the model receives the image there. It's also the trap.
// Don't. 'invoice' appears in your own instructions.
'assets' => ['invoice' => ['type' => 'image', 'part' => 'upload']],
'questions' => [
'check' => [
'type' => 'noul',
// The word "invoice" here gets replaced by the image. Twice.
'instructions' => 'Does this invoice show a VAT number?',
],
],
Every occurrence is substituted, and each substitution adds another copy of the image to what the model reads — against the same 32 MiB expanded-request limit. A filename is just as bad: receipt.jpg matches anywhere that string appears in your state. Use a fresh UUID per image per request and the collision is arithmetically impossible.
Three related rules. Every asset must be referenced somewhere, or the request is a 400 — an orphan image is an error, not a no-op. Object keys are never substituted, so a Choice option name stays text; put the reference in the option's description if you want a picture to define an option. And a reference that appears in several questions sends the image several times, so an image that several questions need belongs in the state once — the same economics that make batching questions into a single Jev call worth doing.
Test the multipart body with Http::fake#
Http::fake() records the parts, so you can assert the exact shape without a network call. For a multipart request, $request->data() returns the raw part list — an array of name / contents / headers / filename entries — and $request->hasFile() matches a part by name, contents and filename.
<?php
declare(strict_types=1);
use App\Support\Jev\JevImageClient;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
it('sends the JSON as the first part and the image as its own part', function () {
Http::fake([
'api.typesafe.ai/*' => Http::response([
'model' => 'jev-1.14.0',
'answers' => ['is_invoice' => ['type' => 'noul', 'noul' => 0.97]],
'usage' => ['input_tokens' => 1420, 'output_tokens' => 9],
]),
]);
(new JevImageClient('test-key'))->ask('raw-jpeg-bytes', [
'is_invoice' => ['type' => 'noul', 'instructions' => 'Is `subject` an invoice?'],
]);
Http::assertSent(function (Request $request) {
$parts = collect($request->data());
// Part order matters: `request` must be first.
expect($parts->first()['name'])->toBe('request');
$json = json_decode($parts->first()['contents'], true, flags: JSON_THROW_ON_ERROR);
$reference = array_key_first($json['assets']);
return $request->isMultipart()
&& $request->hasHeader('TypeSafe-Danger-Zone-Images', 'true')
// The asset points at a part that actually exists...
&& $json['assets'][$reference]['part'] === 'upload'
// ...and the reference is used somewhere, or the API 400s.
&& $json['state']['subject'] === $reference
&& $request->hasFile('upload', 'raw-jpeg-bytes', 'upload.jpg');
});
});
Assert the reference is used, not just that it exists. The orphan-asset 400 is the failure most likely to survive a refactor, because deleting a question is an easy change and nothing in your test suite notices the now-unreferenced image.
Gotchas and Edge Cases#
attach() silently drops empty contents. Laravel runs array_filter over the part it builds, so an empty string, '0', or an empty headers array disappears. Attach a zero-byte file and you get a part that was never sent and a 400 about a missing part. Guard against empty bytes before you attach.
EXIF orientation is not applied. The API strips all metadata and does not rotate. A photo that looks upright in Preview can reach the model sideways. Rotate the pixels themselves — Intervention Image v3 does this on read by default — and send the re-encoded bytes, not the original file.
The limits are a window, not a ceiling. Each side must be between 280 and 1568 pixels and total pixels between 78,400 and 2,458,624. Small images are rejected as hard as large ones, and scaleDown() only shrinks; an image under the minimum needs upscaling or padding separately.
Processing can make an image bigger. The 32 MiB all-images limit applies after the API re-encodes each file, which can inflate it. A request of comfortably small uploads can still go over.
Animated and progressive files. Animated PNGs are rejected outright. Progressive JPEGs are riskier than baseline — re-save as baseline. GIF, WebP and HEIC need converting to PNG or JPEG first.
Compression doesn't buy headroom. Gzipping the request doesn't raise the 32 MiB body limit; it's measured on the uncompressed body.
Wrapping Up#
Swap data_base64 for part, attach the JSON as its own part, and stream from the disk rather than reading files into strings. That's the whole change, and it turns image size from a cliff edge into a non-event for your queue workers.
From here, the two things worth adding are a confidence policy so uncertain answers get a human rather than a database write — see setting Jev confidence thresholds against a labelled sample — and, if you need to know where something is in the image rather than what it is, Box questions on Laravel image uploads.
FAQ#
How do I send an image to the TypeSafe Jev API from Laravel?
Build a multipart request with Laravel's HTTP client: attach the JSON body as a part named request with content type application/json, then attach the image as its own uniquely named file part, and set that part's name in the asset's part field. Every request carrying an image also needs the TypeSafe-Danger-Zone-Images: true header and a vision-capable Jev model. Pass raw bytes or, preferably, a stream resource from Storage::readStream().
Should I use base64 or multipart for Jev image assets?
Multipart, unless you genuinely cannot send it. Base64 makes each image about a third larger on the wire, and that growth counts against the 32 MiB request body limit. It is worse in memory, because the raw bytes, the encoded string, the encoded JSON and the serialised request body all exist at once — roughly four copies of the file. Multipart with a stream keeps peak memory flat regardless of image size.
How do I send multipart with a JSON part using Laravel's HTTP client?
Call Http::attach() with a fourth argument for headers: attach('request', json_encode($payload), headers: ['Content-Type' => 'application/json']). Attachments are sent in the order you call attach(), so call it for the JSON part first. Do not pass the payload as the second argument to post() and do not chain asForm() or asJson() afterwards — both will overwrite the multipart body that attach() set up.
What is the TypeSafe-Danger-Zone-Images header?
It is the opt-in header for TypeSafe's image and Box features, which are off by default because they are dreamer-ready rather than production-ready. Send TypeSafe-Danger-Zone-Images: true on every request that contains an image asset or a Box question. Without it the API returns a 400 saying images are not enabled, even when the rest of your payload is perfect. Set it once in your HTTP client rather than at each call site.
Why is my Jev asset placeholder not being replaced?
Most often the reference never appears in the payload, which the API treats as an error rather than ignoring: an asset referenced nowhere in state, instructions or criteria returns a 400. The other common cause is putting the reference in an object key — a Choice option name or a question ID — which is never substituted. If instead the image appears in unexpected places, your reference is a word like invoice that also occurs in your own prose; use a fresh UUID per image per request.