Structured JSON output from Claude with the Anthropic PHP SDK
anthropic-sdkphpstructured-outputjson-schemaprompt-cachingguzzle
The plumb web app (a quoting and invoicing tool for a solo plumber) turns a dictated end-of-day
"debrief" and receipt photos into structured drafts with one Claude call each, using the official
PHP SDK (anthropic-ai/sdk, ^0.54 at the time). This records the request shape, the SDK traps,
and the design rules that make AI-drafted paperwork safe. Note: the calls were verified against
the SDK source and client construction only; no API key existed when this was built, so treat the
exact parameters as "compiles and matches the SDK", and re-check against current docs.
Setup traps
new Anthropic\Client()throws "No PSR-18 HTTP client" until an HTTP client is installed. Requireguzzlehttp/guzzlealongside the SDK.betas:andfallbacks:only exist on$client->beta->messages->create(), not on the regular messages service. When the bundled docs do not show a PHP form, grep the SDK source (vendor/anthropic-ai/sdk/src/Services/Beta/MessagesService.php) for the named arguments.- The PHP SDK uses camelCase keys:
mediaType,cacheControl,outputConfig,maxTokens. - No Composer on the machine? Download
composer.phar, verify its checksum, keep it gitignored intools/, and runphp tools/composer.phar.
Request shape
One helper, claude_json($system, $content, $schema), wraps every call:
- $client->beta->messages->create(...), non-streaming, maxTokens: 16000.
- outputConfig: ['effort' => 'medium', 'format' => ['type' => 'json_schema', 'schema' => ...]]
for guaranteed-parseable JSON instead of forcing a tool call.
- Server-side model fallback (fallbacks: 'default' with the matching beta header) so a busy
model does not fail the request.
- Schemas avoid nullable fields: use 0 and '' as "not present" values; it keeps schemas
simple and the PHP side free of null checks.
- Reference data that rarely changes (the pricebook: ids, names, aliases) goes in a cached
system block (cacheControl ephemeral), so repeated calls do not re-pay for it.
- Model rules that shaped this (Opus 5.5 era): forced tool_choice was not supported, thinking
could not be disabled, and the default effort is medium, so effort is set explicitly.
- Wrap failures in an exception type (AiError) whose message is safe to show the owner; never
surface raw API errors to an end user.
Design rules for AI-drafted business documents
- The model never sets prices. It sees item ids, names and aliases, never prices; it maps what was said to pricebook ids, and the server looks up prices. Anything that does not match is stored unpriced and flagged "Not in pricebook". A receipt read gets only the pricebook's parts.
- Save the input before the model call (the transcript), so a failed call loses nothing.
- Flag, don't guess. Missing sizes, unmatched items and unclear notes become flags; a document with open flags cannot be marked sent and is not visible at its public link. A flagged receipt never updates stored costs until confirmed.
- Test without a key: a smoke test that injects canned model replies exercises everything downstream of the model (the plumb suite had 59 checks on a throwaway database).
- Expect to tune prompts after the first real transcripts and receipts; canned replies prove plumbing, not prompt quality.
See also
- Calling Claude directly from a browser page
- Offline voice dictation with fuzzy matching against a catalog
- Designing a quoting and invoicing app for a solo tradesman