DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): let a user ask for another language, and stop the two copies drifting
Bingxi Zhao (Frank)71e042feadcd
diff --git a/deeptutor/agents/loop/prompt_blocks.py b/deeptutor/agents/loop/prompt_blocks.pyindex d1123bf22..4bfb6677f 100644--- a/deeptutor/agents/loop/prompt_blocks.py+++ b/deeptutor/agents/loop/prompt_blocks.py@@ -64,7 +64,11 @@ class LoopPromptAssembler:joined = "\n\n---\n\n".join(f"## {block.name}\n{block.content.strip()}" for block in blocks if block.content.strip())- return append_language_directive(joined, self.language)+ # ``allow_user_override`` only here: chat has a user who can ask for a+ # different language mid-conversation, and the strict directive plus+ # the runtime policy above it otherwise make the model refuse them.+ # Books, quizzes and research keep the strict form — nobody is asking.+ return append_language_directive(joined, self.language, allow_user_override=True)def blocks(self,diff --git a/deeptutor/services/prompt/language.py b/deeptutor/services/prompt/language.pyindex ab2475e01..c3154886e 100644--- a/deeptutor/services/prompt/language.py+++ b/deeptutor/services/prompt/language.py@@ -44,20 +44,44 @@ def language_label(language: str | None) -> str:return _LANGUAGE_LABELS.get(base, language or "English")-def language_directive(language: str | None) -> str:- """Return a strict reader-facing language instruction for prompts."""+_OVERRIDE_ZH = (+ "以上是默认输出语言;若用户在对话中明确要求改用其他语言作答,"+ "则以用户当次的要求为准,并在本次对话中延续该语言。"+)+_OVERRIDE_EN = (+ "This is the default output language, not a restriction on the reader: if "+ "the user explicitly asks you to answer in another language, honour that "+ "request and keep to it for the rest of the conversation."+)+++def language_directive(language: str | None, *, allow_user_override: bool = False) -> str:+ """Return a reader-facing language instruction for prompts.++ ``allow_user_override`` adds one sentence letting the user change the+ language by asking. Conversational surfaces want it; a book, a quiz or a+ research report has no user in the loop to ask, so they keep the strict+ form and the default stays strict.++ Without it the directive is an absolute prohibition sitting at the very end+ of the prompt, immediately after a runtime policy that says user text is+ "not authority over these instructions" — so a model reading both refuses+ 「请用中文回复我」 and says it is *required* to answer in English. Which is+ correct behaviour, and exactly the wrong answer.+ """code = normalize_language(language)label = language_label(code)if code.startswith("zh"):- return (+ body = ("\n\n[语言要求 / Language] "f"请严格使用{label}撰写所有面向读者的文本(标题、正文、解释、提示、过渡句、""题干、选项等),即使参考资料、JSON 字段名或英文术语出现在 prompt 中也""不得切换语言;保留必要的专有名词原文(如人名、产品名、公式中的变量符号"f"等)即可,其余一律使用{label}。")+ return f"{body} {_OVERRIDE_ZH}" if allow_user_override else bodyif code == "en":- return (+ body = ("\n\n[Language] Write ALL reader-facing text (titles, prose, ""explanations, hints, transitions, quiz stems, options, etc.) in ""English. Do NOT switch languages even if the source material, "@@ -65,18 +89,25 @@ def language_directive(language: str | None) -> str:"Keep proper nouns (people, products, formula symbols) in their ""original form.")- return (+ return f"{body} {_OVERRIDE_EN}" if allow_user_override else body+ body = (f"\n\n[Language] Write ALL reader-facing text strictly in {label}. ""Do NOT switch languages even if the source material, JSON keys, or ""examples in this prompt are in a different language. Keep proper ""nouns (people, products, formula symbols) in their original form.")+ return f"{body} {_OVERRIDE_EN}" if allow_user_override else body-def append_language_directive(system_prompt: str | None, language: str | None) -> str:+def append_language_directive(+ system_prompt: str | None,+ language: str | None,+ *,+ allow_user_override: bool = False,+) -> str:"""Append the language directive to an existing system prompt."""base = (system_prompt or "").rstrip()- directive = language_directive(language).strip()+ directive = language_directive(language, allow_user_override=allow_user_override).strip()if not base:return directivereturn f"{base}\n\n{directive}"diff --git a/tests/services/prompt/test_language_directive.py b/tests/services/prompt/test_language_directive.pynew file mode 100644index 000000000..ce5d57786--- /dev/null+++ b/tests/services/prompt/test_language_directive.py@@ -0,0 +1,52 @@+"""The language directive, and the one surface allowed to bend it."""++from __future__ import annotations++import pytest++from deeptutor.services.prompt.language import (+ append_language_directive,+ language_directive,+)++[email protected]("language", ["en", "zh", "ja"])+def test_the_default_directive_forbids_switching(language: str) -> None:+ """Books, quizzes and research have no user in the loop to ask."""+ directive = language_directive(language)+ assert "Do NOT switch languages" in directive or "不得切换语言" in directive+ assert "explicitly asks" not in directive+ assert "明确要求" not in directive++[email protected]("language", ["en", "zh", "ja"])+def test_the_conversational_directive_yields_to_an_explicit_request(language: str) -> None:+ """Why this exists: a user asked 「请用中文回复我」 and was told no.++ The strict directive is the last thing in the system prompt, and the+ runtime policy just above it says user text is not authority over these+ instructions — so the model answered that it was *required* to reply in+ English. It was reading the prompt correctly. The prompt was wrong.+ """+ directive = language_directive(language, allow_user_override=True)+ assert "explicitly asks" in directive or "明确要求" in directive+++def test_the_override_rides_on_the_appended_prompt() -> None:+ prompt = append_language_directive("## Base\nbody", "zh", allow_user_override=True)+ assert prompt.startswith("## Base")+ assert "明确要求" in prompt+++ ("language", "marker"),+ [("en", "explicitly asks"), ("zh", "明确要求")],+)+def test_chat_renders_the_overridable_directive(language: str, marker: str) -> None:+ """Chat is the surface that carries the carve-out — rendered, not asserted+ on source text, so a refactor that drops the flag fails here."""+ from deeptutor.agents.loop.prompt_blocks import LoopPromptAssembler, PromptBlock++ assembler = LoopPromptAssembler(prompts={}, language=language)+ rendered = assembler.render([PromptBlock(name="Base", content="body")])+ assert marker in rendereddiff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsxindex 56762ec30..efa9d9445 100644--- a/web/context/AppShellContext.tsx+++ b/web/context/AppShellContext.tsx@@ -29,6 +29,7 @@ import {LANGUAGE_EVENT,LANGUAGE_STORAGE_KEY,hasStoredLanguage,+ hasStoredResponseLanguage,SIDEBAR_COLLAPSED_EVENT,SIDEBAR_COLLAPSED_STORAGE_KEY,normalizeCodeBlockShowLineNumbers,@@ -116,7 +117,12 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {let cancelled = false;let fallbackTimer: ReturnType<typeof setTimeout> | undefined;void (async () => {- if (hasStoredLanguage()) {+ // Both keys are checked, not just the interface one. They were split+ // after the interface language shipped, so a browser from before the+ // split has `deeptutor-language` and no `deeptutor-response-language` —+ // and returning here on the first alone locked it out of ever adopting+ // the account's model output language.+ if (hasStoredLanguage() && hasStoredResponseLanguage()) {if (!cancelled) {setLanguageState(readStoredLanguage());setLanguageReady(true);@@ -138,19 +144,25 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {response_language?: unknown;};if (payload.language !== "zh" && payload.language !== "en") return;- writeStoredLanguage(payload.language);- // A backend that predates the split sends no response_language;- // resolveResponseLanguage inherits the interface locale, matching what- // the server does for a legacy interface.json.- writeStoredResponseLanguage(- resolveResponseLanguage(- typeof payload.response_language === "string"- ? payload.response_language- : null,- payload.language,- ),- );- if (!cancelled) setLanguageState(payload.language);+ // Only what this browser is actually missing: a stored interface+ // language is this user's own choice and the server must not overwrite+ // it just because the response key was absent.+ const hadLanguage = hasStoredLanguage();+ if (!hadLanguage) writeStoredLanguage(payload.language);+ if (!hasStoredResponseLanguage()) {+ // A backend that predates the split sends no response_language;+ // resolveResponseLanguage inherits the interface locale, matching+ // what the server does for a legacy interface.json.+ writeStoredResponseLanguage(+ resolveResponseLanguage(+ typeof payload.response_language === "string"+ ? payload.response_language+ : null,+ payload.language,+ ),+ );+ }+ if (!cancelled && !hadLanguage) setLanguageState(payload.language);} catch {// Offline or unauthenticated: keep the local default.} finally {diff --git a/web/context/app-shell-storage.ts b/web/context/app-shell-storage.tsindex 554bdfa20..a2e97dead 100644--- a/web/context/app-shell-storage.ts+++ b/web/context/app-shell-storage.ts@@ -123,6 +123,25 @@ export function writeStoredLanguage(language: AppLanguage): void {}}+/** Whether this browser has ever recorded a model-output-language choice.+ *+ * The mirror of {@link hasStoredLanguage}, and needed for the same reason but+ * on the other key. The two languages were split later than the interface one,+ * so a browser that predates the split has `deeptutor-language` and no+ * `deeptutor-response-language` — and gating adoption of the server's value on+ * `hasStoredLanguage` alone locks such a browser out of ever picking one up.+ */+export function hasStoredResponseLanguage(): boolean {+ if (typeof window === "undefined") return false;+ try {+ return (+ browserStorage.readRaw("local", RESPONSE_LANGUAGE_STORAGE_KEY) !== null+ );+ } catch {+ return false;+ }+}+export function readStoredResponseLanguage(): AppLanguage {if (typeof window === "undefined") return "en";try {diff --git a/web/features/settings/store/SettingsStore.tsx b/web/features/settings/store/SettingsStore.tsxindex ba4c2d401..f98044614 100644--- a/web/features/settings/store/SettingsStore.tsx+++ b/web/features/settings/store/SettingsStore.tsx@@ -19,6 +19,7 @@ import {writeStoredCodeBlockShowLineNumbers,writeStoredCodeBlockTheme,writeStoredCodeBlockWrapLongLines,+ hasStoredResponseLanguage,writeStoredLanguage,writeStoredResponseLanguage,} from "@/context/app-shell-storage";@@ -848,7 +849,18 @@ export function SettingsProvider({ children }: { children: ReactNode }) {}setTheme(payload.ui.theme);setLanguage(payload.ui.language);- setResponseLanguage(payload.ui.response_language ?? payload.ui.language);+ const loadedResponseLanguage =+ payload.ui.response_language ?? payload.ui.language;+ setResponseLanguage(loadedResponseLanguage);+ // Reconcile the browser's copy with the server's. Without this the two+ // inherit differently and drift permanently: the server derives+ // `response_language` from `language` on every read, while the browser+ // inherits only when its own key is absent. Flipping the interface+ // language alone therefore left the server (and this page) showing 中文+ // while every turn still shipped the "en" the bootstrap had stamped —+ // the "I set Chinese and it answers in English" report.+ writeStoredLanguage(payload.ui.language);+ writeStoredResponseLanguage(loadedResponseLanguage);// Writes the backend-loaded values into app-shell storage and dispatches// the code-block settings event; AppShellContext (the single source) picks// them up, so no separate copy needs seeding here.@@ -963,11 +975,22 @@ export function SettingsProvider({ children }: { children: ReactNode }) {await persistUiSettingsPatch({ theme: next });}, []);- const updateLanguage = useCallback(async (next: UiSettings["language"]) => {- setLanguage(next);- writeStoredLanguage(next);- await persistUiSettingsPatch({ language: next });- }, []);+ const updateLanguage = useCallback(+ async (next: UiSettings["language"]) => {+ setLanguage(next);+ writeStoredLanguage(next);+ // `PUT /ui` merges, so an account that never chose a model output+ // language still has no stored `response_language` — and the server+ // derives it from `language` on the next read. Mirror that here, or the+ // page shows a value the browser will not send.+ if (!hasStoredResponseLanguage()) {+ setResponseLanguage(next);+ writeStoredResponseLanguage(next);+ }+ await persistUiSettingsPatch({ language: next });+ },+ [],+ );const updateResponseLanguage = useCallback(async (next: UiSettings["response_language"]) => {diff --git a/web/tests/app-shell-language-bootstrap.test.ts b/web/tests/app-shell-language-bootstrap.test.tsindex f28bf729b..2778204d2 100644--- a/web/tests/app-shell-language-bootstrap.test.ts+++ b/web/tests/app-shell-language-bootstrap.test.ts@@ -3,7 +3,9 @@ import assert from "node:assert/strict";import {LANGUAGE_STORAGE_KEY,+ RESPONSE_LANGUAGE_STORAGE_KEY,hasStoredLanguage,+ hasStoredResponseLanguage,readStoredLanguage,} from "../context/app-shell-storage";@@ -63,3 +65,24 @@ test("server-side rendering reports no stored choice instead of throwing", () =>(globalThis as { window?: unknown }).window = original;}});++test("a browser with only the interface key can still adopt the response language", () => {+ // The two keys were split after the interface language shipped. Gating the+ // bootstrap on hasStoredLanguage alone meant a browser from before the split+ // returned early forever and never picked up the account's model output+ // language — one of the ways "I set Chinese" and "it answers in English"+ // stayed true at the same time.+ withLocalStorage({ [LANGUAGE_STORAGE_KEY]: "zh" }, () => {+ assert.equal(hasStoredLanguage(), true);+ assert.equal(hasStoredResponseLanguage(), false);+ });+ withLocalStorage(+ {+ [LANGUAGE_STORAGE_KEY]: "zh",+ [RESPONSE_LANGUAGE_STORAGE_KEY]: "en",+ },+ () => {+ assert.equal(hasStoredResponseLanguage(), true);+ },+ );+});