| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- <?php
-
- namespace App\StorePlan\Ai;
-
- use App\Ai\AiException;
- use App\Ai\AiManager;
- use App\Commerce\ChatActions;
- use App\Models\Store;
- use App\StorePlan\FeaturedProducts;
- use App\StorePlan\HeroImages;
- use App\StorePlan\PlanValidator;
- use Closure;
- use Illuminate\Support\Str;
- use Illuminate\Validation\ValidationException;
-
- /**
- * Turns AI answers into checked store plans.
- *
- * - generate(): design a whole store from the brand description.
- * - edit(): apply one small change asked for in plain words.
- *
- * Nothing leaves this class without passing PlanValidator. If an answer is rejected,
- * the AI gets one chance to correct it. After that the attempt fails and the store is left as it was.
- */
- class PlanWriter
- {
- public function __construct(
- private readonly AiManager $ai,
- private readonly PlanValidator $validator,
- ) {}
-
- /**
- * @throws AiException
- */
- public function generate(Store $store): PlanResult
- {
- return $this->askAndCheck(
- task: 'generate',
- system: PlanPrompt::generateSystem(),
- prompt: PlanPrompt::generatePrompt($store),
- build: fn (array $answer) => [$answer, null],
- store: $store,
- merchantWords: (string) $store->description,
- );
- }
-
- /**
- * @throws AiException
- */
- public function edit(Store $store, string $instruction): PlanResult
- {
- $plan = $store->plan;
-
- if (! is_array($plan)) {
- throw new AiException('This store has no design to edit yet.', AiException::SETUP);
- }
-
- return $this->askAndCheck(
- task: 'edit',
- system: PlanPrompt::editSystem(),
- prompt: PlanPrompt::editPrompt($plan, $instruction, PlanPrompt::catalogue($store)),
- build: fn (array $answer) => [
- PlanChanges::apply($plan, $answer),
- is_string($answer['reply'] ?? null) ? Str::limit(trim($answer['reply']), 300) : null,
- // Checked now, so a wrong product or code goes back to the AI to fix. Done only once confirmed.
- ChatActions::check($store, $answer['actions'] ?? null),
- ],
- store: $store,
- merchantWords: $instruction.' '.$store->description,
- );
- }
-
- /**
- * Ask the AI, check the answer, and retry once with the problems listed if it is rejected.
- *
- * @param Closure(array<string, mixed>): array{0: array<mixed>, 1: string|null, 2?: list<array{type: string, input: array<string, mixed>, summary: string}>} $build Turns the decoded answer into [plan, reply, actions].
- *
- * @throws AiException
- */
- private function askAndCheck(string $task, string $system, string $prompt, Closure $build, Store $store, string $merchantWords): PlanResult
- {
- $inputTokens = 0;
- $outputTokens = 0;
- $currentPrompt = $prompt;
- $errors = [];
-
- foreach ([1, 2] as $attempt) {
- $response = $this->ai->ask($task, $system, $currentPrompt);
- $inputTokens += $response->inputTokens;
- $outputTokens += $response->outputTokens;
-
- try {
- $built = $build(JsonAnswer::decode($response->text));
- [$plan, $reply] = $built;
-
- $clean = $this->validator->validate($plan);
- $this->assertProductsExist($store, $clean);
- $this->assertVideosWereGiven($store, $clean, $merchantWords);
-
- return new PlanResult(
- plan: $clean,
- provider: $response->provider,
- model: $response->model,
- inputTokens: $inputTokens,
- outputTokens: $outputTokens,
- reply: $reply,
- actions: $built[2] ?? [],
- );
- } catch (ValidationException $e) {
- $errors = collect($e->errors())
- ->map(fn (array $messages, string $field) => $field.': '.implode(' ', $messages))
- ->values()
- ->all();
- } catch (AiException $e) {
- if ($e->reason !== AiException::INVALID_RESULT) {
- throw $e;
- }
-
- $errors = [$e->getMessage()];
- }
-
- $currentPrompt = PlanPrompt::repairPrompt($prompt, $response->text, array_values($errors));
- }
-
- throw new AiException(
- 'The AI answer failed the store plan check twice: '.implode(' | ', array_slice($errors, 0, 5)),
- AiException::INVALID_RESULT,
- );
- }
-
- /**
- * A video section may only play a video the merchant gave: its address must appear in their words
- * (the chat message or the brand description). The AI never picks a video by itself.
- *
- * @param array<string, mixed> $plan
- *
- * @throws ValidationException
- */
- private function assertVideosWereGiven(Store $store, array $plan, string $merchantWords): void
- {
- $urls = fn (array $design) => array_values(array_filter(array_map(
- fn (mixed $section) => is_array($section) && ($section['type'] ?? null) === 'video' ? ($section['content']['videoUrl'] ?? null) : null,
- array_merge(...array_map(fn (mixed $page) => is_array($page) && is_array($page['sections'] ?? null) ? array_values($page['sections']) : [], array_values(is_array($design['pages'] ?? null) ? $design['pages'] : []))),
- ), 'is_string'));
-
- $new = array_diff($urls($plan), $urls(is_array($store->plan) ? $store->plan : []));
-
- foreach ($new as $url) {
- if (! str_contains($merchantWords, $url)) {
- throw ValidationException::withMessages([
- 'videoUrl' => "The video address [$url] was not given by the merchant. Only use a video address the merchant wrote; otherwise leave the video section out and ask for the link in \"reply\".",
- ]);
- }
- }
- }
-
- /**
- * Every collection name the plan's "shop by" sections use.
- *
- * @param array<mixed> $plan
- * @return list<string>
- */
- private static function collectionNames(array $plan): array
- {
- $names = [];
-
- foreach (is_array($plan['pages'] ?? null) ? $plan['pages'] : [] as $page) {
- foreach (is_array($page['sections'] ?? null) ? $page['sections'] : [] as $section) {
- if (($section['type'] ?? null) === 'shop_by' && is_array($section['content']['collections'] ?? null)) {
- foreach ($section['content']['collections'] as $name) {
- if (is_string($name)) {
- $names[$name] = $name;
- }
- }
- }
- }
- }
-
- return array_values($names);
- }
-
- /**
- * A featured product section may only point at one of this store's active products.
- * A made-up name is sent back to the AI as a problem to fix.
- *
- * @param array<string, mixed> $plan
- *
- * @throws ValidationException
- */
- private function assertProductsExist(Store $store, array $plan): void
- {
- $wanted = FeaturedProducts::slugs($plan);
- $unknown = $wanted === [] ? [] : array_diff($wanted, $store->products()->active()->whereIn('slug', $wanted)->pluck('slug')->all());
-
- if ($unknown !== []) {
- throw ValidationException::withMessages([
- 'productSlug' => 'These are not products of this store: '.implode(', ', $unknown).'. Use a web-address name from the product list, or null.',
- ]);
- }
-
- // A "shop by" section may only name the store's own collections. Names already in the design are left
- // alone: a deleted collection just stops showing.
- $newCollections = array_values(array_diff(self::collectionNames($plan), self::collectionNames(is_array($store->plan) ? $store->plan : [])));
- $unknownCollections = $newCollections === [] ? [] : array_values(array_diff(
- $newCollections,
- $store->collections()->whereIn('slug', $newCollections)->pluck('slug')->all(),
- ));
-
- if ($unknownCollections !== []) {
- throw ValidationException::withMessages([
- 'collections' => 'These are not collections of this store: '.implode(', ', $unknownCollections).'. Use a name from the list of collections, or an empty list.',
- ]);
- }
-
- // A hero photo must be one of the store's photos. Made-up names go back to the AI. Names already in
- // the design are left alone: a deleted photo only makes that hero fall back to product photos.
- $before = is_array($store->plan) ? HeroImages::refs($store->plan) : [];
- $images = array_values(array_diff(HeroImages::refs($plan), $before));
- $missing = $images === [] ? [] : HeroImages::unknown($store, $images);
-
- if ($missing !== []) {
- throw ValidationException::withMessages([
- 'image' => 'These are not photos of this store: '.implode(', ', $missing).'. Use a name from the list of photos, or null.',
- ]);
- }
- }
- }
|