trypost/tests/Unit/Services/Ai/AiImageClientTest.php
Paulo Castellano eb52b6b699
Fix OpenRouter via laravel/ai default provider (revises #216) (#220)
* Fix OpenRouter support by using laravel/ai default provider config.

PR #216 patched Lab::OpenRouter into every agent match, but laravel/ai
already resolves config('ai.default') — including openrouter — when agents
omit provider(). Those matches also forced unknown providers to Gemini and
BrandAnalyzerRunner checked a non-existent services.openrouter key.

Remove the duplicated provider() overrides, gate availability on
ai.providers.*.key, and document OPENROUTER_API_KEY.

Co-authored-by: Paulo Castellano <hello@paulocastellano.com>

* chore(deps): bump laravel/ai to v0.10.3 for native OpenRouter support

v0.5.1's OpenRouter driver only covered text/embeddings via the legacy
Prism gateway. v0.10.3 ships a native OpenRouter gateway with image,
audio (TTS/STT), and web search support, and drops prism-php/prism as
a dependency. ai-sdk-development skill docs refreshed via boost:update
to match the installed version.

* fix: honor AI_IMAGE_PROVIDER instead of hardcoding OpenAI's gpt-image-2

AiImageClient always passed model: 'gpt-image-2' to Image::of()->generate(),
so AI_IMAGE_PROVIDER silently did nothing for any provider other than
OpenAI — gemini/xai/openrouter would fail against an OpenAI-only model id
and quietly fall back to a stock photo. Usage recording was hardcoded to
provider 'openai' too, so credits were billed against the wrong model
whenever a different provider actually ran.

Drop the hardcoded model so generation falls through to the SDK's own
config('ai.default_for_images') + per-provider default model, and read
the actual provider/model back off the response's meta for usage
recording and source_meta instead of assuming OpenAI.

* refactor: extract AiImageClient into single-purpose steps, fix uncaught exception

generate() built the prompt, called the SDK, and unpacked the response all
in one block, with bytes extraction happening after the try/catch — so a
response with an empty images collection threw an uncaught RuntimeException
from ImageResponse::firstImage() instead of returning null as documented.

Split into cleanKeywords(), buildPrompt(), resolveBrandContext(), and
toResult(), and moved response unpacking inside the try block so any
malformed response is treated as a failure like everything else. Added a
regression test with an empty-images fake response.

* fix: drop hardcoded default_text_model, resolve model per provider

default_text_model was the only per-modality model override in ai.php —
image, audio, transcription, embeddings, and reranking all just pick a
provider and let it use its own default model. Text had a config-pinned
model on top, forced into every agent's model() and into every usage
log's model field regardless of which provider actually ran. Switching
AI_TEXT_PROVIDER (e.g. to openrouter) kept sending OpenAI's model id to
whichever provider ended up handling the request.

Removed model() from all six agents so laravel/ai resolves the model
from the active provider's own default (OpenAI's default is already
'gpt-5.4', so no behavior change there). Usage-recording call sites now
read the actual provider/model back off the response's meta instead of
assuming config('ai.default')/default_text_model. StreamPostContent
needed the then() callback since broadcast()'s StreamableAgentResponse
doesn't expose meta directly.

* refactor: drop AiConfiguration wrapper, use data_get() for array reads

