| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
-
- namespace App\StorePlan\Ai;
-
- use App\Ai\AiException;
- use App\Ai\AiManager;
- use App\Models\Store;
- 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],
- );
- }
-
- /**
- * @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),
- build: fn (array $answer) => [
- PlanChanges::apply($plan, $answer),
- is_string($answer['reply'] ?? null) ? Str::limit(trim($answer['reply']), 300) : null,
- ],
- );
- }
-
- /**
- * 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} $build Turns the decoded answer into [plan, reply].
- *
- * @throws AiException
- */
- private function askAndCheck(string $task, string $system, string $prompt, Closure $build): 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 {
- [$plan, $reply] = $build(JsonAnswer::decode($response->text));
-
- return new PlanResult(
- plan: $this->validator->validate($plan),
- provider: $response->provider,
- model: $response->model,
- inputTokens: $inputTokens,
- outputTokens: $outputTokens,
- reply: $reply,
- );
- } 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,
- );
- }
- }
|