LLM
LLM is an abstract facade every provider adapter
(Monad\Clarity\Services\LLMAdapters\{OpenAI,Anthropic,DeepSeek,Gemini}) implements: one
complete() method translating a provider-agnostic request to that provider's wire
format and back. No global registry — construct the adapter you want directly, with its own
credentials and an HttpClient:
use Monad\Clarity\Services\HttpClient;
use Monad\Clarity\Services\LLMAdapters\Anthropic;
use Monad\Clarity\Services\LLM\LLMRequest;
$adapter = new Anthropic(apiKey: $apiKey, httpClient: new HttpClient());
$response = $adapter->complete(new LLMRequest(
model: 'claude-opus-5',
messages: [['role' => 'user', 'content' => 'Say hello in five words.']],
systemInstruction: 'You are terse.',
));
$response->content; // the model's text reply
LLMRequest fields
new LLMRequest(
string $model,
array $messages, // [['role' => 'user'|'assistant', 'content' => string, 'images' => [...]?], ...]
?string $systemInstruction = null, // a top-level field, never a message — providers disagree on system-role messages
float $temperature = 1.0, // 0.0–2.0
int $maxOutputTokens = 1024,
int $timeoutSeconds = 30,
?array $responseSchema = null, // a JSON Schema the output must conform to; null = plain text
)
Validated at construction — a malformed request throws before any network round trip.
LLMResponse fields
$response->provider; // e.g. 'anthropic'
$response->model;
$response->content; // string, or array if $responseSchema was set and honoured
$response->usage; // ['inputTokens' => int, 'outputTokens' => int]
$response->providerRequestId; // ?string
$response->raw; // the provider's full decoded response body — an escape hatch
Structured JSON output
Set responseSchema to a JSON Schema and $response->content comes back as a
decoded array instead of a string. Each provider has its own mechanism behind that one
field — OpenAI and Gemini enforce the schema server-side, DeepSeek offers JSON mode without schema
enforcement, and Anthropic has two mechanisms, neither of which reaches every model.
use Monad\Clarity\Services\LLMAdapters\AnthropicStructuredOutput;
$adapter = new Anthropic(
apiKey: $apiKey,
httpClient: new HttpClient(),
structuredOutput: AnthropicStructuredOutput::NativeSchema,
);
Requires Clarity 1.8.0 or newer. ForcedTool is the default and the
behaviour of every earlier release: a synthetic tool whose schema is yours, with the answer read out
of the resulting tool call. It accepts any JSON Schema you can write, and the newest Anthropic models
refuse it. NativeSchema uses Anthropic's own JSON-schema response mode, which those
models require — but it is absent from several older ones and accepts a narrower range of schema:
no recursion, no numeric or string bounds, and additionalProperties: false on every
object. A rejected schema comes back as a precise error naming the offending keyword.
A model id does not say which mechanism it supports, so the choice is yours to make once, per adapter, rather than something the framework can guess per request. The default was left unchanged so existing code keeps the behaviour it already had.
Workspace-scoped Anthropic keys
$adapter = new Anthropic(
apiKey: $apiKey,
httpClient: new HttpClient(),
workspaceId: 'wrkspc_01abc',
);
Requires Clarity 1.8.0 or newer. Only needed if your API key is not itself scoped to a workspace — Anthropic refuses such a key outright unless the request names one. Leave it unset otherwise and no header is sent.
Provider notes
-
OpenAI — the output cap is sent as
max_completion_tokens. Requires Clarity 1.8.0; earlier releases sentmax_tokens, which every current OpenAI chat model rejects, so the adapter could reach only older models. -
Anthropic —
temperatureis sent only when you move it off the default of1.0. Current Anthropic models refuse a non-default value; if you set one, it is sent as asked and the model decides. -
Gemini — for
complete(), the model is part of the URL path and the key travels in anx-goog-api-keyheader, never in the URL. Requires Clarity 1.12.2; earlier releases sent it as a?key=query parameter, where access logs and any error page that prints a request URI recorded it. Assistant turns are translated to Gemini'smodelrole so your message list stays provider-neutral. AresponseSchemamay containadditionalProperties, which OpenAI's strict mode requires, so one schema serves both. Requires Clarity 1.8.2; earlier releases sent the schema in a form Gemini refuses whenever it contains that keyword. - DeepSeek — structured output is best-effort: DeepSeek guarantees valid JSON but does not enforce the schema server-side, so the adapter also states the schema in the system instruction.
Ask a model about an image
use Monad\Clarity\Services\LLM\LLMRequest;
use Monad\Clarity\Services\LLM\ReferenceImage;
$response = $adapter->complete(new LLMRequest(
model: 'gemini-3.5-flash',
messages: [[
'role' => 'user',
'content' => 'Describe this image in one sentence.',
'images' => [new ReferenceImage('image/jpeg', file_get_contents('lighthouse-0.jpeg'))],
]],
));
$response->content; // a one-sentence description
Requires Clarity 1.10.0 or newer. A user message may carry an images key —
a list of ReferenceImage, the raw bytes and media type of each image. Every adapter sends
them in its provider's own format, images before the text. content stays a string, and a
message without images is sent exactly as before.
- User messages only. No provider accepts images from the assistant, so an image on an assistant message throws at construction.
- Use a vision model. On DeepSeek that is
deepseek-flash; a model without vision is refused by its provider with an error naming the problem. - Limits are the provider's. How many images, how large, and which types each provider accepts differ by provider and model; Clarity passes them through rather than guessing.
- A custom adapter written before 1.10.0 ignores
images. If you wrote your ownLLMsubclass, add image support to it before sending images through it.
Check specific objects for changes
$checklist = ['lighthouse', 'sky']; // only these objects are examined
$schema = [
'type' => 'object',
'properties' => array_fill_keys($checklist, [
'type' => 'object',
'properties' => [
'changed' => ['type' => 'boolean'],
'before' => ['type' => 'string'],
'after' => ['type' => 'string'],
],
'required' => ['changed', 'before', 'after'],
'additionalProperties' => false,
]),
'required' => $checklist,
'additionalProperties' => false,
];
$response = $adapter->complete(new LLMRequest(
model: 'gemini-3.5-flash',
messages: [[
'role' => 'user',
'content' => 'Image 1 is BEFORE, image 2 is AFTER. Compare only these objects: '
. implode(', ', $checklist) . '. Ignore everything else.',
'images' => [new ReferenceImage('image/jpeg', $before), new ReferenceImage('image/jpeg', $after)],
]],
responseSchema: $schema,
));
$response->content['lighthouse']['changed']; // true
$response->content['lighthouse']['after']; // e.g. "a green lighthouse"
To ask whether particular objects changed between two images — rather than what changed anywhere —
build the responseSchema from your own list. Listing every object under
required forces an answer for each, by name; additionalProperties: false
keeps anything outside the list out of the answer. Add whatever properties you need to compare, such as
position or size, and the schema enforces them too. Clarity has no helper for this on purpose: the
prompt and the schema are yours to shape.
Measured on 9 real before/after edits and 4 checklist items (36 judgments), each provider judged all 36
correctly in its recommended mode: gemini-3.5-flash, gpt-5.6-sol,
claude-opus-5 with NativeSchema, and deepseek-flash. The smaller
gpt-4o-mini scored 33 of 36. A different kind of image, or subtler changes, deserves its own
measurement before you rely on it. A schema with additionalProperties needs Clarity 1.8.2 or
newer on Gemini.
-
On Anthropic, use
NativeSchemafor image requests with a schema. In the defaultForcedToolmode,claude-opus-5answered image requests in the wrong shape — every time it was measured — whileNativeSchemakept the shape every time. Construct the adapter withstructuredOutput: AnthropicStructuredOutput::NativeSchema. -
Name checklist items like identifiers — letters, digits,
_,.and-, such asteacup_color. They become schema keys, and Anthropic'sForcedToolmode refuses a key containing a space.
Generate an image with Gemini
use Monad\Clarity\Services\HttpClient;
use Monad\Clarity\Services\LLMAdapters\Gemini;
use Monad\Clarity\Services\LLM\ImageRequest;
$gemini = new Gemini(apiKey: $apiKey, httpClient: new HttpClient());
$response = $gemini->generateImage(new ImageRequest(
model: 'gemini-nano-banana-2.1',
prompt: 'A small red lighthouse on a rock at dusk, flat illustration',
aspectRatio: '1:1',
imageSize: '1K',
));
foreach ($response->images as $i => $image) {
file_put_contents("lighthouse-{$i}." . explode('/', $image->mimeType)[1], $image->bytes);
}
Requires Clarity 1.9.0 or newer. generateImage() is a method on the
Gemini adapter only, not part of the LLM contract — no other adapter has
it. It speaks Google's Interactions API and sends your key in an x-goog-api-key header,
never in the URL. You pass and receive raw bytes, never base64.
Edit an image
use Monad\Clarity\Services\LLM\ReferenceImage;
$response = $gemini->generateImage(new ImageRequest(
model: 'gemini-nano-banana-2.1',
prompt: 'Make the lighthouse green; keep everything else the same',
referenceImages: [new ReferenceImage('image/jpeg', file_get_contents('lighthouse-0.jpeg'))],
));
Pass one or more reference images to edit them, or to generate from them. How many a model accepts
is Google's limit, not Clarity's. The response holds only the new image: your reference images are
never returned in $response->images, so keep the original's bytes if you still need it.
ImageRequest fields
new ImageRequest(
string $model,
string $prompt,
array $referenceImages = [], // list<ReferenceImage>; empty for text-to-image
?string $aspectRatio = null, // e.g. '16:9'; null lets the model choose
?string $imageSize = null, // e.g. '1K', '2K', '4K'; null takes Google's default
?string $outputMimeType = null, // null takes Google's default, which is JPEG
int $timeoutSeconds = 120, // higher than LLMRequest's 30 — a 4K render can take over a minute
)
Validated at construction for shape only: an aspect ratio must be width:height in whole
numbers, and media types must be image/…. Which ratios, sizes and types a model accepts
changes with each model Google ships, so Clarity passes them through and Google's own error is the
answer.
ImageResponse fields
$response->images; // list<GeneratedImage>, never empty — each has ->mimeType and decoded ->bytes
$response->text; // ?string — any prose the model returned alongside the images
$response->usage; // ['inputTokens' => int, 'outputTokens' => int]
$response->providerRequestId; // null — see below
$response->raw; // Google's full decoded response, base64 image data included
-
Every image is returned, not only the last, in the order the model produced them.
$image->mimeTypeis what Google reported, so name files from it rather than from what you asked for. -
Nothing is stored at Google. Every request is sent with
store: false, so Google keeps neither your prompt nor your reference images. Google then returns no interaction id, which is whyproviderRequestIdis null. -
A disallowed prompt may be softened rather than refused. Asked for graphic violence,
Nano Banana 2.1 returned a toned-down image instead of an error — once explaining the change in
$text, once with no text at all. An empty$textdoes not mean your prompt was followed as written. -
A reply without an image throws. An interaction that does not complete, or that
completes with only text, raises
LLMException— naming Google's reason, or quoting what the model said instead. -
Logging
$rawlogs a lot. Each image is several hundred kilobytes of base64, and a skipped reasoning step can carry over a megabyte more.
What's deliberately not here
No agents, tool orchestration, vector databases, memory, prompt pipelines, or automatic cross-provider retries — a thin, provider-agnostic request/response contract, not an agentic framework.
Next steps
- HttpClient — what every adapter sends requests over.