mirror of
https://gitlab.com/CIEFWorldwideSdnBhd/exchange-2.0.git
synced 2026-08-19 12:33:56 +00:00
51 lines
1.6 KiB
PHP
51 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Classes\Modules\OpenAI\Services;
|
|
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use App\Classes\Exceptions\MalformedRequestException;
|
|
use App\Classes\Exceptions\ConnectionErrorException;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class CreatesChatGPTResponse
|
|
{
|
|
/**
|
|
* @param string $userPrompt
|
|
* @return null|object
|
|
* @throws MalformedRequestException
|
|
*/
|
|
public function execute(string $userPrompt) {
|
|
try {
|
|
$data = [
|
|
'model' => 'gpt-4-turbo', //gpt-4-turbo, gpt-4o-mini
|
|
'messages' => [
|
|
[
|
|
'role' => 'user',
|
|
'content' => $userPrompt
|
|
]
|
|
]
|
|
];
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => 'Bearer ' . config('openai.api_key')
|
|
])->post(config('openai.base_url') . '/v1/chat/completions', $data);
|
|
|
|
if ($response->successful()) {
|
|
$data = $response->json();
|
|
return $data;
|
|
} else {
|
|
Log::info('CreatesChatGPTResponse: ' . $response);
|
|
return null;
|
|
}
|
|
}
|
|
catch (\Illuminate\Http\Client\ConnectionException $exception) {
|
|
$error = 'Failed to connect to ChatGPT API';
|
|
throw new ConnectionErrorException($error, $exception->getMessage(), $userPrompt, $exception->getTraceAsString());
|
|
}
|
|
catch (\Exception $exception) {
|
|
throw new MalformedRequestException('Unable to get correct response from ChatGPT API: ' . $exception->getMessage());
|
|
}
|
|
}
|
|
}
|