| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Services\Integrations\AI\Providers; |
| 4 |
|
| 5 |
use FluentSupport\App\Services\Integrations\AI\BaseAIProvider; |
| 6 |
use WP_Error; |
| 7 |
|
| 8 |
class OpenAIProvider extends BaseAIProvider |
| 9 |
{ |
| 10 |
protected $completionsUrl = 'https://api.openai.com/v1/chat/completions'; |
| 11 |
|
| 12 |
public function getProviderName(): string |
| 13 |
{ |
| 14 |
return 'OpenAI'; |
| 15 |
} |
| 16 |
|
| 17 |
public function getAvailableModels(): array |
| 18 |
{ |
| 19 |
$models = [ |
| 20 |
['value' => 'gpt-4.1', 'label' => 'GPT-4.1'], |
| 21 |
['value' => 'gpt-4.1-mini', 'label' => 'GPT-4.1 Mini'], |
| 22 |
['value' => 'gpt-4.1-nano', 'label' => 'GPT-4.1 Nano'], |
| 23 |
['value' => 'gpt-4o', 'label' => 'GPT-4o'], |
| 24 |
['value' => 'gpt-4o-mini', 'label' => 'GPT-4o Mini'], |
| 25 |
['value' => 'gpt-4o-2024-08-06', 'label' => 'GPT-4o (2024-08-06)'], |
| 26 |
['value' => 'gpt-4o-mini-2024-07-18', 'label' => 'GPT-4o Mini (2024-07-18)'], |
| 27 |
['value' => 'gpt-4-turbo', 'label' => 'GPT-4 Turbo'], |
| 28 |
['value' => 'gpt-4', 'label' => 'GPT-4'], |
| 29 |
['value' => 'gpt-3.5-turbo', 'label' => 'GPT-3.5 Turbo'], |
| 30 |
['value' => 'o3', 'label' => 'o3'], |
| 31 |
['value' => 'o3-mini', 'label' => 'o3-mini'], |
| 32 |
['value' => 'o4-mini', 'label' => 'o4-mini'], |
| 33 |
['value' => 'o1', 'label' => 'o1'], |
| 34 |
]; |
| 35 |
|
| 36 |
return apply_filters('fluent_support/supported_openai_models', $models); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* @param int $ticketId |
| 41 |
* @param string $prompt |
| 42 |
* @param array $messages |
| 43 |
* @return string|WP_Error |
| 44 |
*/ |
| 45 |
public function generateResponse(int $ticketId, string $prompt, array $messages = []) |
| 46 |
{ |
| 47 |
if (empty($messages)) { |
| 48 |
$messages = [['role' => 'system', 'content' => $prompt]]; |
| 49 |
} |
| 50 |
|
| 51 |
$payload = [ |
| 52 |
'model' => $this->model, |
| 53 |
'messages' => $messages, |
| 54 |
]; |
| 55 |
|
| 56 |
$headers = ['Authorization' => 'Bearer ' . $this->apiKey]; |
| 57 |
|
| 58 |
$body = $this->sendRequest($this->completionsUrl, $payload, $headers); |
| 59 |
|
| 60 |
if (is_wp_error($body)) { |
| 61 |
return $body; |
| 62 |
} |
| 63 |
|
| 64 |
$content = $body['choices'][0]['message']['content'] ?? ''; |
| 65 |
$tokens = ($body['usage']['prompt_tokens'] ?? 0) + ($body['usage']['completion_tokens'] ?? 0); |
| 66 |
|
| 67 |
$this->fireSuccessAction($ticketId, $prompt, $tokens); |
| 68 |
|
| 69 |
return $content; |
| 70 |
} |
| 71 |
|
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|