AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RunStoreGeneration.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Jobs;
  3. use App\Ai\AiException;
  4. use App\Enums\GenerationStatus;
  5. use App\Enums\GenerationType;
  6. use App\Models\StoreGeneration;
  7. use App\StorePlan\Ai\PlanWriter;
  8. use Illuminate\Contracts\Queue\ShouldQueue;
  9. use Illuminate\Foundation\Queue\Queueable;
  10. use Throwable;
  11. /**
  12. * Runs one AI job in the background: a full store design or one chat edit.
  13. * The store's design only changes if the AI answer passes the store plan check.
  14. */
  15. class RunStoreGeneration implements ShouldQueue
  16. {
  17. use Queueable;
  18. /** AI calls cost money, so a failed job is never retried on its own. The merchant retries. */
  19. public int $tries = 1;
  20. /** Seconds. Must stay below DB_QUEUE_RETRY_AFTER in .env. */
  21. public int $timeout = 540;
  22. public function __construct(public int $generationId) {}
  23. public function handle(PlanWriter $writer): void
  24. {
  25. $generation = StoreGeneration::with('store')->find($this->generationId);
  26. if ($generation === null || $generation->status !== GenerationStatus::Queued) {
  27. return;
  28. }
  29. $generation->status = GenerationStatus::Running;
  30. $generation->started_at = now();
  31. $generation->save();
  32. try {
  33. $store = $generation->store;
  34. $result = $generation->type === GenerationType::Edit
  35. ? $writer->edit($store, (string) $generation->instruction)
  36. : $writer->generate($store);
  37. // Compare the design before and after, so the app (not the AI's reply) says whether anything changed.
  38. $changed = $result->plan != $store->plan;
  39. $store->plan = $result->plan;
  40. $store->save();
  41. $generation->status = GenerationStatus::Completed;
  42. $generation->reply = $result->reply;
  43. $generation->changed = $changed;
  44. $generation->provider = $result->provider;
  45. $generation->model = $result->model;
  46. $generation->input_tokens = $result->inputTokens;
  47. $generation->output_tokens = $result->outputTokens;
  48. $generation->finished_at = now();
  49. $generation->save();
  50. } catch (Throwable $e) {
  51. report($e);
  52. $generation->markFailed($e instanceof AiException
  53. ? $e->friendlyMessage()
  54. : 'Something went wrong. Please try again.');
  55. }
  56. }
  57. /**
  58. * Called when the job dies without reaching the catch block, for example on a timeout.
  59. */
  60. public function failed(?Throwable $e): void
  61. {
  62. StoreGeneration::query()
  63. ->whereKey($this->generationId)
  64. ->active()
  65. ->first()
  66. ?->markFailed('This took too long and was stopped. Please try again.');
  67. }
  68. }