Files
musadaq-saas/app/Services/AI/OpenAIProvider.php

85 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\AI;
use App\Services\AI\Contracts\AIProviderInterface;
use Exception;
final class OpenAIProvider implements AIProviderInterface
{
private string $apiKey;
private string $model;
public function __construct()
{
$this->apiKey = $_ENV['OPENAI_API_KEY'] ?? '';
$this->model = $_ENV['OPENAI_MODEL'] ?? 'gpt-4o-mini';
}
public function isConfigured(): bool
{
return !empty($this->apiKey);
}
public function extractInvoiceData(string $fileContent, string $mimeType, string $prompt): array
{
if (!$this->isConfigured()) {
throw new Exception("OpenAI API Key is missing. Please configure it in .env");
}
$base64Data = base64_encode($fileContent);
$payload = [
'model' => $this->model,
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => $prompt
],
[
'type' => 'image_url',
'image_url' => [
'url' => "data:{$mimeType};base64,{$base64Data}"
]
]
]
]
],
'response_format' => ['type' => 'json_object'],
'temperature' => 0.1
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"Authorization: Bearer {$this->apiKey}"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("OpenAI Extraction failed. HTTP Code: {$httpCode}. Response: {$response}");
}
$result = json_decode($response, true);
$text = $result['choices'][0]['message']['content'] ?? '{}';
$data = json_decode($text, true);
if (!is_array($data)) {
throw new Exception("Failed to parse OpenAI output as JSON: {$text}");
}
return $data;
}
}