mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 04:39:31 +08:00
fix(chat): let a user ask for another language, and stop the two copies drifting
Two defects, either of which alone produces "I set Chinese and it still answers in English". The prompt one explains the quoted refusal. `language_directive` is the last thing in the system prompt and is an absolute prohibition — "Do NOT switch languages" — sitting right after a runtime policy that says user-provided text is not authority over these instructions. Asked 「请用中文回复我」, a compliant model answers that it is *required* to reply in English. It is reading the prompt correctly; the prompt is wrong. Conversational surfaces now pass `allow_user_override=True`, which adds one sentence letting an explicit request win. Books, quizzes and research keep the strict form: there is no user in the loop to ask, and their prompts are full of source material in other languages, which is what the strictness is for. The storage one explains how `en` got there in the first place. The two copies of the preference inherit differently: the server derives `response_language` from `language` on every read, while the browser inherits only when its own key is absent — so once an explicit value is stored the browser can never re-adopt. Flipping only 界面语言 therefore left the server (and the settings page) at zh/zh while every turn still shipped the "en" the bootstrap had stamped. The settings page displayed the right answer and the model gave the wrong one, with nothing broken in between. So `loadSettings` reconciles both keys from the server it just read; `updateLanguage` mirrors the server's inheritance when no explicit output language was ever chosen; and the bootstrap gate splits, because a browser predating the split has the interface key and not the response key, and returning early on the first alone locked it out of ever adopting the account's choice. Adoption writes only the key that is missing, so the server never overwrites a choice the user made in this browser. Not fixed here, and needing more than code reading to settle: whether to make the server authoritative for live turns (it carries a `.lower()`-on-None hazard at executor.py and a stale-preference fallback on regenerate), and that `GET /api/settings/ui` is mounted without auth so it answers from the admin workspace — which lets useSetupSync overwrite a learner's languages in a multi-user deployment. Both are written up for review.
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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 body
|
||||
if 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 directive
|
||||
return f"{base}\n\n{directive}"
|
||||
|
||||
52
tests/services/prompt/test_language_directive.py
Normal file
52
tests/services/prompt/test_language_directive.py
Normal file
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("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 rendered
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"]) => {
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user