88
99use Chamilo \CoreBundle \Repository \AiRequestsRepository ;
1010use Chamilo \CoreBundle \Settings \SettingsManager ;
11- use Exception ;
1211use InvalidArgumentException ;
12+ use Throwable ;
1313use Symfony \Bundle \SecurityBundle \Security ;
1414use Symfony \Contracts \HttpClient \HttpClientInterface ;
1515
@@ -35,7 +35,7 @@ public function __construct(
3535 ) {
3636 $ config = $ this ->readProvidersConfig ();
3737
38- // Default provider = first key in config (if any)
38+ // Default provider = first key in config (if any). It may be replaced later if it is not usable.
3939 $ this ->defaultProvider = array_key_first ($ config ) ?? 'openai ' ;
4040
4141 // Provider name -> class prefix
@@ -45,6 +45,8 @@ public function __construct(
4545 'grok ' => 'Grok ' ,
4646 'mistral ' => 'Mistral ' ,
4747 'gemini ' => 'Gemini ' ,
48+ 'claude ' => 'Claude ' ,
49+ 'anthropic ' => 'Anthropic ' ,
4850 ];
4951
5052 // Suffix used only if you create type-specific classes (optional)
@@ -136,9 +138,19 @@ public function __construct(
136138 }
137139 }
138140
139- // Ensure default provider exists when config is not empty
141+ // Keep the AI UI usable even if the first configured provider is invalid.
140142 if (!empty ($ config ) && !isset ($ this ->providers [$ this ->defaultProvider ])) {
141- throw new InvalidArgumentException ("The default AI provider ' {$ this ->defaultProvider }' is not configured properly. " );
143+ $ fallbackProvider = array_key_first ($ this ->providers );
144+
145+ if (\is_string ($ fallbackProvider )) {
146+ error_log ('[AI] Default provider " ' .$ this ->defaultProvider .'" is not usable. Falling back to " ' .$ fallbackProvider .'". ' );
147+ $ this ->defaultProvider = $ fallbackProvider ;
148+
149+ return ;
150+ }
151+
152+ error_log ('[AI] No usable AI providers are configured. ' );
153+ $ this ->defaultProvider = 'openai ' ;
142154 }
143155 }
144156
@@ -193,7 +205,15 @@ private function readProvidersConfig(): array
193205 $ configJson = $ this ->settingsManager ->getSetting ('ai_helpers.ai_providers ' , true );
194206
195207 if (\is_string ($ configJson )) {
196- return json_decode ($ configJson , true ) ?? [];
208+ $ decoded = json_decode ($ configJson , true );
209+
210+ if (!\is_array ($ decoded )) {
211+ error_log ('[AI] Invalid JSON in ai_helpers.ai_providers: ' .json_last_error_msg ());
212+
213+ return [];
214+ }
215+
216+ return $ decoded ;
197217 }
198218
199219 if (\is_array ($ configJson )) {
@@ -219,7 +239,7 @@ private function instantiateProvider(string $fqcn): ?object
219239 $ this ->aiRequestsRepository ,
220240 $ this ->security
221241 );
222- } catch (Exception $ e ) {
242+ } catch (Throwable $ e ) {
223243 error_log ('[AI] Could not instantiate ' .$ fqcn .': ' .$ e ->getMessage ());
224244
225245 return null ;
0 commit comments