askAndCheck( task: 'generate', system: PlanPrompt::generateSystem(), prompt: PlanPrompt::generatePrompt($store), build: fn (array $answer) => [$answer, null], store: $store, ); } /** * @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, ); } /** * Ask the AI, check the answer, and retry once with the problems listed if it is rejected. * * @param Closure(array): array{0: array, 1: string|null, 2?: list, 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): 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); 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 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 $plan * * @throws ValidationException */ private function assertProductsExist(Store $store, array $plan): void { $wanted = FeaturedProducts::slugs($plan); if ($wanted === []) { return; } $unknown = 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.', ]); } } }