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, 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.
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:
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.
Result that lists every attempt, skip, token count, cost and guard action.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);
#[\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.
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:
{"0":"a"} passed as an array of strings, and {} and [] passed as each other. Validation now decodes to objects.minLength and still return it. Repaired data is now validated again.$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.
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.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.
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.