AiConfiguration was a one-line static helper used by only two call
sites, with no laravel/ai equivalent to lean on (confirmed AiManager
and the Provider base class expose no isConfigured()/hasKey() check —
the package's model is try-then-catch, not pre-flight checks). Inlined
the filled(config(...)) check directly into HandleInertiaRequests and
BrandAnalyzerRunner instead of keeping a class around one line of logic.

Also swapped direct array-key reads for data_get() per project
convention across every file touched by the recent AI provider/model
fixes (agents' budget arrays, RunGenerateNode/StreamPostCreation's
humanizer merge, RegeneratePostMediaImage's baseContext/copy/rendered
access). Write/assignment sites (`$x['key'] = ...`) are left as-is —
data_get() only reads.

* feat: enhance AI configuration with new providers and options

Added strict types declaration and updated Azure OpenAI API version. Introduced new 'bedrock' provider configuration with AWS credentials and role assumptions. Enhanced existing providers with additional options, including image deployment for Azure and OpenAI, and updated URLs for Gemini and Ollama. Added support for an 'openai-compatible' driver to broaden integration capabilities.

* fix: remove trailing newline in AI configuration file

* feat: add support for OpenRouter and ElevenLabs API keys in configuration

Updated the production Docker Compose file and example environment file to include commented-out entries for OPENROUTER_API_KEY and ELEVENLABS_API_KEY. This enhances the configuration options for AI providers, allowing for easier integration of additional services.

* feat: allow per-provider model overrides for every AI modality

Adds a `models` array to each provider block, wired to env vars, so
self-hosted operators can pin a specific text/image/audio/transcription/
embeddings/reranking model instead of relying on the package's built-in
default for that provider. Only added for the modalities each provider
actually implements (verified against laravel/ai's Provider classes).

Azure is left untouched — it resolves models via deployment names
(AZURE_OPENAI_DEPLOYMENT etc.), not raw model strings, which was already
wired before this change.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-08-10 21:38:50 -03:00

220 lines
7.1 KiB
PHP

<?php
declare(strict_types=1);
use App\Enums\Workspace\ImageStyle;
use App\Services\Ai\AiImageClient;
use Illuminate\Support\Collection;
use Laravel\Ai\Image;
use Laravel\Ai\Prompts\ImagePrompt;
use Laravel\Ai\Responses\Data\Meta;
use Laravel\Ai\Responses\Data\Usage;
use Laravel\Ai\Responses\ImageResponse;
test('generate returns null when keywords are empty', function () {
Image::fake();
$client = new AiImageClient;
expect($client->generate([], ImageStyle::Cinematic))->toBeNull();
Image::assertNothingGenerated();
});
test('generate returns bytes plus the resolved provider and model when AI succeeds', function () {
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==');
Image::fake([base64_encode($bytes)]);
$client = new AiImageClient;
$result = $client->generate(['kitchen', 'morning'], ImageStyle::Illustration);
expect($result)
->not->toBeNull()
->and($result['bytes'])->toBe($bytes)
->and($result['provider'])->toBe('openai')
->and($result['model'])->toBe('gpt-image-2');
});
test('generate honours AI_IMAGE_PROVIDER instead of always using OpenAI', function () {
config()->set('ai.default_for_images', 'gemini');
Image::fake();
$client = new AiImageClient;
$result = $client->generate(['kitchen'], ImageStyle::Illustration);
expect($result)
->not->toBeNull()
->and($result['provider'])->toBe('gemini');
});
test('generate uses style-specific prompt prefix', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['mountain hiker'], ImageStyle::Cinematic);
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('Cinematic photograph')
&& $prompt->contains('mountain hiker'));
});
test('generate maps orientation to portrait', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, orientation: 'portrait');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->isPortrait());
});
test('generate maps orientation to landscape', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, orientation: 'landscape');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->isLandscape());
});
test('generate falls back to square for unknown orientation', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, orientation: 'whatever');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->isSquare());
});
test('generate appends Brazilian Portuguese instruction when language is pt-BR', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, language: 'pt-BR');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('Brazilian Portuguese'));
});
test('generate appends Spanish instruction when language is es', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, language: 'es');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('Spanish'));
});
test('generate appends French instruction when language is fr', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, language: 'fr');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('French'));
});
test('generate appends Ukrainian instruction when language is uk', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, language: 'uk');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('Ukrainian'));
});
test('generate defaults to English instruction when language is unsupported', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, language: 'sv');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('English'));
});
test('generate appends brand palette when workspace colours are provided', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(
['x'],
ImageStyle::Infographic,
brandColor: '#facc15',
backgroundColor: '#ffffff',
textColor: '#0f172a',
);
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('BRAND COLOR PALETTE')
&& $prompt->contains('golden yellow')
&& $prompt->contains('charts, bars')
&& $prompt->contains('off-white')
&& $prompt->contains('in-scene typography'));
});
test('generate omits brand palette when no workspace colours are set', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic);
Image::assertGenerated(fn (ImagePrompt $prompt) => ! $prompt->contains('BRAND COLOR PALETTE'));
});
test('generate includes only valid colours in the palette', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, brandColor: 'not-a-hex', backgroundColor: '#ffffff');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('BRAND COLOR PALETTE')
&& $prompt->contains('off-white')
&& ! $prompt->contains('Brand / primary accent'));
});
test('generate appends brand context when brandDescription is provided', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, brandDescription: 'a fitness coaching brand for busy professionals');
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('Brand context')
&& $prompt->contains('fitness coaching'));
});
test('generate truncates brand description longer than 200 chars', function () {
Image::fake();
$longDescription = str_repeat('lorem ipsum ', 50);
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, brandDescription: $longDescription);
Image::assertGenerated(fn (ImagePrompt $prompt) => $prompt->contains('Brand context')
&& $prompt->contains('…'));
});
test('generate omits brand context when brandDescription is empty or whitespace', function () {
Image::fake();
$client = new AiImageClient;
$client->generate(['x'], ImageStyle::Cinematic, brandDescription: ' ');
Image::assertGenerated(fn (ImagePrompt $prompt) => ! $prompt->contains('Brand context'));
});
test('generate returns null when SDK throws', function () {
Image::fake(fn () => throw new RuntimeException('boom'));
$client = new AiImageClient;
expect($client->generate(['x'], ImageStyle::Cinematic))->toBeNull();
});
test('generate returns null instead of throwing when the provider responds with no images', function () {
Image::fake(fn () => new ImageResponse(
new Collection,
new Usage,
new Meta('openai', 'gpt-image-2'),
));
$client = new AiImageClient;
expect($client->generate(['x'], ImageStyle::Cinematic))->toBeNull();
});