DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(i18n): stop collapsing every non-English language to Chinese (#712)
Bingxi Zhao (Frank)591329322d2a
diff --git a/deeptutor/learning/prompts.py b/deeptutor/learning/prompts.pyindex 4ce85152d..b98357fcb 100644--- a/deeptutor/learning/prompts.py+++ b/deeptutor/learning/prompts.py@@ -14,6 +14,7 @@ from typing import Anyimport yamlfrom deeptutor.services.config import parse_language+from deeptutor.services.prompt.language import append_language_directive_PROMPT_DIR = Path(__file__).with_name("prompts")@@ -31,7 +32,9 @@ def _get_nested(data: dict[str, Any], path: str, default: str = "") -> str:def get_learning_prompts(language: str = "zh") -> dict[str, Any]:"""Load localized Mastery Path LLM prompts."""lang = parse_language(language)- candidates = [lang, "zh" if lang != "zh" else "en"]+ # Regional codes reuse their base locale's file ("zh-tw" -> zh.yaml); a+ # language with no file of its own lands on English, not Chinese (#712).+ candidates = dict.fromkeys([lang, lang.split("-", 1)[0], "en", "zh"])for candidate in candidates:path = _PROMPT_DIR / f"{candidate}.yaml"if path.exists():@@ -47,6 +50,11 @@ def notebook_generation_prompts(language: str, records_json: str) -> tuple[str,prompts = get_learning_prompts(language)system_prompt = _get_nested(prompts, "notebook.system", NOTEBOOK_SYSTEM)user_template = _get_nested(prompts, "notebook.user", NOTEBOOK_USER)+ # Only en/zh ship prompt files, so a Japanese learner is handed English+ # scaffolding. The directive — the same one book, quiz and Deep Research+ # already append — is what makes the answer come back in the language that+ # was actually asked for (#712).+ system_prompt = append_language_directive(system_prompt, parse_language(language))return system_prompt, user_template.format(records_json=records_json)diff --git a/deeptutor/learning/tests/test_prompt_language_fallback.py b/deeptutor/learning/tests/test_prompt_language_fallback.pynew file mode 100644index 000000000..4b0163e2b--- /dev/null+++ b/deeptutor/learning/tests/test_prompt_language_fallback.py@@ -0,0 +1,51 @@+"""Mastery Path prompts must not fall back to Chinese for every other language.++Only ``en.yaml`` and ``zh.yaml`` exist, and the old candidate list was+``[lang, "zh" if lang != "zh" else "en"]`` — so a Japanese learner got Chinese+prompt scaffolding while the rest of the book stayed Japanese (issue #712).+"""++from __future__ import annotations++import pytest++from deeptutor.learning.prompts import (+ get_learning_prompts,+ notebook_generation_prompts,+)++[email protected]("code", ["ja", "ko", "fr", "de", "ru"])+def test_a_language_without_its_own_file_lands_on_english(code: str) -> None:+ assert get_learning_prompts(code) == get_learning_prompts("en")+++def test_a_regional_chinese_code_still_gets_the_chinese_file() -> None:+ assert get_learning_prompts("zh-tw") == get_learning_prompts("zh")+++def test_the_two_shipped_locales_are_unchanged() -> None:+ chinese = get_learning_prompts("zh")+ english = get_learning_prompts("en")++ assert chinese and english+ assert chinese != english+++ ("code", "label"),+ [("ja", "日本語"), ("ko", "한국어"), ("fr", "Français")],+)+def test_notebook_prompts_ask_the_model_for_the_requested_language(code: str, label: str) -> None:+ """English scaffolding is fine; English *output* for a Japanese learner is not."""+ system_prompt, _user_prompt = notebook_generation_prompts(code, "[]")++ assert label in system_prompt+++def test_notebook_prompts_still_carry_a_directive_for_the_shipped_locales() -> None:+ zh_system, _ = notebook_generation_prompts("zh", "[]")+ en_system, _ = notebook_generation_prompts("en", "[]")++ assert "中文(简体)" in zh_system+ assert "in English" in en_systemdiff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.pyindex 5dc5271bf..c97a3bf86 100644--- a/deeptutor/services/config/loader.py+++ b/deeptutor/services/config/loader.py@@ -172,27 +172,31 @@ def parse_language(language: Any) -> str:"""Unified language configuration parser, supports multiple input formats- Supported language representations:- - English: "en", "english", "English"- - Chinese: "zh", "chinese", "Chinese"+ Resolves the spelled-out aliases of the two locales that ship prompt+ resources ("english"/"en", "chinese"/"cn"/"zh") and otherwise passes the+ code through normalized, so a request for Japanese stays ``"ja"`` instead+ of collapsing to Chinese (#712). Callers that load per-language prompt+ files fall back to English when a code has no files of its own; what makes+ the model actually answer in that language is the directive built from+ this code, not the prompt file.Args:- language: Language configuration value (can be "zh"/"en"/"Chinese"/"English" etc.)+ language: Language configuration value ("zh"/"en"/"Chinese"/"ja"/…)Returns:- Standardized language code: 'zh' or 'en', defaults to 'zh'+ Normalized language code, defaulting to 'zh' when nothing is configured"""- if not language:+ if not isinstance(language, str) or not language.strip():return "zh"- if isinstance(language, str):- lang_lower = language.lower()- if lang_lower in ["en", "english"]:- return "en"- if lang_lower in ["zh", "chinese", "cn"]:- return "zh"+ from deeptutor.services.prompt.language import normalize_language- return "zh" # Default Chinese+ code = normalize_language(language)+ if code in ("en", "english"):+ return "en"+ if code in ("zh", "chinese", "cn"):+ return "zh"+ return codedef get_agent_params(module_name: str) -> dict:diff --git a/deeptutor/services/prompt/manager.py b/deeptutor/services/prompt/manager.pyindex bdcf231cb..f4fdd736b 100644--- a/deeptutor/services/prompt/manager.py+++ b/deeptutor/services/prompt/manager.py@@ -100,7 +100,7 @@ class PromptManager:) -> dict[str, Any]:"""Load prompt file with language fallback."""prompt_dirs = self._candidate_prompt_dirs(module_name)- fallback_chain = self.LANGUAGE_FALLBACKS.get(lang_code, ["en"])+ fallback_chain = self._fallback_chain(lang_code)for prompts_dir in prompt_dirs:for lang in fallback_chain:@@ -116,6 +116,19 @@ class PromptManager:print(f"Warning: No prompt file found for {module_name}/{agent_name}")return {}+ def _fallback_chain(self, lang_code: str) -> list[str]:+ """Prompt-file lookup order for *lang_code*.++ A regional code reuses its base locale's files ("zh-tw" -> "zh"), and a+ language that ships none of its own lands on English rather than on+ Chinese (#712) — the language directive, not the prompt file, is what+ makes the model answer in the requested language.+ """+ base_chain = self.LANGUAGE_FALLBACKS.get(lang_code) or self.LANGUAGE_FALLBACKS.get(+ lang_code.split("-", 1)[0], []+ )+ return list(dict.fromkeys([lang_code, *base_chain, "en"]))+def _candidate_prompt_dirs(self, module_name: str) -> list[Path]:"""Return legacy and current prompt roots for a module."""if module_name in self.NON_AGENT_MODULES:diff --git a/tests/services/test_parse_language.py b/tests/services/test_parse_language.pynew file mode 100644index 000000000..080737cce--- /dev/null+++ b/tests/services/test_parse_language.py@@ -0,0 +1,61 @@+"""Language codes must survive parsing.++``parse_language`` used to be a binary zh/en classifier whose final statement+was ``return "zh"``, so a Japanese book came back with Chinese quizzes — the+prose path normalized the code correctly while quiz, Deep Research and Mastery+Path all ran through this one (issue #712).+"""++from __future__ import annotations++import pytest++from deeptutor.services.config import parse_language+from deeptutor.services.prompt import get_prompt_manager+++def prompt_file_chain(code: str) -> list[str]:+ """The order ``PromptManager`` tries language-specific prompt files in."""+ return get_prompt_manager()._fallback_chain(code)++[email protected]("code", ["ja", "ko", "fr", "de", "es", "ru", "ar", "pt", "it"])+def test_a_requested_language_is_not_rewritten_to_chinese(code: str) -> None:+ assert parse_language(code) == code++[email protected]("value", ["en", "EN", "English", "english"])+def test_english_aliases_resolve_to_en(value: str) -> None:+ assert parse_language(value) == "en"++[email protected]("value", ["zh", "ZH", "cn", "Chinese", "chinese"])+def test_chinese_aliases_resolve_to_zh(value: str) -> None:+ assert parse_language(value) == "zh"+++def test_regional_codes_keep_their_region() -> None:+ assert parse_language("zh-tw") == "zh-tw"+ assert parse_language("pt-BR") == "pt-br"++[email protected]("value", [None, "", " ", 0, 5, ["ja"]])+def test_an_unconfigured_language_still_defaults_to_chinese(value: object) -> None:+ """Deployments that never set a language keep the behaviour they shipped with."""+ assert parse_language(value) == "zh"+++def test_prompt_files_fall_back_to_english_not_chinese() -> None:+ """Only zh/en ship prompt YAML; a language without files must not land on zh,+ or the model is handed Chinese scaffolding for a Japanese answer."""+ assert prompt_file_chain("ja") == ["ja", "en"]+ assert prompt_file_chain("ko") == ["ko", "en"]+++def test_prompt_files_reuse_the_base_locale_for_a_regional_code() -> None:+ assert prompt_file_chain("zh-tw") == ["zh-tw", "zh", "cn", "en"]+++def test_prompt_file_fallbacks_are_unchanged_for_the_two_shipped_locales() -> None:+ assert prompt_file_chain("zh") == ["zh", "cn", "en"]+ assert prompt_file_chain("en") == ["en", "zh", "cn"]