|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Jobs; |
| 4 | + |
| 5 | +use App\Enums\FeedbackType; |
| 6 | +use App\Jobs\Concerns\ResolvesAiProvider; |
| 7 | +use App\Models\Document; |
| 8 | +use Illuminate\Bus\Queueable; |
| 9 | +use Illuminate\Contracts\Queue\ShouldQueue; |
| 10 | +use Illuminate\Foundation\Bus\Dispatchable; |
| 11 | +use Illuminate\Queue\InteractsWithQueue; |
| 12 | +use Illuminate\Queue\Middleware\RateLimited; |
| 13 | +use Illuminate\Queue\SerializesModels; |
| 14 | +use Illuminate\Support\Facades\Cache; |
| 15 | +use Prism\Prism\Facades\Prism; |
| 16 | + |
| 17 | +class GenerateFeedbackJob implements ShouldQueue |
| 18 | +{ |
| 19 | + use Dispatchable, InteractsWithQueue, Queueable, ResolvesAiProvider, SerializesModels; |
| 20 | + |
| 21 | + public int $tries = 3; |
| 22 | + |
| 23 | + /** @var array<int, int> */ |
| 24 | + public array $backoff = [10, 30, 60]; |
| 25 | + |
| 26 | + public function __construct( |
| 27 | + public string $documentId, |
| 28 | + public FeedbackType $feedbackType, |
| 29 | + public string $cacheKey, |
| 30 | + ) { |
| 31 | + $this->afterCommit(); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @return array<int, object> |
| 36 | + */ |
| 37 | + public function middleware(): array |
| 38 | + { |
| 39 | + return [new RateLimited('llm:requests')]; |
| 40 | + } |
| 41 | + |
| 42 | + public function handle(): void |
| 43 | + { |
| 44 | + $document = Document::with(['currentVersion', 'project'])->findOrFail($this->documentId); |
| 45 | + $project = $document->project; |
| 46 | + |
| 47 | + $system = view('prompts.feedback.system')->render(); |
| 48 | + $prompt = view("prompts.feedback.{$this->feedbackType->value}", [ |
| 49 | + 'content' => $document->currentVersion->content_md, |
| 50 | + 'documentType' => strtolower($document->type->label()), |
| 51 | + ])->render(); |
| 52 | + |
| 53 | + $provider = $this->resolveProvider($project->preferred_provider ?? 'anthropic'); |
| 54 | + $model = $project->preferred_model ?? 'claude-sonnet-4-20250514'; |
| 55 | + |
| 56 | + $response = Prism::text() |
| 57 | + ->using($provider, $model) |
| 58 | + ->withMaxTokens(2000) |
| 59 | + ->withSystemPrompt($system) |
| 60 | + ->withPrompt($prompt) |
| 61 | + ->withClientOptions(['timeout' => 60]) |
| 62 | + ->asText(); |
| 63 | + |
| 64 | + Cache::put($this->cacheKey, [ |
| 65 | + 'feedback' => $response->text, |
| 66 | + 'type' => $this->feedbackType->value, |
| 67 | + 'generated_at' => now()->toIso8601String(), |
| 68 | + ], now()->addHour()); |
| 69 | + } |
| 70 | +} |
0 commit comments