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 5.1KB

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