DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: unify grade_answer, remove substring false positive (Block4)
unknown2a49676a6876
diff --git a/deeptutor/api/routers/guided_learning.py b/deeptutor/api/routers/guided_learning.pyindex a71ee7dcf..783d7d528 100644--- a/deeptutor/api/routers/guided_learning.py+++ b/deeptutor/api/routers/guided_learning.py@@ -6,6 +6,7 @@ from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModelfrom pydantic import ValidationError as PydanticValidationError+from deeptutor.learning.grading import grade_answerfrom deeptutor.learning.models import (ErrorType,KnowledgePoint,@@ -20,18 +21,9 @@ from deeptutor.learning.storage import LearningStorerouter = APIRouter()-def _grade_answer(user_answer: str, expected_answer: str) -> bool:- """Simple comparison. For short answers, do fuzzy match."""- if not expected_answer:- return False- user = user_answer.strip().lower()- expected = expected_answer.strip().lower()- if user == expected:- return True- # Allow substring match for long expected answers- if len(expected) > 10 and expected in user:- return True- return False+def _grade_answer(user_answer: str, expected_answer: str, question_type: str = "short") -> bool:+ """Delegate to unified grading function."""+ return grade_answer(user_answer, expected_answer, question_type)def _classify_error(user_answer: str, expected_answer: str) -> ErrorType | None:diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.pyindex 4e0899b8a..2693b4400 100644--- a/deeptutor/capabilities/guided_learning.py+++ b/deeptutor/capabilities/guided_learning.py@@ -9,6 +9,7 @@ from typing import Anyfrom deeptutor.core.capability_protocol import BaseCapability, CapabilityManifestfrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBus+from deeptutor.learning.grading import grade_answerfrom deeptutor.learning.models import (DiagnosticResult,ErrorType,@@ -250,7 +251,7 @@ class GuidedLearningCapability(BaseCapability):user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)stored = self._store.load_question_answers(book_id)expected = stored.get(qid, "")- is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()+ is_correct = bool(expected) and grade_answer(user_answer, expected)if is_correct:correct_count += 1self._service.record_quiz_attempt(@@ -295,7 +296,7 @@ class GuidedLearningCapability(BaseCapability):user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)stored = self._store.load_question_answers(book_id)expected = stored.get(qid, "")- is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()+ is_correct = bool(expected) and grade_answer(user_answer, expected)if is_correct:correct_count += 1self._service.record_quiz_attempt(@@ -476,7 +477,7 @@ class GuidedLearningCapability(BaseCapability):user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)stored = self._store.load_question_answers(book_id)expected = stored.get(qid, "")- is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()+ is_correct = bool(expected) and grade_answer(user_answer, expected)if is_correct:correct_count += 1self._service.record_quiz_attempt(@@ -533,7 +534,7 @@ class GuidedLearningCapability(BaseCapability):user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)stored = self._store.load_question_answers(book_id)expected = stored.get(qid, "")- is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()+ is_correct = bool(expected) and grade_answer(user_answer, expected)self._service.record_quiz_attempt(progress,QuizAttempt(diff --git a/deeptutor/learning/grading.py b/deeptutor/learning/grading.pynew file mode 100644index 000000000..7ea02e3e4--- /dev/null+++ b/deeptutor/learning/grading.py@@ -0,0 +1,47 @@+"""Unified grading function for guided learning."""+from __future__ import annotations++import re+from difflib import SequenceMatcher+++def grade_answer(user_answer: str, expected_answer: str, question_type: str = "short") -> bool:+ """Grade user answer against expected answer.++ Args:+ user_answer: The user's submitted answer.+ expected_answer: The stored expected answer.+ question_type: One of "choice", "short", "open".++ Returns:+ True if answer is correct.+ """+ user = user_answer.strip().lower()+ expected = expected_answer.strip().lower()++ if not expected:+ return False++ if question_type == "choice":+ user_norm = user.replace(" ", "")+ expected_norm = expected.replace(" ", "")+ return user_norm == expected_norm++ if question_type == "short":+ if user == expected:+ return True+ if len(expected) <= 30:+ return SequenceMatcher(None, user, expected).ratio() >= 0.85+ return False++ if question_type == "open":+ keywords = [k.strip() for k in re.split(r"[,;,;。\n]+", expected) if k.strip()]+ if not keywords:+ return False+ matched = sum(1 for kw in keywords if kw in user)+ return matched / len(keywords) >= 0.6++ return False+++__all__ = ["grade_answer"]diff --git a/deeptutor/learning/tests/test_grading.py b/deeptutor/learning/tests/test_grading.pynew file mode 100644index 000000000..835f60715--- /dev/null+++ b/deeptutor/learning/tests/test_grading.py@@ -0,0 +1,69 @@+"""Tests for the unified grade_answer function."""++from deeptutor.learning.grading import grade_answer+++class TestChoiceGrading:+ def test_choice_exact_match(self):+ assert grade_answer("A", "A", "choice") is True++ def test_choice_case_insensitive(self):+ assert grade_answer("b", "B", "choice") is True++ def test_choice_with_spaces(self):+ assert grade_answer("A ", " A", "choice") is True++ def test_choice_wrong(self):+ assert grade_answer("C", "A", "choice") is False+++class TestShortGrading:+ def test_short_exact_match(self):+ assert grade_answer("photosynthesis", "photosynthesis", "short") is True++ def test_short_fuzzy_pass(self):+ # "photosynthesi" vs "photosynthesis" — high similarity+ assert grade_answer("photosynthesi", "photosynthesis", "short") is True++ def test_short_fuzzy_fail(self):+ assert grade_answer("completely different", "photosynthesis", "short") is False++ def test_short_long_expected_no_fuzzy(self):+ long_expected = "a" * 31 # >30 chars, no fuzzy+ assert grade_answer(long_expected, long_expected, "short") is True+ assert grade_answer("something else entirely", long_expected, "short") is False+++class TestOpenGrading:+ def test_open_keywords_pass(self):+ expected = "cell membrane, nucleus, mitochondria"+ user = "The cell has a cell membrane and nucleus, with mitochondria for energy"+ assert grade_answer(user, expected, "open") is True++ def test_open_keywords_fail(self):+ expected = "cell membrane, nucleus, mitochondria"+ user = "I don't know anything about cells"+ assert grade_answer(user, expected, "open") is False++ def test_open_chinese_separators(self):+ expected = "光合作用;叶绿体;二氧化碳"+ user = "光合作用发生在叶绿体中,需要二氧化碳"+ assert grade_answer(user, expected, "open") is True+++class TestEdgeCases:+ def test_empty_expected_returns_false(self):+ assert grade_answer("anything", "", "short") is False+ assert grade_answer("anything", " ", "short") is False++ def test_empty_user_answer(self):+ assert grade_answer("", "expected", "short") is False++ def test_substring_no_longer_matches(self):+ """Regression: 'expected in user' substring match must not cause false positive."""+ user = "I do not know electromagnetic induction but maybe something else"+ expected = "electromagnetic induction"+ assert grade_answer(user, expected, "short") is False++ def test_unknown_type_returns_false(self):+ assert grade_answer("a", "a", "unknown") is False