|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* For licensing terms, see /license.txt */ |
|
6
|
|
|
|
|
7
|
|
|
namespace Chamilo\CoreBundle\Controller; |
|
8
|
|
|
|
|
9
|
|
|
use Chamilo\CoreBundle\Service\AI\AiProviderFactory; |
|
10
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
|
11
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
12
|
|
|
use Symfony\Component\Routing\Annotation\Route; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Controller to handle AI-related functionalities. |
|
16
|
|
|
*/ |
|
17
|
|
|
#[Route('/ai')] |
|
18
|
|
|
class AiController |
|
19
|
|
|
{ |
|
20
|
|
|
private AiProviderFactory $aiProviderFactory; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct(AiProviderFactory $aiProviderFactory) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->aiProviderFactory = $aiProviderFactory; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Generate Aiken questions using AI. |
|
29
|
|
|
*/ |
|
30
|
|
|
#[Route('/generate_aiken', name: 'chamilo_core_ai_generate_aiken', methods: ['POST'])] |
|
31
|
|
|
public function generateAiken(Request $request): JsonResponse |
|
32
|
|
|
{ |
|
33
|
|
|
try { |
|
34
|
|
|
$data = json_decode($request->getContent(), true); |
|
35
|
|
|
$nQ = (int) ($data['nro_questions'] ?? 0); |
|
36
|
|
|
$language = (string) ($data['language'] ?? 'en'); |
|
37
|
|
|
$topic = trim((string) ($data['quiz_name'] ?? '')); |
|
38
|
|
|
$questionType = $data['question_type'] ?? 'multiple_choice'; |
|
39
|
|
|
$aiProvider = $data['ai_provider'] ?? null; |
|
40
|
|
|
|
|
41
|
|
|
if ($nQ <= 0 || empty($topic)) { |
|
42
|
|
|
return new JsonResponse([ |
|
43
|
|
|
'success' => false, |
|
44
|
|
|
'text' => 'Invalid request parameters. Ensure all fields are filled correctly.', |
|
45
|
|
|
], 400); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$aiService = $this->aiProviderFactory->getProvider($aiProvider); |
|
49
|
|
|
$questions = $aiService->generateQuestions($topic, $nQ, $questionType, $language); |
|
50
|
|
|
|
|
51
|
|
|
if (str_starts_with($questions, 'Error:')) { |
|
52
|
|
|
return new JsonResponse([ |
|
53
|
|
|
'success' => false, |
|
54
|
|
|
'text' => $questions, |
|
55
|
|
|
], 500); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return new JsonResponse([ |
|
59
|
|
|
'success' => true, |
|
60
|
|
|
'text' => trim($questions), |
|
61
|
|
|
]); |
|
62
|
|
|
|
|
63
|
|
|
} catch (\Exception $e) { |
|
64
|
|
|
error_log("AI Request failed: " . $e->getMessage()); |
|
65
|
|
|
return new JsonResponse([ |
|
66
|
|
|
'success' => false, |
|
67
|
|
|
'text' => "An error occurred while generating questions. Please contact the administrator.", |
|
68
|
|
|
], 500); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|