AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PlanWriter.php 9.0KB

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