Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * The helper module or AI Subsystem.
18
 *
19
 * @module     core_ai/helper
20
 * @copyright  2024 Huong Nguyen <huongnv13@gmail.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
export default class AIHelper {
24
    /**
25
     * Replace double line breaks with <br> and with </p><p> for paragraphs.
26
     * This is to handle the difference in response from the AI to what is expected by the editor.
27
     *
28
     * @param {String} text The text to replace.
29
     * @returns {String}
30
     */
31
    static replaceLineBreaks(text) {
32
        // Replace double line breaks with </p><p> for paragraphs
33
        const textWithParagraphs = text.replace(/\n{2,}|\r\n/g, '<br/><br/>');
34
 
35
        // Replace remaining single line breaks with <br> tags
36
        const textWithBreaks = textWithParagraphs.replace(/\n/g, '<br/>');
37
 
38
        // Add opening and closing <p> tags to wrap the entire content
39
        return `<p>${textWithBreaks}</p>`;
40
    }
41
 
42
    /**
43
     * Replace markdown formatting.
44
     * Even when asked not to, AI models will sometimes return markdown.
45
     *
46
     * @param {String} text The text to replace.
47
     * @returns {String}
48
     */
49
    static replaceMarkdown(text) {
50
        // Replace markdown bold formatting HTML equivalent.
51
        const textWithMarkdown = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
52
 
53
        return textWithMarkdown;
54
    }
55
 
56
    /**
57
     * Format the response provided by the AI model.
58
     *
59
     * @param {String} text The text to format.
60
     * @returns {String}
61
     */
62
    static formatResponse(text) {
63
        let formattedText = this.replaceLineBreaks(text) ;
64
        formattedText = this.replaceMarkdown(formattedText);
65
 
66
        return formattedText;
67
    }
68
}