Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
9 ariadna 1
{"version":3,"file":"lib.min.js","sources":["../src/lib.js"],"sourcesContent":["var questionString = 'Ask a question...'\nvar errorString = 'An error occurred! Please try again later.'\n\nexport const init = (data) => {\n\n    const blockId = data['blockId']\n    const api_type = data['api_type']\n    const persistConvo = data['persistConvo']\n\n    // Initialize local data storage if necessary\n    // If a thread ID exists for this block, make an API request to get existing messages\n    if (api_type === 'assistant') {\n        chatData = localStorage.getItem(\"block_openai_chat_data\")\n        if (chatData) {\n            chatData = JSON.parse(chatData)\n            if (chatData[blockId] && chatData[blockId]['threadId'] && persistConvo === \"1\") {\n                fetch(`${M.cfg.wwwroot}/blocks/openai_chat/api/thread.php?thread_id=${chatData[blockId]['threadId']}`)\n                .then(response => response.json())\n                .then(data => {\n                    for (let message of data) {\n                        addToChatLog(message.role === 'user' ? 'user' : 'bot', message.message)\n                    }\n                })\n                // Some sort of error in the API call. Probably the thread no longer exists, so lets reset it\n                .catch(error => {\n                    chatData[blockId] = {}\n                    localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n                })\n            // The block ID doesn't exist in the chat data object, so let's create it\n            } else {\n                chatData[blockId] = {}\n            }\n        // We don't even have a chat data object, so we'll create one\n        } else {\n            chatData = {[blockId]: {}}\n        }\n        localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n    }\n\n    // Prevent sidebar from closing when osk pops up (hack for MDL-77957)\n    window.addEventListener('resize', event => {\n        event.stopImmediatePropagation();\n    }, true);\n\n    document.querySelector('#openai_input').addEventListener('keyup', e => {\n        if (e.which === 13 && e.target.value !== \"\") {\n            addToChatLog('user', e.target.value)\n            createCompletion(e.target.value, blockId, api_type)\n            e.target.value = ''\n        }\n    })\n    document.querySelector('.block_openai_chat #go').addEventListener('click', e => {\n        const input = document.querySelector('#openai_input')\n        if (input.value !== \"\") {\n            addToChatLog('user', input.value)\n            createCompletion(input.value, blockId, api_type)\n            input.value = ''\n        }\n    })\n\n    document.querySelector('.block_openai_chat #refresh').addEventListener('click', e => {\n        clearHistory(blockId)\n    })\n\n    document.querySelector('.block_openai_chat #popout').addEventListener('click', e => {\n        if (document.querySelector('.drawer.drawer-right')) {\n            document.querySelector('.drawer.drawer-right').style.zIndex = '1041'\n        }\n        document.querySelector('.block_openai_chat').classList.toggle('expanded')\n    })\n\n    require(['core/str'], function(str) {\n        var strings = [\n            {\n                key: 'askaquestion',\n                component: 'block_openai_chat'\n            },\n            {\n                key: 'erroroccurred',\n                component: 'block_openai_chat'\n            },\n        ];\n        str.get_strings(strings).then((results) => {\n            questionString = results[0];\n            errorString = results[1];\n        });\n    });\n}\n\n/**\n * Add a message to the chat UI\n * @param {string} type Which side of the UI the message should be on. Can be \"user\" or \"bot\"\n * @param {string} message The text of the message to add\n */\nconst addToChatLog = (type, message) => {\n    let messageContainer = document.querySelector('#openai_chat_log')\n    \n    const messageElem = document.createElement('div')\n    messageElem.classList.add('openai_message')\n    for (let className of type.split(' ')) {\n        messageElem.classList.add(className)\n    }\n\n    const messageText = document.createElement('span')\n    messageText.innerHTML = message\n    messageElem.append(messageText)\n\n    messageContainer.append(messageElem)\n    if (messageText.offsetWidth) {\n        messageElem.style.width = (messageText.offsetWidth + 40) + \"px\"\n    }\n    messageContainer.scrollTop = messageContainer.scrollHeight\n    messageContainer.closest('.block_openai_chat > div').scrollTop = messageContainer.scrollHeight\n}\n\n/**\n * Clears the thread ID from local storage and removes the messages from the UI in order to refresh the chat\n */\nconst clearHistory = (blockId) => {\n    chatData = localStorage.getItem(\"block_openai_chat_data\")\n    if (chatData) {\n        chatData = JSON.parse(chatData)\n        if (chatData[blockId]) {\n            chatData[blockId] = {}\n            localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n        }\n    }\n    document.querySelector('#openai_chat_log').innerHTML = \"\"\n}\n\n/**\n * Makes an API request to get a completion from GPT-3, and adds it to the chat log\n * @param {string} message The text to get a completion for\n * @param {int} blockId The ID of the block this message is being sent from -- used to override settings if necessary\n * @param {string} api_type \"assistant\" | \"chat\" The type of API to use\n */\nconst createCompletion = (message, blockId, api_type) => {\n    let threadId = null\n    let chatData\n\n    // If the type is assistant, attempt to fetch a thread ID\n    if (api_type === 'assistant') {\n        chatData = localStorage.getItem(\"block_openai_chat_data\")\n        if (chatData) {\n            chatData = JSON.parse(chatData)\n            if (chatData[blockId]) {\n                threadId = chatData[blockId]['threadId'] || null\n            }\n        } else {\n            // create the chat data item if necessary\n            chatData = {[blockId]: {}}\n        }\n    }  \n\n    const history = buildTranscript()\n\n    document.querySelector('.block_openai_chat #control_bar').classList.add('disabled')\n    document.querySelector('#openai_input').classList.remove('error')\n    document.querySelector('#openai_input').placeholder = questionString\n    document.querySelector('#openai_input').blur()\n    addToChatLog('bot loading', '...');\n\n    fetch(`${M.cfg.wwwroot}/blocks/openai_chat/api/completion.php`, {\n        method: 'POST',\n        body: JSON.stringify({\n            message: message,\n            history: history,\n            blockId: blockId,\n            threadId: threadId\n        })\n    })\n    .then(response => {\n        let messageContainer = document.querySelector('#openai_chat_log')\n        messageContainer.removeChild(messageContainer.lastElementChild)\n        document.querySelector('.block_openai_chat #control_bar').classList.remove('disabled')\n\n        if (!response.ok) {\n            throw Error(response.statusText)\n        } else {\n            return response.json()\n        }\n    })\n    .then(data => {\n        try {\n            addToChatLog('bot', data.message)\n            if (data.thread_id) {\n                chatData[blockId]['threadId'] = data.thread_id\n                localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n            }\n        } catch (error) {\n            console.log(error)\n            addToChatLog('bot', data.error.message)\n        }\n        document.querySelector('#openai_input').focus()\n    })\n    .catch(error => {\n        console.log(error)\n        document.querySelector('#openai_input').classList.add('error')\n        document.querySelector('#openai_input').placeholder = errorString\n    })\n}\n\n/**\n * Using the existing messages in the chat history, create a string that can be used to aid completion\n * @return {JSONObject} A transcript of the conversation up to this point\n */\nconst buildTranscript = () => {\n    let transcript = []\n    document.querySelectorAll('.openai_message').forEach((message, index) => {\n        if (index === document.querySelectorAll('.openai_message').length - 1) {\n            return\n        }\n\n        let user = userName\n        if (message.classList.contains('bot')) {\n            user = assistantName\n        }\n        transcript.push({\"user\": user, \"message\": message.innerText})\n    })\n\n    return transcript\n}\n"],"names":["questionString","errorString","data","blockId","api_type","persistConvo","chatData","localStorage","getItem","JSON","parse","fetch","M","cfg","wwwroot","then","response","json","message","addToChatLog","role","catch","error","setItem","stringify","window","addEventListener","event","stopImmediatePropagation","document","querySelector","e","which","target","value","createCompletion","input","clearHistory","style","zIndex","classList","toggle","require","str","get_strings","key","component","results","type","messageContainer","messageElem","createElement","add","className","split","messageText","innerHTML","append","offsetWidth","width","scrollTop","scrollHeight","closest","threadId","history","buildTranscript","remove","placeholder","blur","method","body","removeChild","lastElementChild","ok","Error","statusText","thread_id","console","log","focus","transcript","querySelectorAll","forEach","index","length","user","userName","contains","assistantName","push","innerText"],"mappings":"gJAAIA,eAAiB,oBACjBC,YAAc,2DAEGC,aAEXC,QAAUD,KAAI,QACdE,SAAWF,KAAI,SACfG,aAAeH,KAAI,aAIR,cAAbE,WACAE,SAAWC,aAAaC,QAAQ,0BAC5BF,UACAA,SAAWG,KAAKC,MAAMJ,UAClBA,SAASH,UAAYG,SAASH,SAAT,UAAkD,MAAjBE,aACtDM,gBAASC,EAAEC,IAAIC,gEAAuDR,SAASH,SAAT,WACrEY,MAAKC,UAAYA,SAASC,SAC1BF,MAAKb,WACG,IAAIgB,WAAWhB,KAChBiB,aAA8B,SAAjBD,QAAQE,KAAkB,OAAS,MAAOF,QAAQA,YAItEG,OAAMC,QACHhB,SAASH,SAAW,GACpBI,aAAagB,QAAQ,yBAA0Bd,KAAKe,UAAUlB,cAIlEA,SAASH,SAAW,IAIxBG,SAAW,EAAEH,SAAU,IAE3BI,aAAagB,QAAQ,yBAA0Bd,KAAKe,UAAUlB,YAIlEmB,OAAOC,iBAAiB,UAAUC,QAC9BA,MAAMC,8BACP,GAEHC,SAASC,cAAc,i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