mirror of
https://gitlab.com/CIEFWorldwideSdnBhd/exchange-2.0.git
synced 2026-08-19 04:23:55 +00:00
53 lines
1.7 KiB
PHP
53 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Classes\Modules\OpenAI\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use App\Classes\Exceptions\MalformedRequestException;
|
|
use App\Classes\Exceptions\ConnectionErrorException;
|
|
|
|
class CreatesChatGPTResponseWithFiles
|
|
{
|
|
public function execute(string $userPrompt, array $fileIds)
|
|
{
|
|
try {
|
|
$fileContents = [];
|
|
foreach ($fileIds as $fileId) {
|
|
$fileContents[] = [
|
|
'type' => 'input_file',
|
|
'file_id' => $fileId,
|
|
];
|
|
}
|
|
|
|
$inputs = array_merge([
|
|
[
|
|
'type' => 'input_text',
|
|
'text' => $userPrompt,
|
|
]
|
|
], $fileContents);
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => 'Bearer ' . config('openai.api_key'),
|
|
'Content-Type' => 'application/json',
|
|
])->post(config('openai.base_url') . '/v1/responses', [
|
|
'model' => 'gpt-4.1-mini',
|
|
'input' => [
|
|
[
|
|
'role' => 'user',
|
|
'content' => $inputs,
|
|
],
|
|
],
|
|
]);
|
|
|
|
return $response->json();
|
|
}
|
|
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());
|
|
}
|
|
}
|
|
}
|