From 870e156f04ba466ec12d12bb82c24bbcff0eb767 Mon Sep 17 00:00:00 2001 From: mormal1016 Date: Mon, 16 Nov 2026 01:41:30 +0800 Subject: [PATCH] feat(review): ask follow-up questions beneath answer explanations --- pages/13_Answer_Review.py | 2 ++ services/answer_followup.py | 62 +++++++++++++++++++++++++++++++++++ services/i18n.py | 9 +++++ tests/test_answer_followup.py | 57 ++++++++++++++++++++++++++++++++ tests/test_practice_pages.py | 4 +-- 5 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 services/answer_followup.py create mode 100644 tests/test_answer_followup.py diff --git a/pages/13_Answer_Review.py b/pages/13_Answer_Review.py index 292dc59..a748748 100644 --- a/pages/13_Answer_Review.py +++ b/pages/13_Answer_Review.py @@ -8,6 +8,7 @@ import streamlit as st from components.page_links import back_button +from services.answer_followup import render_answer_followup from services.accessibility import display_question from services.hints import hints_for from services.practice_insights import session_insights @@ -110,6 +111,7 @@ def render_answer(review, display): st.subheader(tr("Explanation")) st.write(display.explanation) + render_answer_followup(course, question) reflection_controls(course, session, question, review, confirmed_topic_ids, practice_key) if question.source_pages: diff --git a/services/answer_followup.py b/services/answer_followup.py new file mode 100644 index 0000000..a4c6022 --- /dev/null +++ b/services/answer_followup.py @@ -0,0 +1,62 @@ +"""Question-scoped follow-up, asked only after a student submits the form.""" +import hashlib + +import streamlit as st + +from models.schemas import Question, StudyPackage +from services.ai_service import MAX_TUTOR_QUESTION_CHARS, ask_tutor +from services.i18n import LANGUAGE_KEY, tr + + +def render_answer_followup(course: StudyPackage, question: Question) -> None: + scope = hashlib.sha256( + (course.model_dump_json() + question.model_dump_json()).encode('utf-8') + ).hexdigest() + history_key = f'answer_followup_history_{scope}' + st.subheader(tr('Ask about this explanation')) + st.caption(tr('Ask what you did not understand. This conversation stays in this session and does not change your score.')) + for item in st.session_state.get(history_key, []): + with st.chat_message('user'): + st.write(item['question']) + with st.chat_message('assistant'): + st.write(item['answer']) + with st.form(f'answer_followup_form_{scope}', clear_on_submit=True): + question_text = st.text_area( + tr('What part is unclear?'), + placeholder=tr('For example: why is option B incorrect?'), + max_chars=MAX_TUTOR_QUESTION_CHARS, + ) + submitted = st.form_submit_button(tr('Ask AI')) + if not submitted: + return + question_text = question_text.strip() + if not question_text: + st.warning(tr('Enter a question first.')) + return + language = 'Simplified Chinese' if st.session_state.get(LANGUAGE_KEY, False) else 'English' + prompt = ( + f'Answer in {language}. The student is reviewing this exact question. ' + 'Explain the unclear part step by step, using the selected answer and reference explanation as context. ' + 'If the reference is insufficient, say so; do not invent course claims. ' + f'Question: {question.question}\n' + f'Options: {question.options}\n' + f'Correct option: {question.options[question.correct_index]}\n' + f'Reference explanation: {question.explanation}\n' + f'Student asks: {question_text}' + ) + # Limit the assembled prompt as well as the text area: ask_tutor caps total question length. + if len(prompt) > MAX_TUTOR_QUESTION_CHARS: + st.warning(tr('Your question is too long for this explanation. Please shorten it.')) + return + with st.spinner(tr('Preparing the explanation…')): + result = ask_tutor(course.model_dump(mode='json'), prompt, question.topic_id) + if not result.get('ok') or not result.get('answer', '').strip(): + st.warning(tr('AI is unavailable right now. Your score and explanation are unchanged.')) + return + st.session_state.setdefault(history_key, []).append( + {'question': question_text, 'answer': result['answer']} + ) + with st.chat_message('user'): + st.write(question_text) + with st.chat_message('assistant'): + st.write(result['answer']) diff --git a/services/i18n.py b/services/i18n.py index 02cc582..363df02 100644 --- a/services/i18n.py +++ b/services/i18n.py @@ -20,6 +20,15 @@ def remember_language() -> None: _TRANSLATIONS = { + 'Ask about this explanation': '针对这段解析提问', + 'Ask what you did not understand. This conversation stays in this session and does not change your score.': '哪里不理解就直接问。对话仅保留在当前会话,不影响成绩。', + 'What part is unclear?': '哪里没理解?', + 'For example: why is option B incorrect?': '例如:为什么 B 选项不对?', + 'Ask AI': '向 AI 提问', + 'Enter a question first.': '请先输入问题。', + 'Your question is too long for this explanation. Please shorten it.': '问题过长,请简化后重试。', + 'AI is unavailable right now. Your score and explanation are unchanged.': 'AI 暂时不可用;成绩和原解析均不受影响。', + 'Detailed explanation & examples': '详细讲解与例题', 'Go beyond the summary: understand the idea, then work through an example.': '不止看概述:先理解思路,再通过例题掌握用法。', 'Explain step by step': '分步骤讲解', diff --git a/tests/test_answer_followup.py b/tests/test_answer_followup.py new file mode 100644 index 0000000..53712c8 --- /dev/null +++ b/tests/test_answer_followup.py @@ -0,0 +1,57 @@ +from unittest.mock import Mock + +from streamlit.testing.v1 import AppTest + +from services import answer_followup + + +def followup_app(): + import streamlit as st + from models.schemas import StudyPackage + from services.answer_followup import render_answer_followup + from services.i18n import LANGUAGE_KEY + + st.toggle('Chinese', key=LANGUAGE_KEY) + topic = st.selectbox('Topic', ['t1', 't2']) + course = StudyPackage.model_validate({ + 'course_id': 'test', 'course_name': 'Test', + 'topics': [{'id': 't1', 'name': 'First', 'summary': 'First.'}, + {'id': 't2', 'name': 'Second', 'summary': 'Second.'}], + 'relationships': [], + 'questions': [ + {'id': t, 'topic_id': t, 'question': f'Question {t}?', + 'options': ['A', 'B', 'C', 'D'], 'correct_index': 0, + 'explanation': f'Explanation {t}.'} for t in ['t1', 't2'] + ], + }) + question = next(q for q in course.questions if q.topic_id == topic) + render_answer_followup(course, question) + + +def test_followup_only_calls_ai_on_submit_and_is_scoped(monkeypatch): + tutor = Mock(return_value={'ok': True, 'answer': 'Because of step one.'}) + monkeypatch.setattr(answer_followup, 'ask_tutor', tutor) + app = AppTest.from_function(followup_app).run() + assert not tutor.called + app.text_area[0].set_value('Why?').run() + assert not tutor.called + app.button[0].click().run() + assert tutor.call_count == 1 + assert tutor.call_args.args[2] == 't1' + assert any('Because of step one.' in item.value for item in app.markdown) + app.selectbox[0].select('t2').run() + assert not any('Because of step one.' in item.value for item in app.markdown) + assert tutor.call_count == 1 + + +def test_blank_and_failure_do_not_record_a_reply(monkeypatch): + tutor = Mock(return_value={'ok': False, 'message': 'Unavailable'}) + monkeypatch.setattr(answer_followup, 'ask_tutor', tutor) + app = AppTest.from_function(followup_app).run() + app.button[0].click().run() + assert not tutor.called + app.text_area[0].set_value('Can you explain?').run() + app.button[0].click().run() + assert tutor.call_count == 1 + assert any('unavailable' in item.value for item in app.warning) + assert not app.exception diff --git a/tests/test_practice_pages.py b/tests/test_practice_pages.py index faede74..5ccea28 100644 --- a/tests/test_practice_pages.py +++ b/tests/test_practice_pages.py @@ -270,7 +270,7 @@ def test_review_page_shows_one_question_with_everything_visible(): assert badges(app) == ["Q02"] and "Question 02 / 02" in [c.value for c in app.caption] # A missed question: everything about it is on the page, no expander and no tabs. assert not app.expander and not app.tabs - assert subheaders(app) == ["Answer", "Explanation", "Reflect and explain your answer", "Source material"] + assert subheaders(app) == ["Answer", "Explanation", "Ask about this explanation", "Reflect and explain your answer", "Source material"] assert [e.value for e in app.error] == ["✕ Your answer: B"] assert [s.value for s in app.success] == ["✓ Correct answer: A"] captions = [caption.value for caption in app.caption] @@ -282,7 +282,7 @@ def test_review_page_shows_one_question_with_everything_visible(): assert [text.value for text in app.text] == ["Page two says compare both values."] # The heading order reads top to bottom: answer, explanation, reflection, source. order = [subheader.value for subheader in app.subheader] - assert order == ["Answer", "Explanation", "Reflect and explain your answer", "Source material"] + assert order == ["Answer", "Explanation", "Ask about this explanation", "Reflect and explain your answer", "Source material"] def test_review_page_shows_the_original_wording_of_a_simplified_question():