← Tous les articles

Getting reliable JSON from an LLM: schemas, validation and error handling in PHP

Markdown fences around the JSON, renamed fields, values outside the allowed list, truncated responses: why “answer in JSON” isn't enough, and the approach we use to plug a language model into an application without breaking everything else.

Getting reliable JSON from an LLM: schemas, validation and error handling in PHP

Key points

  • Enforce the structure with a schema (forced tool call or structured output) instead of describing it in the prompt.
  • Validate the response server-side like any external input: types, allowed values, lengths.
  • Plan for failure: one retry, a fallback that keeps the app working, and logs so you can measure.

Plugging a language model into an application rarely means showing free text. Most of the time you want data your code can use: classify an incoming message, pull fields out of an invoice, suggest tags for a post, detect the language and intent of a request. So you need a structured response, nearly always JSON. On our first projects we did what everyone does: write “reply only in JSON” in the prompt and call json_decode(). It works in the demo, then fails a few times a week in production, always at the worst moment. Here’s the approach we use now, shown in PHP on a concrete case: automatically triaging messages from a contact form.

Why “answer in JSON” isn’t enough

A language model generates text one token at a time. An instruction in the prompt makes valid JSON much more likely, but doesn’t guarantee it. The failures we’ve run into are always the same ones:

  • the JSON comes wrapped in Markdown code fences, or after a sentence like “Here’s the classification:”;
  • a field gets renamed (categorie instead of category), or an invented field shows up;
  • a value falls outside the expected list (“urgent” instead of “high”);
  • the response is cut off because the token limit was reached;
  • the model refuses or comments instead of answering.

Each case on its own is rare. Across thousands of calls, though, “rare” means “several times a week”. And if your code assumes the response is correct, one anomaly is enough to cause a fatal error or, worse, to silently store wrong data.

Enforce the structure with a schema

The first improvement is to stop describing the format in the prompt and declare it as a JSON schema instead. The major model APIs support this, either through a structured output mode or through tool use: you declare a tool whose parameters follow the schema, and force the model to call it. Here’s an example with Anthropic’s API, in dependency-free PHP:

<?php
// Classify a message sent through the contact form
$schema = [
    'type'       => 'object',
    'properties' => [
        'category' => ['type' => 'string', 'enum' => ['quote', 'support', 'billing', 'other']],
        'urgency'   => ['type' => 'string', 'enum' => ['low', 'normal', 'high']],
        'summary'    => ['type' => 'string', 'description' => 'One sentence, 200 characters max'],
    ],
    'required'             => ['category', 'urgency', 'summary'],
    'additionalProperties' => false,
];

$payload = [
    'model'       => getenv('LLM_MODEL'),
    'max_tokens'  => 512,
    'system'      => "You classify customer messages. Answer only through the provided tool.",
    'messages'    => [['role' => 'user', 'content' => $message]],
    'tools'       => [[
        'name'         => 'classify_message',
        'description'  => 'Records the message classification.',
        'input_schema' => $schema,
    ]],
    'tool_choice' => ['type' => 'tool', 'name' => 'classify_message'], // tool is mandatory
];

$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTPHEADER     => [
        'content-type: application/json',
        'x-api-key: ' . getenv('ANTHROPIC_API_KEY'),
        'anthropic-version: 2023-06-01',
    ],
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_THROW_ON_ERROR),
]);
$raw  = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

A few details matter. The schema restricts values with enum, which works far better than listing choices in the prompt. additionalProperties set to false says no other field is expected. tool_choice forces the tool, so the model can’t answer with a sentence. The explicit timeout stops a slow call from holding up the form.

With this in place, syntax problems all but disappear: the response arrives already decoded, as an object. The content still needs checking, though: depending on the provider and mode, not every schema constraint is enforced the same way, and a maximum length written in a description is only a hint.

Extract and validate it like any external input

Treat a model’s response exactly like data posted from a form: it isn’t trustworthy until it’s been validated. Start by checking the call itself and extracting the expected block:

