PluginProbe
Fluent Support – Helpdesk & Customer Support Ticket System / 2.4.0
Fluent Support – Helpdesk & Customer Support Ticket System v2.4.0
2.4.0 2.3.2 2.3.1 2.3.0 2.2.1 2.2.0 trunk 1.10.0 1.10.1 1.10.2 1.10.3 1.10.4 1.10.5 1.4.0 1.4.1 1.4.2 1.4.5 1.4.6 1.4.7 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.5.5 All 68 releases
fluent-support / app / Services / Integrations / AI / BaseAIProvider.php

BaseAIProvider.php in Fluent Support – Helpdesk & Customer Support Ticket System 2.4.0, at app/Services/Integrations/AI/BaseAIProvider.php

84 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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