# llm-json-php: validated JSON from chat endpoints in plain PHP

llm-json-php is a PHP library for getting structured JSON out of OpenRouter, OpenAI or any other chat completions endpoint. It is for PHP developers and WordPress plugin authors who run model calls unattended. The code is at [https://github.com/IndianOpinion/llm-json-php](https://github.com/IndianOpinion/llm-json-php), under the MIT licence, and v0.1.0 was released on 12 November 2026.

It was written from scratch. It is independent of any third-party plugin it integrates with.

## The problem

One HTTP request is not enough to get a structured answer from a model. The failures that matter are quiet ones. The requirements document for this repo lists the cases to guard against:

- Output that parses but is wrong. Under strict schema decoding, a model that types a straight double quote inside a text value can end the string there. The JSON is valid, every key is present, and the paragraph stops mid-sentence. The spill-over sometimes lands as an extra array item that starts in lower case.

- Text corrupted after the model, by a plugin that inserted typos and zero-width characters.

- Truncated bodies, sometimes cut mid-key.

- Credit exhaustion. One provider answers 402 on an empty balance. Another answers 429 with a quota code in the body, which looks like an ordinary rate limit.

- Fallback that is too eager: one transport blip on the primary model skipped its sibling and went straight to a costlier last-resort provider.

The library packages the work needed to handle these. One call goes in. A validated PHP array comes out, or a typed exception says what went wrong.

## What it does

- Sends a chat completions request and returns an array that matches your JSON schema.

- Walks an ordered chain of routes (a provider plus a model), with retries and jittered backoff on transport errors, 408, 425, 429 and 5xx.

- Puts routes that keep failing on cooldown, using a store you choose: memory, file, PSR-16 cache or WordPress transients.

- Detects credit exhaustion (402, or a quota pattern in a 429, 403 or 200 body), skips that account, and fires an event you can wire to an alert.

- Uses strict structured output where the provider and schema allow it, and falls back to JSON mode and then to prompt-only mode, validating locally in every case.

- Runs a guard on the parsed output, with rules G1 to G12 for truncation, missing fields, invisible and control characters, mid-sentence endings and wrong-script text.

- Returns a Result that lists every attempt, skip, token count, cost and guard action.

## How it works

The public API is Client, Request, Schema, Provider, Route, Chain and Options. Value objects are immutable, and with* methods return a copy.

A call validates its configuration first. Empty chains, plain http to a remote host, a guard path that is not in the schema and similar mistakes throw ConfigurationException before any request. Then, for each route, the client skips it if its account already failed in this call, if the provider is on a credit hold, or if the route is on cooldown. The last route is never skipped for a hold or cooldown. It builds the body, always with a token cap, and sends it.

Each response becomes exactly one outcome: success, truncated, malformed, schema violation, guard rejected, refusal, content filter, rate limited, credit exhausted, authentication failed, server error and a few more. The library reads the body, not only the status. Bad output, transport errors and rate limits retry on the same route. Bad keys, empty balances, refusals and redirects never retry.

State lives in the store under keys of the form <prefix>.<type>.<hash>, at most 51 characters. Separate keys hold consecutive failures, cooldown end, a remembered strict-to-JSON downgrade, the credit hold, a log throttle marker and a per-day count of chain failures. The key fingerprint is the first 12 hex characters of a SHA-256 of the API key, so no key material is stored.

The minimal call from the README:

$client = Client::create(Chain::of(Route::to(Provider::openRouter((string) getenv('OPENROUTER_API_KEY')), 'vendor/model-id')));
$schema = Schema::fromArray('answer', ['type' => 'object', 'properties' => ['answer' => ['type' => 'string']], 'required' => ['answer'], 'additionalProperties' => false]);
$data = $client->ask('demo', $schema, 'Answer in one sentence.', 'Why is the sky blue?');

For production you add more routes, a FileStore or WordPressTransientStore, and catch CreditExhaustedException and ChainExhaustedException. The guard is set per purpose, with JSON pointer paths:

$profile = GuardProfile::forSchema($schema)
->withQuoteInstruction()
->withSentenceEnd(['/paragraphs'], Action::Repair)
->withContinuationItems(['/paragraphs'], Action::Repair)
->withWordFloor('/paragraphs', 80);
$client = $client->withGuardProfile('summary', $profile);

## Guard rails

- A token cap is always sent. The default is 8192.

- Defaults: two attempts per route, a 90 second request timeout, a 300 second deadline per call, and no attempt starts with under 5 seconds left.

- Output is validated and guarded even in strict mode, because a router can send a request to a host that does not enforce the schema.

- The guard runs last, on schema-valid data. A repair that breaks the schema is treated as a retryable rejection. If a repair leaves too few words, the library regenerates once and keeps the longer result.

- API keys are redacted in error excerpts, exceptions and logs. Key parameters carry #[\SensitiveParameter].

- Options::withReliability(false) turns off retries, cooldowns and store traffic. The token cap, validation and guard stay on.

The guard is a quality check, not a security boundary. It does not sanitise HTML or defend against prompt injection. Escape the output where you use it.

## What review changed

The work was split into roles: a builder that saw only the spec, and an independent reviewer. The reviewer's comment on the build pull request lists what it fixed before the merge. Three examples:

- Type confusion in the validator. Output was decoded to associative arrays, so {"0":"a"} passed as an array of strings, and {} and [] passed as each other. Validation now decodes to objects.

- Repairs could break the schema. A sentence repair could leave a string under minLength and still return it. Repaired data is now validated again.

- The recursion limit tripped on valid data. A recursive tree deeper than 32 levels threw after a paid answer, because the limit counted every $ref along the data. It now counts only references followed without consuming data.

Ten regression tests for these and related fixes are in tests/Unit/ReviewFixesTest.php.

## Limits and what is next

- Chat completions only. No streaming, tools, embeddings or images.

- The validator covers the keywords strict structured outputs allow. Others such as format, if and oneOf are ignored.

- MemoryStore remembers nothing across web requests. The PSR-16 and transient stores have no atomic increment, so a cooldown can start one failure late.

- There are no built-in prices. You pass a price table, or rely on the cost the provider reports.

- Not yet: the OpenAI Responses API and per-language abbreviation lists.

Test status: this is v0.1.0. At review the suite had 295 tests with 2 live tests skipped, static analysis at level 8 was clean, and a forked eight-process run on FileStore gave an exact count. Those runs used mocks and stubs. CI has not yet run on GitHub, because the token lacked the scope to push the workflow. The library has not been run against a live site. There are no open issues.

## Install

The package is not on Packagist yet, so first add a Composer vcs repository entry for https://github.com/IndianOpinion/llm-json-php.

composer require indianopinion/llm-json-php

It needs PHP 8.1 or later, with ext-json. ext-curl is recommended, and without it the library uses PHP streams. Without Composer, copy the repository into your project and require bootstrap.php.

[All 47 utilities](https://indianopinion.org/blog/open-source/) · [llm-json-php on GitHub](https://github.com/IndianOpinion/llm-json-php)

Canonical: https://indianopinion.org/blog/open-source/llm-json-php/

AI disclosure: Every summary and comment here is written by AI and published automatically, without a person reviewing each article. We do no original reporting. How this works: https://indianopinion.org/ai-use-policy/
