Validate LLM JSON Output in Laravel: Rules, a Retry and Typed Results
An LLM returns text. Your application needs a category from a fixed list, a priority and a number between 0 and 1. The gap between those two is where AI features break: the model answers "billing" in a Markdown code fence, or "Billing", or "refund", or adds a friendly sentence before the JSON, or returns a confidence of "high". If your code does json_decode() and trusts the result, each of those becomes a bug in a screen or a database.
This guide treats model output as what it is, untrusted input, and builds a small classifier that parses it defensively, validates it with Laravel's validator, retries once with the error message, and returns a typed object. The example classifies a support ticket, but the pattern fits any task where the model must return a structured answer.
What this article is, and is not
The code was run on Laravel 13 with PHP 8.3: 8 automated tests (16 assertions) with a faked HTTP layer, plus runs against a small fake model server for four scenarios. No real model provider was involved, so I make no claims about any provider's accuracy, pricing or request format. The client below is a stand-in that sends a prompt and returns text, and you will replace it with your provider's SDK or HTTP API. Many providers offer features that make structured output more reliable, such as JSON modes or schema-constrained replies. That comes from their documentation and I did not test it here. Even with those features, validating on your side is still worth doing.
What goes wrong
- Wrapping: the JSON arrives inside a Markdown code fence, or with a sentence before and after it.
- Wrong value: a category that is not on your list ("refund" instead of "billing").
- Wrong type: a confidence of
"high" or 7.
- Extra fields: keys you never asked for. In the worst case the text of an instruction hidden in the input.
- Truncated or malformed JSON: a missing closing brace.
- No JSON at all: a refusal or an apology.
The approach
prompt -> model -> raw text
1. find the JSON object in the text (fence, prose around it)
2. decode it (malformed? note the reason)
3. validate it with Laravel rules (wrong value or type? note the reasons)
4. on failure: ask once more, quoting the reasons
5. on success: build a typed object, keeping only validated keys
6. still failing: throw a specific exception, and log what was rejected
Step 1: Define the shape you accept
A small immutable class is the contract between the model and the rest of your code. Nothing downstream ever sees an array of unknown shape.
app/Services/Llm/TicketClassification.php
<?php
namespace App\Services\Llm;
final class TicketClassification
{
public function __construct(
public readonly string $category,
public readonly string $priority,
public readonly float $confidence,
public readonly string $summary,
) {}
}
app/Exceptions/InvalidModelOutput.php
<?php
namespace App\Exceptions;
use RuntimeException;
class InvalidModelOutput extends RuntimeException {}
Step 2: A thin client
One class talks to the model. It calls ->throw() so that an HTTP error is an error, not "invalid output". A 500 from the provider is a different problem from a bad answer, and it should reach your normal error handling and retries.
app/Services/Llm/LlmClient.php
<?php
namespace App\Services\Llm;
use Illuminate\Support\Facades\Http;
/** Stand-in for whatever model API you use: send a prompt, get text back. */
class LlmClient
{
public function complete(string $prompt): string
{
$response = Http::baseUrl(rtrim(config('services.llm.base_url'), '/'))
->acceptJson()
->connectTimeout(3)
->timeout(20)
->post('/complete', ['prompt' => $prompt])
->throw(); // an HTTP error is not "invalid output": let it surface
return (string) $response->json('text');
}
}
Step 3: Find the JSON, then decode it strictly
The decode() method in the classifier below does two things. It strips a Markdown fence if there is one, then takes the text from the first { to the last }, which removes a sentence before or after the object. It then decodes with JSON_THROW_ON_ERROR, so malformed JSON becomes an exception you handle, and it rejects anything that is not a JSON object, such as a list.
Step 4: Validate with Laravel rules
Model output is not an HTTP request, so a Form Request is the wrong tool. A Form Request validates an incoming request. Use the Validator directly on the decoded array, with the same rules you would write anywhere else. Two details matter:
- Enumerations come from one place. The prompt and the rule both read the same constants, so they cannot drift apart.
- Only validated keys come back.
$validator->validated() returns just the keys that have rules, so a field the model invented is dropped before it reaches your code.
Step 5: Retry once, with the reason
If the first reply fails, the classifier asks again and includes what was wrong ("The selected category is invalid"). That gives the model something concrete to correct. It makes one retry, not a loop: every retry costs money and time, and a model that fails twice on the same prompt usually needs a better prompt, not a third attempt.
app/Services/Llm/TicketClassifier.php
<?php
namespace App\Services\Llm;
use App\Exceptions\InvalidModelOutput;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use JsonException;
class TicketClassifier
{
public const CATEGORIES = ['billing', 'technical', 'sales', 'other'];
public const PRIORITIES = ['low', 'normal', 'high'];
private const MAX_ATTEMPTS = 2; // the first try, then one retry that includes the error
public function __construct(private LlmClient $llm) {}
public function classify(string $subject, string $body): TicketClassification
{
$prompt = $this->prompt($subject, $body);
$errors = [];
for ($attempt = 1; $attempt <= self::MAX_ATTEMPTS; $attempt++) {
$raw = $this->llm->complete($attempt === 1 ? $prompt : $this->retryPrompt($prompt, $errors));
try {
$data = $this->decode($raw);
} catch (JsonException $e) {
$errors = ['the reply was not a single valid JSON object'];
$this->logRejected($raw, $errors, $attempt);
continue;
}
$validator = Validator::make($data, [
'category' => ['required', 'string', 'in:'.implode(',', self::CATEGORIES)],
'priority' => ['required', 'string', 'in:'.implode(',', self::PRIORITIES)],
'confidence' => ['required', 'numeric', 'between:0,1'],
'summary' => ['required', 'string', 'max:300'],
]);
if ($validator->fails()) {
$errors = $validator->errors()->all();
$this->logRejected($raw, $errors, $attempt);
continue;
}
// Only the keys we validated come back, so extra fields from the model are dropped.
return new TicketClassification(...$validator->validated());
}
throw new InvalidModelOutput('The model did not return usable output: '.implode('; ', $errors));
}
/** @return array<string, mixed> */
private function decode(string $raw): array
{
$text = trim($raw);
// Models often wrap JSON in a markdown fence...
if (preg_match('/```(?:json)?\s*(.*?)\s*```/s', $text, $m)) {
$text = $m[1];
}
// ...or add a sentence before or after it. Take the outermost object.
$start = strpos($text, '{');
$end = strrpos($text, '}');
if ($start === false || $end === false || $end < $start) {
throw new JsonException('No JSON object found');
}
$data = json_decode(substr($text, $start, $end - $start + 1), true, 8, JSON_THROW_ON_ERROR);
if (! is_array($data) || array_is_list($data)) {
throw new JsonException('Not a JSON object');
}
return $data;
}
private function prompt(string $subject, string $body): string
{
return "Classify this support ticket. Reply with ONLY a JSON object with the keys "
.'"category" (one of: '.implode(', ', self::CATEGORIES).'), '
.'"priority" (one of: '.implode(', ', self::PRIORITIES).'), '
.'"confidence" (a number from 0 to 1) and "summary" (one sentence, under 300 characters).'
."\n\nSubject: {$subject}\n\nBody: {$body}";
}
/** @param array<int, string> $errors */
private function retryPrompt(string $prompt, array $errors): string
{
return $prompt."\n\nYour previous reply was rejected: ".rtrim(implode('; ', $errors), '.').'. Reply again with only the JSON object.';
}
/** @param array<int, string> $errors */
private function logRejected(string $raw, array $errors, int $attempt): void
{
// Keep enough to fix the prompt, but not whole replies that may echo personal data.
Log::warning('llm.output_rejected', [
'attempt' => $attempt,
'errors' => $errors,
'raw' => Str::limit($raw, 500),
]);
}
}
Step 6: Log what was rejected
The classifier logs every rejected reply with the reasons, the attempt number and a truncated copy of the raw text. That log is how you improve the prompt: when you see the same mistake ten times, fix the instruction. Truncating matters because a reply can echo the customer's message, so do not store whole replies by default. Check what personal data your logs may contain, and keep it out of them.
Using it
try {
$result = app(TicketClassifier::class)->classify($ticket->subject, $ticket->body);
$ticket->update([
'category' => $result->category,
'priority' => $result->priority,
]);
} catch (InvalidModelOutput $e) {
// Fall back: leave it unclassified and route it to a person.
$ticket->update(['needs_review' => true]);
}
Decide the fallback before you write the feature. A classification that fails should result in a person looking at the ticket, not in a guess.
Testing without calling a model
Faking the HTTP layer with a sequence of replies lets each test describe exactly what the "model" says. These eight tests cover the behaviour above:
| Test | What it protects against |
|---|
| Valid JSON returns a typed result after one call | The happy path regressing |
| JSON in a code fence with prose around it is extracted | The most common real-world wrapper |
| Extra fields are dropped | Unexpected keys reaching your code |
| An invalid category triggers one retry whose prompt includes the validation error | Retrying blindly |
Two bad replies throw InvalidModelOutput after exactly two calls | Endless retries |
| A confidence of 7, or of "high", is rejected | Out-of-range and wrong-type values |
An HTTP 500 raises the HTTP exception, not InvalidModelOutput | Hiding provider outages as bad answers |
| A rejected reply is logged, truncated to 500 characters | Logging whole replies |
function model(string ...$replies): void
{
Http::fake(['model.test/*' => Http::sequence(array_map(fn ($text) => Http::response(['text' => $text], 200), $replies))]);
}
it('retries once and sends the validation error back to the model', function () {
model(
'{"category":"refund","priority":"high","confidence":0.9,"summary":"Wants money back."}',
'{"category":"billing","priority":"high","confidence":0.9,"summary":"Wants money back."}',
);
expect(classify()->category)->toBe('billing');
Http::assertSentCount(2);
Http::assertSent(fn (Request $r) => str_contains($r['prompt'], 'previous reply was rejected')
&& str_contains($r['prompt'], 'selected category is invalid'));
});
I also ran the classifier against a small PHP script acting as a model server, with a different reply per scenario:
| What the stand-in model replied | Calls | Result |
|---|
| Valid JSON inside a code fence, with a sentence before it | 1 | Parsed into a typed object |
| An invalid category first, then valid JSON | 2 | The second request included "Your previous reply was rejected: The selected category is invalid", and the result was valid |
| "I am unable to help with that." both times | 2 | InvalidModelOutput |
| HTTP 500 | 1 | The HTTP exception, with no retry for bad output |
Validation is not safety
- A valid shape can still carry wrong or manipulated content. The model's summary may repeat instructions a customer planted in their message. Treat every string as data. Never run it, and escape it on output.
- Map enumerations to actions through your own code. Let "billing" select a queue. Do not let a model-supplied value decide what happens next without an allow-list.
- Use confidence carefully. A number the model reports about itself is not a probability. Use it as a hint to send low values to a person, not as a guarantee.
- Keep a human path for the cases the classifier cannot handle.
Common mistakes
- Calling
json_decode and trusting the result.
- Retrying in a loop. One retry with the error is plenty.
- Treating an HTTP error as invalid output (or the reverse), so outages look like bad prompts.
- Keeping prompt and rules in separate places, so a new category is added to one and not the other.
- Logging whole replies, which may contain personal data.
- No fallback, so a failed classification blocks the ticket.
Troubleshooting
| Symptom | Likely cause | What to try |
|---|
| Many rejections for "category is invalid" | The model uses synonyms or capitalisation | Tighten the prompt with an explicit list, and add an example in the exact format |
| "Not a single valid JSON object" very often | The model adds prose with braces in it, or truncates long output | Ask for less output, raise the output limit, or use your provider's structured-output option |
| Fine in tests, unreliable in production | The real model behaves differently from your fakes | Replay logged rejections as test cases |
| A deploy changed the enumeration and old rows break | Stored values no longer match the list | Version the list, or migrate old values |
| Costs rose | Retries are common | Look at the rejection log and fix the prompt |
Frequently asked questions
Can I use a Form Request?
A Form Request is built for an incoming HTTP request. For model output, call the Validator facade directly, as the classifier does.
Why a DTO and not an array?
A typed object makes the contract explicit and gives your editor and static analysis something to check. It also stops code further along from reaching for keys that may not exist.
Should I rely on the provider's JSON mode instead?
Use it if it exists, because it should reduce invalid replies. Still validate: the shape being valid JSON says nothing about whether the values are on your list or in range.
How many retries are sensible?
One. A second failure on the same prompt more often points to the prompt than to bad luck.
Does this work for lists of items?
Yes, with nested rules such as items.*.category. The classifier here rejects a top-level list on purpose, to keep the example small.
Where this fits
If you are adding AI features to a Laravel application and want them to behave when the model misbehaves, see AI-Powered Web Development and Laravel & PHP Development, or describe your project here. More guides on this topic are collected under Laravel + AI.