Files
exchange-2.0/app/Classes/Modules/OpenAI/Services/CreatesChatGPTResponseWithFiles.php
T
2025-12-30 16:09:16 +08:00

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());
}
}
}