opnform/app/Jobs/Form/GenerateAiForm.php

90 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Jobs\Form;
use App\Console\Commands\GenerateTemplate;
use App\Models\Forms\AI\AiFormCompletion;
use App\Service\OpenAi\GptCompleter;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
class GenerateAiForm implements ShouldQueue
{
2024-02-23 10:54:12 +00:00
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(public AiFormCompletion $completion)
{
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->completion->update([
2024-02-23 10:54:12 +00:00
'status' => AiFormCompletion::STATUS_PROCESSING,
]);
$completer = (new GptCompleter(config('services.openai.api_key')))
2023-10-25 15:55:53 +00:00
->useStreaming()
->setSystemMessage('You are a robot helping to generate forms.')
->expectsJson();
try {
$completer->completeChat([
2024-02-23 10:54:12 +00:00
['role' => 'user', 'content' => Str::of(GenerateTemplate::FORM_STRUCTURE_PROMPT)
->replace('[REPLACE]', $this->completion->form_prompt)->toString()],
], 3000);
$this->completion->update([
'status' => AiFormCompletion::STATUS_COMPLETED,
2024-02-23 10:54:12 +00:00
'result' => $this->cleanOutput($completer->getArray()),
]);
} catch (\Exception $e) {
2023-10-25 15:55:53 +00:00
$this->onError($e);
}
}
private function cleanOutput($formData)
{
// Add property uuids
foreach ($formData['properties'] as &$property) {
$property['id'] = Str::uuid()->toString();
}
return $formData;
}
2023-10-25 15:55:53 +00:00
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception): void
{
$this->onError($exception);
}
2024-02-23 10:54:12 +00:00
private function onError(\Throwable $e)
{
2023-10-25 15:55:53 +00:00
$this->completion->update([
'status' => AiFormCompletion::STATUS_FAILED,
2024-02-23 10:54:12 +00:00
'result' => ['error' => $e->getMessage()],
2023-10-25 15:55:53 +00:00
]);
}
}