Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: short answer reset button #4

Merged
merged 1 commit into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions ai_eval/shortanswer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from web_fragments.fragment import Fragment
from xblock.core import XBlock
from xblock.exceptions import JsonHandlerError
from xblock.fields import Integer, String, Scope
from xblock.fields import Boolean, Integer, String, Scope
from xblock.validation import ValidationMessage

from .llm import get_llm_response
Expand Down Expand Up @@ -37,7 +37,17 @@ class ShortAnswerAIEvalXBlock(AIEvalXBlock):
default=3,
)

editable_fields = AIEvalXBlock.editable_fields + ("max_responses",)
allow_reset = Boolean(
display_name=_("Allow reset"),
help=_("Allow the learner to reset the chat"),
scope=Scope.settings,
default=False,
)

editable_fields = AIEvalXBlock.editable_fields + (
"max_responses",
"allow_reset",
)

def validate_field_data(self, validation, data):
"""
Expand Down Expand Up @@ -132,6 +142,16 @@ def get_response(self, data, suffix=""): # pylint: disable=unused-argument

raise JsonHandlerError(500, "A probem occured. The LLM sent an empty response.")

@XBlock.json_handler
def reset(self, data, suffix=""):
"""
Reset the Xblock.
"""
if not self.allow_reset:
raise JsonHandlerError(403, "Reset is disabled.")
self.messages = {self.USER_KEY: [], self.LLM_KEY: []}
return {}

@staticmethod
def workbench_scenarios():
"""A canned scenario for display in the workbench."""
Expand Down
18 changes: 14 additions & 4 deletions ai_eval/static/css/shortanswer.css
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,36 @@
.submit-row .user-input {
flex: 8;
height: auto;
margin-right: 10px;
border: 1px solid gray;
border-radius: 5px;
overflow: auto;
max-height: 200px;
resize: none;
}

.submit-row #submit-button {
#submit-button, #reset-button {
flex: 1;
height: fit-content;
text-align: center;
padding: 10px 0;
margin-left: auto;
background-color: #00262b;
color: white;
border-radius: 5px;
border: none;
cursor: pointer;
}

#submit-button {
background-color: #00262b;
color: white;
margin-left: 10px;
}

#reset-button {
border: 1px solid;
color: #00262b;
margin-right: 10px;
}

.submit-row .disabled-btn {
opacity: 0.8;
cursor: not-allowed !important;
Expand Down
24 changes: 24 additions & 0 deletions ai_eval/static/js/src/shortanswer.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* Javascript for ShortAnswerAIEvalXBlock. */
function ShortAnswerAIEvalXBlock(runtime, element, data) {
const handlerUrl = runtime.handlerUrl(element, "get_response");
const resetHandlerURL = runtime.handlerUrl(element, "reset");

loadMarkedInIframe(data.marked_html);

$(function () {
const spinner = $(".message-spinner", element);
const spinnnerContainer = $("#chat-spinner-container", element);
const resetButton = $("#reset-button", element);
const submitButton = $("#submit-button", element);
const userInput = $(".user-input", element);
const userInputElem = userInput[0];
Expand Down Expand Up @@ -46,6 +48,25 @@ function ShortAnswerAIEvalXBlock(runtime, element, data) {

submitButton.click(getResponse);

resetButton.click(() => {
if (!resetButton.hasClass("disabled-btn")) {
$.ajax({
url: resetHandlerURL,
method: "POST",
data: JSON.stringify({}),
success: function (data) {
spinnnerContainer.prevAll('.chat-message-container').remove();
resetButton.addClass("disabled-btn");
enableInput();
},
error: function(xhr, status, error) {
console.error('Error:', error);
alert("A problem occured during reset.");
}
});
}
});

function disableInput() {
userInput.prop("disabled", true);
userInput.removeAttr("placeholder");
Expand Down Expand Up @@ -74,6 +95,7 @@ function ShortAnswerAIEvalXBlock(runtime, element, data) {
for (let i = 0; i < data.messages.USER.length; i++) {
insertUserMessage(data.messages.USER[i]);
insertAIMessage(data.messages.LLM[i]);
resetButton.removeClass("disabled-btn");
}
if (
data.messages.USER.length &&
Expand All @@ -88,6 +110,7 @@ function ShortAnswerAIEvalXBlock(runtime, element, data) {
$(` <div class="chat-message-container">
<div class="chat-message user-answer">${MarkdownToHTML(msg)}</div>
</div>`).insertBefore(spinnnerContainer);
resetButton.removeClass("disabled-btn");
}
}

Expand All @@ -96,6 +119,7 @@ function ShortAnswerAIEvalXBlock(runtime, element, data) {
$(` <div class="chat-message-container">
<div class="chat-message ai-eval">${MarkdownToHTML(msg)}</div>
</div>`).insertBefore(spinnnerContainer);
resetButton.removeClass("disabled-btn");
}
}
function deleteLastMessage() {
Expand Down
3 changes: 3 additions & 0 deletions ai_eval/templates/shortanswer.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
</div>
</div>
<div class="submit-row">
{% if self.allow_reset %}
<span id="reset-button" class="disabled-btn">Reset chat</span>
{% endif %}
<textarea class="user-input" rows="1" placeholder="Type your answer here" maxlength="1000"></textarea>
<span id="submit-button">Submit <i class="fa fa-paper-plane"></i></span>
</div>
Expand Down
50 changes: 41 additions & 9 deletions ai_eval/tests/test_ai_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import unittest
from xblock.exceptions import JsonHandlerError
from xblock.field_data import DictFieldData
from xblock.test.toy_runtime import ToyRuntime
from ai_eval import CodingAIEvalXBlock, ShortAnswerAIEvalXBlock
Expand Down Expand Up @@ -39,17 +40,48 @@ def test_basics_student_view(self):
class TestShortAnswerAIEvalXBlock(unittest.TestCase):
"""Tests for ShortAnswerAIEvalXBlock"""

data = {
"question": "ca va?",
"messages": {"USER": [], "LLM": []},
"max_responses": 3,
"marked_html": (
'<!doctype html>\n<html lang="en">\n<head></head>\n<body>\n'
' <script type="text/javascript" '
'src="https://cdnjs.cloudflare.com'
'/ajax/libs/marked/13.0.2/marked.min.js"></script>\n'
'</body>\n</html>'
),
}

def test_basics_student_view(self):
"""Test the basic view loads."""
block = ShortAnswerAIEvalXBlock(
ToyRuntime(),
DictFieldData(self.data),
None,
)
frag = block.student_view()
self.assertEqual(frag.json_init_args, self.data)
self.assertIn('<div class="shortanswer_block">', frag.content)

def test_reset(self):
"""Test the reset function."""
data = {
"question": "ca va?",
"messages": {"USER": [], "LLM": []},
"max_responses": 3,
"marked_html": '<!doctype html>\n<html lang="en">\n<head></head>\n<body>\n <script '
'type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/marked/13.0.2/marked'
'.min.js"></script>\n</body>\n</html>',
**self.data,
"allow_reset": True,
"messages": {"USER": ["Hello"], "LLM": ["Hello"]},
}
block = ShortAnswerAIEvalXBlock(ToyRuntime(), DictFieldData(data), None)
frag = block.student_view()
self.assertEqual(data, frag.json_init_args)
self.assertIn('<div class="shortanswer_block">', frag.content)
block.reset.__wrapped__(block, data={})
self.assertEqual(block.messages, {"USER": [], "LLM": []})

def test_reset_forbidden(self):
"""Test the reset function."""
data = {
**self.data,
"messages": {"USER": ["Hello"], "LLM": ["Hello"]},
}
block = ShortAnswerAIEvalXBlock(ToyRuntime(), DictFieldData(data), None)
with self.assertRaises(JsonHandlerError):
block.reset.__wrapped__(block, data={})
self.assertEqual(block.messages, {"USER": ["Hello"], "LLM": ["Hello"]})
Loading