|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* For licensing terms, see /license.txt */ |
|
6
|
|
|
|
|
7
|
|
|
namespace Chamilo\CoreBundle\Service\AI; |
|
8
|
|
|
|
|
9
|
|
|
use Chamilo\CoreBundle\Repository\AiRequestsRepository; |
|
10
|
|
|
use Chamilo\CoreBundle\Settings\SettingsManager; |
|
11
|
|
|
use Symfony\Bundle\SecurityBundle\Security; |
|
12
|
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface; |
|
13
|
|
|
use InvalidArgumentException; |
|
14
|
|
|
|
|
15
|
|
|
class AiProviderFactory |
|
16
|
|
|
{ |
|
17
|
|
|
private array $providers; |
|
18
|
|
|
private string $defaultProvider; |
|
19
|
|
|
private AiRequestsRepository $aiRequestsRepository; |
|
20
|
|
|
private Security $security; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct( |
|
23
|
|
|
HttpClientInterface $httpClient, |
|
24
|
|
|
SettingsManager $settingsManager, |
|
25
|
|
|
AiRequestsRepository $aiRequestsRepository, |
|
26
|
|
|
Security $security |
|
27
|
|
|
) { |
|
28
|
|
|
$this->aiRequestsRepository = $aiRequestsRepository; |
|
29
|
|
|
$this->security = $security; |
|
30
|
|
|
|
|
31
|
|
|
// Get AI providers from settings |
|
32
|
|
|
$configJson = $settingsManager->getSetting('ai_helpers.ai_providers', true); |
|
33
|
|
|
$config = json_decode($configJson, true) ?? []; |
|
34
|
|
|
|
|
35
|
|
|
// Get the first available provider as default |
|
36
|
|
|
$this->defaultProvider = array_key_first($config) ?? 'openai'; |
|
37
|
|
|
|
|
38
|
|
|
// Initialize AI providers dynamically |
|
39
|
|
|
$this->providers = []; |
|
40
|
|
|
foreach ($config as $providerName => $providerConfig) { |
|
41
|
|
|
if ($providerName === 'openai') { |
|
42
|
|
|
$this->providers[$providerName] = new OpenAiProvider($httpClient, $settingsManager, $this->aiRequestsRepository, $this->security); |
|
43
|
|
|
} elseif ($providerName === 'deepseek') { |
|
44
|
|
|
$this->providers[$providerName] = new DeepSeekAiProvider($httpClient, $settingsManager, $this->aiRequestsRepository, $this->security); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
// Ensure the selected default provider exists |
|
49
|
|
|
if (!isset($this->providers[$this->defaultProvider])) { |
|
50
|
|
|
throw new InvalidArgumentException("The default AI provider '{$this->defaultProvider}' is not configured properly."); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function getProvider(string $provider = null): AiProviderInterface |
|
55
|
|
|
{ |
|
56
|
|
|
$provider = $provider ?? $this->defaultProvider; |
|
57
|
|
|
|
|
58
|
|
|
if (!isset($this->providers[$provider])) { |
|
59
|
|
|
throw new InvalidArgumentException("AI Provider '$provider' is not supported."); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return $this->providers[$provider]; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|