AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PlanWriter.php 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. <?php
  2. namespace App\StorePlan\Ai;
  3. use App\Ai\AiException;
  4. use App\Ai\AiManager;
  5. use App\Models\Store;
  6. use App\StorePlan\FeaturedProducts;
  7. use App\StorePlan\PlanValidator;
  8. use Closure;
  9. use Illuminate\Support\Str;
  10. use Illuminate\Validation\ValidationException;
  11. /**
  12. * Turns AI answers into checked store plans.
  13. *
  14. * - generate(): design a whole store from the brand description.
  15. * - edit(): apply one small change asked for in plain words.
  16. *
  17. * Nothing leaves this class without passing PlanValidator. If an answer is rejected,
  18. * the AI gets one chance to correct it. After that the attempt fails and the store is left as it was.
  19. */
  20. class PlanWriter
  21. {
  22. public function __construct(
  23. private readonly AiManager $ai,
  24. private readonly PlanValidator $validator,
  25. ) {}
  26. /**
  27. * @throws AiException
  28. */
  29. public function generate(Store $store): PlanResult
  30. {
  31. return $this->askAndCheck(
  32. task: 'generate',
  33. system: PlanPrompt::generateSystem(),
  34. prompt: PlanPrompt::generatePrompt($store),
  35. build: fn (array $answer) => [$answer, null],
  36. store: $store,
  37. );
  38. }
  39. /**
  40. * @throws AiException
  41. */
  42. public function edit(Store $store, string $instruction): PlanResult
  43. {
  44. $plan = $store->plan;
  45. if (! is_array($plan)) {
  46. throw new AiException('This store has no design to edit yet.', AiException::SETUP);
  47. }
  48. return $this->askAndCheck(
  49. task: 'edit',
  50. system: PlanPrompt::editSystem(),
  51. prompt: PlanPrompt::editPrompt($plan, $instruction, PlanPrompt::productList($store)),
  52. build: fn (array $answer) => [
  53. PlanChanges::apply($plan, $answer),
  54. is_string($answer['reply'] ?? null) ? Str::limit(trim($answer['reply']), 300) : null,
  55. ],
  56. store: $store,
  57. );
  58. }
  59. /**
  60. * Ask the AI, check the answer, and retry once with the problems listed if it is rejected.
  61. *
  62. * @param Closure(array<string, mixed>): array{0: array<mixed>, 1: string|null} $build Turns the decoded answer into [plan, reply].
  63. *
  64. * @throws AiException
  65. */
  66. private function askAndCheck(string $task, string $system, string $prompt, Closure $build, Store $store): PlanResult
  67. {
  68. $inputTokens = 0;
  69. $outputTokens = 0;
  70. $currentPrompt = $prompt;
  71. $errors = [];
  72. foreach ([1, 2] as $attempt) {
  73. $response = $this->ai->ask($task, $system, $currentPrompt);
  74. $inputTokens += $response->inputTokens;
  75. $outputTokens += $response->outputTokens;
  76. try {
  77. [$plan, $reply] = $build(JsonAnswer::decode($response->text));
  78. $clean = $this->validator->validate($plan);
  79. $this->assertProductsExist($store, $clean);
  80. return new PlanResult(
  81. plan: $clean,
  82. provider: $response->provider,
  83. model: $response->model,
  84. inputTokens: $inputTokens,
  85. outputTokens: $outputTokens,
  86. reply: $reply,
  87. );
  88. } catch (ValidationException $e) {
  89. $errors = collect($e->errors())
  90. ->map(fn (array $messages, string $field) => $field.': '.implode(' ', $messages))
  91. ->values()
  92. ->all();
  93. } catch (AiException $e) {
  94. if ($e->reason !== AiException::INVALID_RESULT) {
  95. throw $e;
  96. }
  97. $errors = [$e->getMessage()];
  98. }
  99. $currentPrompt = PlanPrompt::repairPrompt($prompt, $response->text, array_values($errors));
  100. }
  101. throw new AiException(
  102. 'The AI answer failed the store plan check twice: '.implode(' | ', array_slice($errors, 0, 5)),
  103. AiException::INVALID_RESULT,
  104. );
  105. }
  106. /**
  107. * A featured product section may only point at one of this store's active products.
  108. * A made-up name is sent back to the AI as a problem to fix.
  109. *
  110. * @param array<string, mixed> $plan
  111. *
  112. * @throws ValidationException
  113. */
  114. private function assertProductsExist(Store $store, array $plan): void
  115. {
  116. $wanted = FeaturedProducts::slugs($plan);
  117. if ($wanted === []) {
  118. return;
  119. }
  120. $unknown = array_diff($wanted, $store->products()->active()->whereIn('slug', $wanted)->pluck('slug')->all());
  121. if ($unknown !== []) {
  122. throw ValidationException::withMessages([
  123. 'productSlug' => 'These are not products of this store: '.implode(', ', $unknown).'. Use a web-address name from the product list, or null.',
  124. ]);
  125. }
  126. }
  127. }