Passed
Push — master ( 4c7952...221fe6 )
by Angel Fernando Quiroz
08:53
created

DeepSeekAiProvider::generateLearnPath()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 87
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 59
nc 9
nop 6
dl 0
loc 87
rs 7.3389
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\AiProvider;
8
9
use Chamilo\CoreBundle\Entity\AiRequests;
10
use Chamilo\CoreBundle\Repository\AiRequestsRepository;
11
use Chamilo\CoreBundle\Settings\SettingsManager;
12
use Exception;
13
use RuntimeException;
14
use Symfony\Bundle\SecurityBundle\Security;
15
use Symfony\Component\Security\Core\User\UserInterface;
16
use Symfony\Contracts\HttpClient\HttpClientInterface;
17
18
class DeepSeekAiProvider implements AiProviderInterface
19
{
20
    private string $apiUrl;
21
    private string $apiKey;
22
    private string $model;
23
    private float $temperature;
24
    private string $organizationId;
25
    private int $monthlyTokenLimit;
26
    private HttpClientInterface $httpClient;
27
    private AiRequestsRepository $aiRequestsRepository;
28
    private Security $security;
29
30
    public function __construct(
31
        HttpClientInterface $httpClient,
32
        SettingsManager $settingsManager,
33
        AiRequestsRepository $aiRequestsRepository,
34
        Security $security
35
    ) {
36
        $this->httpClient = $httpClient;
37
        $this->aiRequestsRepository = $aiRequestsRepository;
38
        $this->security = $security;
39
40
        // Get AI providers from settings
41
        $configJson = $settingsManager->getSetting('ai_helpers.ai_providers', true);
42
        $config = json_decode($configJson, true) ?? [];
43
44
        if (!isset($config['deepseek'])) {
45
            throw new RuntimeException('DeepSeek configuration is missing.');
46
        }
47
48
        $this->apiUrl = $config['deepseek']['url'] ?? 'https://api.deepseek.com/chat/completions';
49
        $this->apiKey = $config['deepseek']['api_key'] ?? '';
50
        $this->model = $config['deepseek']['model'] ?? 'deepseek-chat';
51
        $this->temperature = $config['deepseek']['temperature'] ?? 0.7;
52
        $this->organizationId = $config['deepseek']['organization_id'] ?? '';
53
        $this->monthlyTokenLimit = $config['deepseek']['monthly_token_limit'] ?? 1000;
54
55
        if (empty($this->apiKey)) {
56
            throw new RuntimeException('DeepSeek API key is missing.');
57
        }
58
    }
59
60
    public function generateQuestions(string $topic, int $numQuestions, string $questionType, string $language): ?string
61
    {
62
        $prompt = \sprintf(
63
            'Generate %d "%s" questions in Aiken format in the %s language about "%s".
64
            Ensure each question follows this format:
65
66
            1. The question text.
67
            A. Option A
68
            B. Option B
69
            C. Option C
70
            D. Option D
71
            ANSWER: (Correct answer letter)
72
73
            The output should be plain text without additional symbols or markdown.',
74
            $numQuestions,
75
            $questionType,
76
            $language,
77
            $topic
78
        );
79
80
        return $this->requestDeepSeekAI($prompt, 'quiz');
81
    }
82
83
    public function generateLearnPath(string $topic, int $chaptersCount, string $language, int $wordsCount, bool $addTests, int $numQuestions): ?array
84
    {
85
        // Step 1: Generate the Table of Contents
86
        $tableOfContentsPrompt = \sprintf(
87
            'Generate a structured table of contents for a course in "%s" with %d chapters on "%s".
88
            Return a numbered list, each chapter on a new line. No conclusion.',
89
            $language,
90
            $chaptersCount,
91
            $topic
92
        );
93
94
        $lpStructure = $this->requestDeepSeekAI($tableOfContentsPrompt, 'learnpath');
95
        if (!$lpStructure) {
96
            return ['success' => false, 'message' => 'Failed to generate course structure.'];
97
        }
98
99
        // Step 2: Generate content for each chapter
100
        $lpItems = [];
101
        $chapters = explode("\n", trim($lpStructure));
102
        foreach ($chapters as $index => $chapterTitle) {
103
            $chapterTitle = trim($chapterTitle);
104
            if (empty($chapterTitle)) {
105
                continue;
106
            }
107
108
            $chapterPrompt = \sprintf(
109
                'Create a learning chapter in HTML for "%s" in "%s" with %d words.
110
                Title: "%s". Assume the reader already knows the context.',
111
                $topic,
112
                $language,
113
                $wordsCount,
114
                $chapterTitle
115
            );
116
117
            $chapterContent = $this->requestDeepSeekAI($chapterPrompt, 'learnpath');
118
            if (!$chapterContent) {
119
                continue;
120
            }
121
122
            $lpItems[] = [
123
                'title' => $chapterTitle,
124
                'content' => "<html><head><title>{$chapterTitle}</title></head><body>{$chapterContent}</body></html>",
125
            ];
126
        }
127
128
        // Step 3: Generate quizzes if enabled
129
        $quizItems = [];
130
        if ($addTests) {
131
            foreach ($lpItems as &$chapter) {
132
                $quizPrompt = \sprintf(
133
                    'Generate %d multiple-choice questions in Aiken format in %s about "%s".
134
        Ensure each question follows this format:
135
136
        1. The question text.
137
        A. Option A
138
        B. Option B
139
        C. Option C
140
        D. Option D
141
        ANSWER: (Correct answer letter)
142
143
        Each question must have exactly 4 options and one answer line.
144
        Return only valid questions without extra text.',
145
                    $numQuestions,
146
                    $language,
147
                    $chapter['title']
148
                );
149
150
                $quizContent = $this->requestDeepSeekAI($quizPrompt, 'learnpath');
151
152
                if ($quizContent) {
153
                    $validQuestions = $this->filterValidAikenQuestions($quizContent);
154
155
                    if (!empty($validQuestions)) {
156
                        $quizItems[] = [
157
                            'title' => 'Quiz: '.$chapter['title'],
158
                            'content' => implode("\n\n", $validQuestions),
159
                        ];
160
                    }
161
                }
162
            }
163
        }
164
165
        return [
166
            'success' => true,
167
            'topic' => $topic,
168
            'lp_items' => $lpItems,
169
            'quiz_items' => $quizItems,
170
        ];
171
    }
172
173
    private function filterValidAikenQuestions(string $quizContent): array
174
    {
175
        $questions = preg_split('/\n{2,}/', trim($quizContent));
176
177
        $validQuestions = [];
178
        foreach ($questions as $questionBlock) {
179
            $lines = explode("\n", trim($questionBlock));
180
181
            if (\count($lines) < 6) {
182
                continue;
183
            }
184
185
            $options = \array_slice($lines, 1, 4);
186
            $validOptions = array_filter($options, fn ($line) => preg_match('/^[A-D]\. .+/', $line));
187
188
            $answerLine = end($lines);
189
            if (4 === \count($validOptions) && preg_match('/^ANSWER: [A-D]$/', $answerLine)) {
190
                $validQuestions[] = implode("\n", $lines);
191
            }
192
        }
193
194
        return $validQuestions;
195
    }
196
197
    private function requestDeepSeekAI(string $prompt, string $toolName): ?string
198
    {
199
        $userId = $this->getUserId();
200
        if (!$userId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
201
            throw new RuntimeException('User not authenticated.');
202
        }
203
204
        $payload = [
205
            'model' => $this->model,
206
            'messages' => [
207
                ['role' => 'system', 'content' => 'You are a helpful AI assistant that generates structured educational content.'],
208
                ['role' => 'user', 'content' => $prompt],
209
            ],
210
            'temperature' => $this->temperature,
211
            'max_tokens' => 300,
212
        ];
213
214
        try {
215
            $response = $this->httpClient->request('POST', $this->apiUrl, [
216
                'headers' => [
217
                    'Authorization' => 'Bearer '.$this->apiKey,
218
                    'Content-Type' => 'application/json',
219
                ],
220
                'json' => $payload,
221
            ]);
222
223
            $statusCode = $response->getStatusCode();
224
            $data = $response->toArray();
225
226
            if (200 === $statusCode && isset($data['choices'][0]['message']['content'])) {
227
                $generatedContent = $data['choices'][0]['message']['content'];
228
229
                $aiRequest = new AiRequests();
230
                $aiRequest->setUserId($userId)
231
                    ->setToolName($toolName)
232
                    ->setRequestText($prompt)
233
                    ->setPromptTokens($data['usage']['prompt_tokens'] ?? 0)
234
                    ->setCompletionTokens($data['usage']['completion_tokens'] ?? 0)
235
                    ->setTotalTokens($data['usage']['total_tokens'] ?? 0)
236
                    ->setAiProvider('deepseek')
237
                ;
238
239
                $this->aiRequestsRepository->save($aiRequest);
240
241
                return $generatedContent;
242
            }
243
244
            return null;
245
        } catch (Exception $e) {
246
            error_log('ERROR - DeepSeek Request failed: '.$e->getMessage());
247
248
            return null;
249
        }
250
    }
251
252
    private function getUserId(): ?int
253
    {
254
        $user = $this->security->getUser();
255
256
        return $user instanceof UserInterface ? $user->getId() : null;
257
    }
258
}
259