if ($raw === false || $code !== 200) {
    throw new RuntimeException("Model call failed (HTTP $code)");
}
$response = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);

if (($response['stop_reason'] ?? '') === 'max_tokens') {
    throw new RuntimeException('Truncated response: max_tokens too low');
}

$data = null;
foreach ($response['content'] ?? [] as $block) {
    if ($block['type'] === 'tool_use' && $block['name'] === 'classify_message') {
        $data = $block['input']; // already decoded: a PHP array
    }
}

Checking stop_reason catches truncated responses that could otherwise slip through. Then validate the content against the same rules as the schema, in PHP:

function validate_classification(mixed $d): array
{
    if (!is_array($d)) {
        return ["response is not an object"];
    }
    $errors = [];
    $lists  = [
        'category' => ['quote', 'support', 'billing', 'other'],
        'urgency'   => ['low', 'normal', 'high'],
    ];
    foreach ($lists as $field => $values) {
        if (!in_array($d[$field] ?? null, $values, true)) {
            $errors[] = "$field invalid";
        }
    }
    $summary = $d['summary'] ?? null;
    if (!is_string($summary) || trim($summary) === '' || mb_strlen($summary) > 200) {
        $errors[] = 'summary missing or too long';
    }
    return $errors; // empty array = usable response
}

For a richer schema, a JSON Schema validation library (via Composer) lets you use the same schema file for the call and for validation. And remember the summary is still text derived from customer input: escape it on output and only ever store it through a prepared statement.

Plan for failure, test and monitor

Even with a schema and validation, you need to decide what happens when the response is unusable or the API doesn’t answer. Our rule: one more attempt, then a fallback that lets the application carry on normally.

function classify(string $message): array
{
    for ($attempt = 1; $attempt <= 2; $attempt++) {
        try {
            $data    = call_model($message); // call + extraction shown above
            $errors = validate_classification($data);
            if (!$errors) {
                return $data + ['auto' => true];
            }
            error_log("Invalid classification (attempt $attempt): " . implode(' ; ', $errors));
        } catch (Throwable $e) {
            error_log("Classification failed (attempt $attempt): " . $e->getMessage());
        }
    }
    // Fallback: the message is still handled, a human will triage it
    return ['category' => 'other', 'urgency' => 'normal', 'summary' => '', 'auto' => false];
}

The fallback is the most important part. Here, a message that couldn’t be classified isn’t lost: it lands in “other” with an auto flag set to false, and the team triages it by hand, as they did before automation. The AI improves the service when it works and never breaks it when it fails.

On the second attempt, send the detected errors back to the model (“urgency must be low, normal or high”): that’s often enough. Avoid multi-retry loops, which add cost for little gain.

Then measure. Before going live, build a set of around fifty real, anonymised messages with their expected classification, awkward ones included (empty message, another language, several requests, an email signature), and replay it whenever you change the prompt, the schema or the model. In production, log the invalid response rate, the fallback rate and call duration: a sudden change almost always signals a model update or a new kind of message. On our projects, that monitoring has more than once surfaced a problem before the client noticed.

FAQ

Do I still need to validate if the API offers strict structured outputs?

Yes. The structure is guaranteed, but not whether the content makes sense: a valid category can be the wrong one, and a summary can be empty or too long. Validation costs a few lines and protects the rest of your application.

Does this approach work with providers other than the one in the example?

Yes. The vocabulary changes (functions, tools, response format), but the principle is the same across the major providers: declare a JSON schema, force its use, then validate server-side. Keeping the call in a single function makes switching providers easier.

What if the model misclassifies some messages?

Add those cases to your test set, sharpen the value descriptions in the schema or add two or three examples to the prompt, then replay the whole set to make sure the fix doesn’t break anything else.

Want to bring AI into your website or application without making it fragile? We build dependable integrations: structured data, validation, fallbacks and production monitoring.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →