| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Services\Integrations\AI; |
| 4 |
|
| 5 |
use WP_Error; |
| 6 |
|
| 7 |
abstract class BaseAIProvider |
| 8 |
{ |
| 9 |
protected $apiKey; |
| 10 |
protected $model; |
| 11 |
|
| 12 |
public function __construct(string $apiKey, string $model) |
| 13 |
{ |
| 14 |
$this->apiKey = $apiKey; |
| 15 |
$this->model = $model; |
| 16 |
} |
| 17 |
|
| 18 |
abstract public function getProviderName(): string; |
| 19 |
|
| 20 |
abstract public function getAvailableModels(): array; |
| 21 |
|
| 22 |
/** |
| 23 |
* @param int $ticketId |
| 24 |
* @param string $prompt |
| 25 |
* @param array $messages |
| 26 |
* @return string|WP_Error |
| 27 |
*/ |
| 28 |
abstract public function generateResponse(int $ticketId, string $prompt, array $messages = []); |
| 29 |
|
| 30 |
public function streamResponse(int $ticketId, string $prompt, array $messages = []): void |
| 31 |
{ |
| 32 |
$content = $this->generateResponse($ticketId, $prompt, $messages); |
| 33 |
|
| 34 |
if (is_wp_error($content)) { |
| 35 |
echo 'data: ' . wp_json_encode(['error' => $content->get_error_message()]) . "\n\n"; |
| 36 |
flush(); |
| 37 |
return; |
| 38 |
} |
| 39 |
|
| 40 |
echo 'data: ' . wp_json_encode(['choices' => [['delta' => ['content' => $content]]]]) . "\n\n"; |
| 41 |
echo "data: [DONE]\n\n"; |
| 42 |
flush(); |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
/** |
| 47 |
* @return array|WP_Error |
| 48 |
*/ |
| 49 |
protected function sendRequest(string $url, array $payload, array $headers) |
| 50 |
{ |
| 51 |
$timeout = apply_filters('fs_ai_request_timeout', 60); |
| 52 |
$response = wp_remote_post($url, [ |
| 53 |
'headers' => array_merge(['Content-Type' => 'application/json'], $headers), |
| 54 |
'body' => wp_json_encode($payload), |
| 55 |
'timeout' => $timeout, |
| 56 |
]); |
| 57 |
|
| 58 |
if (is_wp_error($response)) { |
| 59 |
return $response; |
| 60 |
} |
| 61 |
|
| 62 |
$code = wp_remote_retrieve_response_code($response); |
| 63 |
$body = json_decode(wp_remote_retrieve_body($response), true) ?? []; |
| 64 |
|
| 65 |
if ($code !== 200) { |
| 66 |
return new WP_Error($code, $this->extractErrorMessage($body)); |
| 67 |
} |
| 68 |
|
| 69 |
return $body; |
| 70 |
} |
| 71 |
|
| 72 |
protected function fireSuccessAction(int $ticketId, string $prompt, int $tokens): void |
| 73 |
{ |
| 74 |
do_action('fluent_support/ai_response_success', $ticketId, $prompt, $tokens, $this->getProviderName()); |
| 75 |
} |
| 76 |
|
| 77 |
protected function extractErrorMessage(array $body): string |
| 78 |
{ |
| 79 |
return $body['error']['message'] |
| 80 |
?? $body['message'] |
| 81 |
?? __('Unknown error occurred.', 'fluent-support'); |
| 82 |
} |
| 83 |
} |
| 84 |
|