|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Binaryk\LaravelRestify\Exceptions\Solutions; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\Cache; |
| 6 | +use OpenAI\Laravel\Facades\OpenAI; |
| 7 | +use Spatie\Backtrace\Backtrace; |
| 8 | +use Spatie\Backtrace\Frame; |
| 9 | +use Throwable; |
| 10 | + |
| 11 | +class OpenAiSolution |
| 12 | +{ |
| 13 | + protected string $solution; |
| 14 | + |
| 15 | + public function __construct(protected Throwable $throwable) |
| 16 | + { |
| 17 | + $this->solution = Cache::remember('restify-solution-'.sha1($this->throwable->getTraceAsString()), |
| 18 | + now()->addHour(), |
| 19 | + fn () => OpenAI::completions()->create([ |
| 20 | + 'model' => 'text-davinci-003', |
| 21 | + 'prompt' => $this->generatePrompt($this->throwable), |
| 22 | + 'max_tokens' => 100, |
| 23 | + 'temperature' => 0, |
| 24 | + ])->choices[0]->text |
| 25 | + ); |
| 26 | + } |
| 27 | + |
| 28 | + public function getSolutionTitle(): string |
| 29 | + { |
| 30 | + return 'AI Generated Solution'; |
| 31 | + } |
| 32 | + |
| 33 | + public function getSolutionDescription(): string |
| 34 | + { |
| 35 | + return view('restify::prompts.solution', [ |
| 36 | + 'solution' => $this->solution, |
| 37 | + ])->render(); |
| 38 | + } |
| 39 | + |
| 40 | + public function getDocumentationLinks(): array |
| 41 | + { |
| 42 | + return []; |
| 43 | + } |
| 44 | + |
| 45 | + protected function getApplicationFrame(Throwable $throwable): ?Frame |
| 46 | + { |
| 47 | + $backtrace = Backtrace::createForThrowable($throwable)->applicationPath(base_path()); |
| 48 | + $frames = $backtrace->frames(); |
| 49 | + |
| 50 | + return $frames[$backtrace->firstApplicationFrameIndex()] ?? null; |
| 51 | + } |
| 52 | + |
| 53 | + protected function generatePrompt(Throwable $throwable): string |
| 54 | + { |
| 55 | + $applicationFrame = $this->getApplicationFrame($throwable); |
| 56 | + |
| 57 | + $snippet = $applicationFrame->getSnippet(15); |
| 58 | + |
| 59 | + return (string) view('restify::prompts.prompt', [ |
| 60 | + 'snippet' => collect($snippet)->map(fn ($line, $number) => $number.' '.$line)->join(PHP_EOL), |
| 61 | + 'file' => $applicationFrame->file, |
| 62 | + 'line' => $applicationFrame->lineNumber, |
| 63 | + 'exception' => $throwable->getMessage(), |
| 64 | + ]); |
| 65 | + } |
| 66 | +} |
0 commit comments