AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

PlanWriter.php 5.9KB

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