AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

PlanWriter.php 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. merchantWords: (string) $store->description,
  40. );
  41. }
  42. /**
  43. * @throws AiException
  44. */
  45. /**
  46. * @param array{section: string, label: string, detail: string|null}|null $target The part the merchant selected in the preview.
  47. */
  48. public function edit(Store $store, string $instruction, ?array $target = null): PlanResult
  49. {
  50. $plan = $store->plan;
  51. if (! is_array($plan)) {
  52. throw new AiException('This store has no design to edit yet.', AiException::SETUP);
  53. }
  54. $selected = $target !== null ? PlanChanges::findSection($plan, $target['section']) : null;
  55. return $this->askAndCheck(
  56. task: 'edit',
  57. system: PlanPrompt::editSystem(),
  58. prompt: PlanPrompt::editPrompt($plan, $instruction, PlanPrompt::catalogue($store), $target !== null && $selected !== null ? [...$target, ...$selected] : null),
  59. build: fn (array $answer) => [
  60. // With a part selected, only changes to that part are kept, whatever the AI sent.
  61. PlanChanges::apply($plan, $selected !== null ? PlanChanges::limitTo($answer, $target['section']) : $answer),
  62. is_string($answer['reply'] ?? null) ? Str::limit(trim($answer['reply']), 300) : null,
  63. // Checked now, so a wrong product or code goes back to the AI to fix. Done only once confirmed.
  64. ChatActions::check($store, $answer['actions'] ?? null),
  65. ],
  66. store: $store,
  67. merchantWords: $instruction.' '.$store->description,
  68. );
  69. }
  70. /**
  71. * Ask the AI, check the answer, and retry once with the problems listed if it is rejected.
  72. *
  73. * @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].
  74. *
  75. * @throws AiException
  76. */
  77. private function askAndCheck(string $task, string $system, string $prompt, Closure $build, Store $store, string $merchantWords): PlanResult
  78. {
  79. $inputTokens = 0;
  80. $outputTokens = 0;
  81. $currentPrompt = $prompt;
  82. $errors = [];
  83. foreach ([1, 2] as $attempt) {
  84. $response = $this->ai->ask($task, $system, $currentPrompt);
  85. $inputTokens += $response->inputTokens;
  86. $outputTokens += $response->outputTokens;
  87. try {
  88. $built = $build(JsonAnswer::decode($response->text));
  89. [$plan, $reply] = $built;
  90. $clean = $this->validator->validate($plan);
  91. $this->assertProductsExist($store, $clean);
  92. $this->assertVideosWereGiven($store, $clean, $merchantWords);
  93. return new PlanResult(
  94. plan: $clean,
  95. provider: $response->provider,
  96. model: $response->model,
  97. inputTokens: $inputTokens,
  98. outputTokens: $outputTokens,
  99. reply: $reply,
  100. actions: $built[2] ?? [],
  101. );
  102. } catch (ValidationException $e) {
  103. $errors = collect($e->errors())
  104. ->map(fn (array $messages, string $field) => $field.': '.implode(' ', $messages))
  105. ->values()
  106. ->all();
  107. } catch (AiException $e) {
  108. if ($e->reason !== AiException::INVALID_RESULT) {
  109. throw $e;
  110. }
  111. $errors = [$e->getMessage()];
  112. }
  113. $currentPrompt = PlanPrompt::repairPrompt($prompt, $response->text, array_values($errors));
  114. }
  115. throw new AiException(
  116. 'The AI answer failed the store plan check twice: '.implode(' | ', array_slice($errors, 0, 5)),
  117. AiException::INVALID_RESULT,
  118. );
  119. }
  120. /**
  121. * A video section may only play a video the merchant gave: its address must appear in their words
  122. * (the chat message or the brand description). The AI never picks a video by itself.
  123. *
  124. * @param array<string, mixed> $plan
  125. *
  126. * @throws ValidationException
  127. */
  128. private function assertVideosWereGiven(Store $store, array $plan, string $merchantWords): void
  129. {
  130. $urls = fn (array $design) => array_values(array_filter(array_map(
  131. fn (mixed $section) => is_array($section) && ($section['type'] ?? null) === 'video' ? ($section['content']['videoUrl'] ?? null) : null,
  132. 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'] : []))),
  133. ), 'is_string'));
  134. $new = array_diff($urls($plan), $urls(is_array($store->plan) ? $store->plan : []));
  135. foreach ($new as $url) {
  136. if (! str_contains($merchantWords, $url)) {
  137. throw ValidationException::withMessages([
  138. '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\".",
  139. ]);
  140. }
  141. }
  142. }
  143. /**
  144. * Every collection name the plan's "shop by" sections use.
  145. *
  146. * @param array<mixed> $plan
  147. * @return list<string>
  148. */
  149. private static function collectionNames(array $plan): array
  150. {
  151. $names = [];
  152. foreach (is_array($plan['pages'] ?? null) ? $plan['pages'] : [] as $page) {
  153. foreach (is_array($page['sections'] ?? null) ? $page['sections'] : [] as $section) {
  154. if (($section['type'] ?? null) === 'shop_by' && is_array($section['content']['collections'] ?? null)) {
  155. foreach ($section['content']['collections'] as $name) {
  156. if (is_string($name)) {
  157. $names[$name] = $name;
  158. }
  159. }
  160. }
  161. }
  162. }
  163. return array_values($names);
  164. }
  165. /**
  166. * A featured product section may only point at one of this store's active products.
  167. * A made-up name is sent back to the AI as a problem to fix.
  168. *
  169. * @param array<string, mixed> $plan
  170. *
  171. * @throws ValidationException
  172. */
  173. private function assertProductsExist(Store $store, array $plan): void
  174. {
  175. $wanted = FeaturedProducts::slugs($plan);
  176. $unknown = $wanted === [] ? [] : array_diff($wanted, $store->products()->active()->whereIn('slug', $wanted)->pluck('slug')->all());
  177. if ($unknown !== []) {
  178. throw ValidationException::withMessages([
  179. 'productSlug' => 'These are not products of this store: '.implode(', ', $unknown).'. Use a web-address name from the product list, or null.',
  180. ]);
  181. }
  182. // A "shop by" section may only name the store's own collections. Names already in the design are left
  183. // alone: a deleted collection just stops showing.
  184. $newCollections = array_values(array_diff(self::collectionNames($plan), self::collectionNames(is_array($store->plan) ? $store->plan : [])));
  185. $unknownCollections = $newCollections === [] ? [] : array_values(array_diff(
  186. $newCollections,
  187. $store->collections()->whereIn('slug', $newCollections)->pluck('slug')->all(),
  188. ));
  189. if ($unknownCollections !== []) {
  190. throw ValidationException::withMessages([
  191. 'collections' => 'These are not collections of this store: '.implode(', ', $unknownCollections).'. Use a name from the list of collections, or an empty list.',
  192. ]);
  193. }
  194. // A hero photo must be one of the store's photos. Made-up names go back to the AI. Names already in
  195. // the design are left alone: a deleted photo only makes that hero fall back to product photos.
  196. $before = is_array($store->plan) ? HeroImages::refs($store->plan) : [];
  197. $images = array_values(array_diff(HeroImages::refs($plan), $before));
  198. $missing = $images === [] ? [] : HeroImages::unknown($store, $images);
  199. if ($missing !== []) {
  200. throw ValidationException::withMessages([
  201. 'image' => 'These are not photos of this store: '.implode(', ', $missing).'. Use a name from the list of photos, or null.',
  202. ]);
  203. }
  204. }
  205. }