DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(prompts): externalize answer_now/notebook prompts to YAML and tidy capability/UI configs
Bingxi Zhao (Frank)5f29b508e073
diff --git a/deeptutor/agents/notebook/analysis_agent.py b/deeptutor/agents/notebook/analysis_agent.pyindex 3df08cae3..5326f79e3 100644--- a/deeptutor/agents/notebook/analysis_agent.py+++ b/deeptutor/agents/notebook/analysis_agent.py@@ -10,6 +10,7 @@ from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, nefrom deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargsfrom deeptutor.services.llm import complete as llm_complete, stream as llm_streamfrom deeptutor.services.llm import stream as llm_stream+from deeptutor.services.prompt.manager import get_prompt_managerfrom deeptutor.utils.json_parser import parse_json_responselogger = logging.getLogger(__name__)@@ -35,6 +36,12 @@ class NotebookAnalysisAgent:self.base_url = getattr(self.llm_config, "base_url", None)self.api_version = getattr(self.llm_config, "api_version", None)self.binding = getattr(self.llm_config, "binding", None) or "openai"+ # Prompts come from deeptutor/agents/notebook/prompts/{en,zh}/analysis_agent.yaml+ # so the three-stage notebook reasoning loop stays bilingual without+ # carrying language-specific text in this file.+ self._prompts = get_prompt_manager().load_prompts(+ "notebook", "analysis_agent", self.language+ )async def analyze(self,@@ -277,58 +284,27 @@ class NotebookAnalysisAgent:))+ def _stage_section(self, stage: str) -> dict[str, Any]:+ section = self._prompts.get(stage)+ return section if isinstance(section, dict) else {}++ def _stage_text(self, stage: str, field: str) -> str:+ section = self._stage_section(stage)+ return str(section.get(field, "")).strip()+def _thinking_system_prompt(self) -> str:- if self.language == "zh":- return (- "你是 DeepTutor 的 notebook thinking 阶段。"- "你会先阅读用户问题与 notebook 摘要列表,判断要从哪些历史记录中提取细节。"- "输出内部思考,不要直接回答用户。"- )- return (- "You are DeepTutor's notebook thinking stage. "- "Review the user question and notebook summaries, then reason about which saved records matter most. "- "Output internal reasoning only, not the final answer."- )+ return self._stage_text("thinking", "system")def _acting_system_prompt(self) -> str:- if self.language == "zh":- return (- "你是 DeepTutor 的 notebook acting 阶段。"- "你必须只输出 JSON:{\"selected_record_ids\": [最多5个id]}。"- "优先选择最能支撑当前问题的记录,避免冗余。"- )- return (- "You are DeepTutor's notebook acting stage. "- 'Output JSON only: {"selected_record_ids": [up to 5 ids]}. '- "Choose the records most useful for the current question."- )+ return self._stage_text("acting", "system")def _observing_system_prompt(self) -> str:- if self.language == "zh":- return (- "你是 DeepTutor 的 notebook observing 阶段。"- "请基于用户问题、thinking、以及选中历史记录的细节,产出一份供后续主能力使用的上下文总结。"- "总结必须结构化、紧凑,并区分已知事实、可复用内容、仍需谨慎的点。"- "不要用第一人称描述内部流程。"- )- return (- "You are DeepTutor's notebook observing stage. "- "Synthesize the user question, the prior reasoning, and the selected record details into a compact context note "- "for the main capability. Distinguish confirmed facts, reusable material, and uncertainties."- )+ return self._stage_text("observing", "system")def _thinking_prompt(self, user_question: str, records: list[dict[str, Any]]) -> str:- catalog = self._summary_catalog(records)- if self.language == "zh":- return (- f"用户问题:\n{user_question.strip() or '(empty)'}\n\n"- f"可用 notebook 摘要:\n{catalog}\n\n"- "请思考:当前问题最需要哪些历史信息?哪些记录可能只需要摘要,哪些必须查看原文细节?"- )- return (- f"User question:\n{user_question.strip() or '(empty)'}\n\n"- f"Available notebook summaries:\n{catalog}\n\n"- "Reason about which saved records matter most and which ones likely require full detail."+ return self._stage_text("thinking", "user_template").format(+ user_question=user_question.strip() or "(empty)",+ catalog=self._summary_catalog(records),)def _acting_prompt(@@ -337,19 +313,10 @@ class NotebookAnalysisAgent:thinking_text: str,records: list[dict[str, Any]],) -> str:- catalog = self._summary_catalog(records)- if self.language == "zh":- return (- f"用户问题:\n{user_question.strip() or '(empty)'}\n\n"- f"[Thinking]\n{thinking_text or '(empty)'}\n\n"- f"可选记录:\n{catalog}\n\n"- "请只返回最值得查看细节的记录 id,最多 5 个。"- )- return (- f"User question:\n{user_question.strip() or '(empty)'}\n\n"- f"[Thinking]\n{thinking_text or '(empty)'}\n\n"- f"Available records:\n{catalog}\n\n"- "Return only the ids of the records whose full details should be inspected, up to 5."+ return self._stage_text("acting", "user_template").format(+ user_question=user_question.strip() or "(empty)",+ thinking_text=thinking_text or "(empty)",+ catalog=self._summary_catalog(records),)def _observing_prompt(@@ -372,20 +339,10 @@ class NotebookAnalysisAgent:for record in selected_records]) or "(none)"- if self.language == "zh":- return (- f"用户问题:\n{user_question.strip() or '(empty)'}\n\n"- f"[Thinking]\n{thinking_text or '(empty)'}\n\n"- f"[Detailed Records]\n{detailed_blocks}\n\n"- "请输出 notebook 分析结论,用于注入后续主能力。"- "建议包含:1. 与当前问题直接相关的历史信息;2. 可复用的结论/草稿/上下文;3. 需要谨慎处理的地方。"- )- return (- f"User question:\n{user_question.strip() or '(empty)'}\n\n"- f"[Thinking]\n{thinking_text or '(empty)'}\n\n"- f"[Detailed Records]\n{detailed_blocks}\n\n"- "Produce the notebook analysis output that will be injected into the main capability. "- "Include directly relevant history, reusable conclusions or drafts, and any caveats."+ return self._stage_text("observing", "user_template").format(+ user_question=user_question.strip() or "(empty)",+ thinking_text=thinking_text or "(empty)",+ detailed_blocks=detailed_blocks,)def _summary_catalog(self, records: list[dict[str, Any]]) -> str:diff --git a/deeptutor/agents/notebook/prompts/en/analysis_agent.yaml b/deeptutor/agents/notebook/prompts/en/analysis_agent.yamlnew file mode 100644index 000000000..499f19354--- /dev/null+++ b/deeptutor/agents/notebook/prompts/en/analysis_agent.yaml@@ -0,0 +1,52 @@+thinking:+ system: |+ You are DeepTutor's notebook thinking stage. Review the user question and+ notebook summaries, then reason about which saved records matter most.+ Output internal reasoning only, not the final answer.+ user_template: |+ User question:+ {user_question}++ Available notebook summaries:+ {catalog}++ Reason about which saved records matter most and which ones likely require+ full detail.++acting:+ system: |+ You are DeepTutor's notebook acting stage.+ Output JSON only: {{"selected_record_ids": [up to 5 ids]}}.+ Choose the records most useful for the current question.+ user_template: |+ User question:+ {user_question}++ [Thinking]+ {thinking_text}++ Available records:+ {catalog}++ Return only the ids of the records whose full details should be inspected,+ up to 5.++observing:+ system: |+ You are DeepTutor's notebook observing stage. Synthesize the user question,+ the prior reasoning, and the selected record details into a compact context+ note for the main capability. Distinguish confirmed facts, reusable+ material, and uncertainties.+ user_template: |+ User question:+ {user_question}++ [Thinking]+ {thinking_text}++ [Detailed Records]+ {detailed_blocks}++ Produce the notebook analysis output that will be injected into the main+ capability. Include directly relevant history, reusable conclusions or+ drafts, and any caveats.diff --git a/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml b/deeptutor/agents/notebook/prompts/en/summarize_agent.yamlnew file mode 100644index 000000000..0c3406b43--- /dev/null+++ b/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml@@ -0,0 +1,27 @@+system: |+ You are DeepTutor's notebook summary agent. Compress a saved record into a+ concise, retrieval-friendly summary for future reuse. Focus on topic, key+ conclusions, use cases, and why this record matters. Output only the summary+ text with no heading or bullets.++user_template: |+ Record type: {record_type}+ Type hint: {record_hint}+ Title: {title}+ User input:+ {user_query}++ Saved content:+ {output}++ Metadata: {metadata}++ Write an 80-180 word summary. Focus on the topic, key information, current+ completion state, and what makes this record useful for future reuse.++# Per-record-type hints injected into `user_template` as `{record_hint}`.+record_hints:+ chat: "A full chat transcript; focus on the question, conclusion, and next actions."+ co_writer: "A writing draft; focus on theme, structure, current completeness, and expansion paths."+ guided_learning: "A guided learning record; focus on topic, knowledge structure, and partial/final output."+ default: "Summarize the most reusable information in this record."diff --git a/deeptutor/agents/notebook/prompts/zh/analysis_agent.yaml b/deeptutor/agents/notebook/prompts/zh/analysis_agent.yamlnew file mode 100644index 000000000..a61937781--- /dev/null+++ b/deeptutor/agents/notebook/prompts/zh/analysis_agent.yaml@@ -0,0 +1,51 @@+thinking:+ system: |+ 你是 DeepTutor 的 notebook thinking 阶段。+ 你会先阅读用户问题与 notebook 摘要列表,判断要从哪些历史记录中提取细节。+ 输出内部思考,不要直接回答用户。+ user_template: |+ 用户问题:+ {user_question}++ 可用 notebook 摘要:+ {catalog}++ 请思考:当前问题最需要哪些历史信息?哪些记录可能只需要摘要,哪些必须查看+ 原文细节?++acting:+ system: |+ 你是 DeepTutor 的 notebook acting 阶段。+ 你必须只输出 JSON:{{"selected_record_ids": [最多5个id]}}。+ 优先选择最能支撑当前问题的记录,避免冗余。+ user_template: |+ 用户问题:+ {user_question}++ [Thinking]+ {thinking_text}++ 可选记录:+ {catalog}++ 请只返回最值得查看细节的记录 id,最多 5 个。++observing:+ system: |+ 你是 DeepTutor 的 notebook observing 阶段。+ 请基于用户问题、thinking、以及选中历史记录的细节,产出一份供后续主能力使用的+ 上下文总结。总结必须结构化、紧凑,并区分已知事实、可复用内容、仍需谨慎的点。+ 不要用第一人称描述内部流程。+ user_template: |+ 用户问题:+ {user_question}++ [Thinking]+ {thinking_text}++ [Detailed Records]+ {detailed_blocks}++ 请输出 notebook 分析结论,用于注入后续主能力。+ 建议包含:1. 与当前问题直接相关的历史信息;2. 可复用的结论/草稿/上下文;+ 3. 需要谨慎处理的地方。diff --git a/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml b/deeptutor/agents/notebook/prompts/zh/summarize_agent.yamlnew file mode 100644index 000000000..42bc95040--- /dev/null+++ b/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml@@ -0,0 +1,28 @@+system: |+ 你是 DeepTutor 的 notebook summary agent。请把一条待保存内容提炼成简洁、可检索、+ 面向未来复用的摘要。摘要必须突出主题、关键结论、适用场景和保存价值。+ 只输出摘要正文,不要加标题、前缀或项目符号。++user_template: |+ 记录类型:{record_type}+ 类型提示:{record_hint}+ 标题:{title}+ 用户输入:+ {user_query}++ 保存内容:+ {output}++ 元数据:{metadata}++ 请输出 80-180 字的中文摘要。要求:+ 1. 优先概括知识主题与关键信息;+ 2. 如果内容是草稿或中间过程,要说明当前完成度;+ 3. 如果内容适合后续复用,要点明可复用角度。++# 各记录类型的提示语,会被注入到 user_template 的 {record_hint}。+record_hints:+ chat: "一段完整聊天历史,重点提炼问题、结论与后续行动。"+ co_writer: "一份写作草稿,重点提炼主题、结构、当前完成度与可继续扩展方向。"+ guided_learning: "一段引导式学习记录,重点提炼学习主题、知识点结构与阶段性产出。"+ default: "请总结此记录中最值得复用的信息。"diff --git a/deeptutor/agents/notebook/summarize_agent.py b/deeptutor/agents/notebook/summarize_agent.pyindex d5a4d260e..e6d7e8743 100644--- a/deeptutor/agents/notebook/summarize_agent.py+++ b/deeptutor/agents/notebook/summarize_agent.py@@ -6,6 +6,7 @@ from typing import AsyncGeneratorfrom deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargsfrom deeptutor.services.llm import stream as llm_stream+from deeptutor.services.prompt.manager import get_prompt_managerdef _clip_text(value: str, limit: int) -> str:@@ -27,6 +28,12 @@ class NotebookSummarizeAgent:self.api_version = getattr(self.llm_config, "api_version", None)self.binding = getattr(self.llm_config, "binding", None) or "openai"self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}+ # Prompts live under deeptutor/agents/notebook/prompts/{en,zh}/summarize_agent.yaml+ # so the notebook summarizer follows the same bilingual convention as+ # the rest of the agents and never hard-codes prompt strings here.+ self._prompts = get_prompt_manager().load_prompts(+ "notebook", "summarize_agent", self.language+ )async def summarize(self,@@ -86,19 +93,7 @@ class NotebookSummarizeAgent:yield chunkdef _system_prompt(self) -> str:- if self.language == "zh":- return (- "你是 DeepTutor 的 notebook summary agent。"- "请把一条待保存内容提炼成简洁、可检索、面向未来复用的摘要。"- "摘要必须突出主题、关键结论、适用场景和保存价值。"- "只输出摘要正文,不要加标题、前缀或项目符号。"- )- return (- "You are DeepTutor's notebook summary agent. "- "Compress a saved record into a concise, retrieval-friendly summary for future reuse. "- "Focus on topic, key conclusions, use cases, and why this record matters. "- "Output only the summary text with no heading or bullets."- )+ return str(self._prompts.get("system", "")).strip()def _build_user_prompt(self,@@ -111,46 +106,21 @@ class NotebookSummarizeAgent:) -> str:clipped_query = _clip_text(user_query, 1200) or "(empty)"clipped_output = _clip_text(output, 6000) or "(empty)"- clipped_metadata = _clip_text(str(metadata or {}), 1000)- record_hint = self._record_hint(record_type)- if self.language == "zh":- return (- f"记录类型:{record_type}\n"- f"类型提示:{record_hint}\n"- f"标题:{title or '(untitled)'}\n"- f"用户输入:\n{clipped_query}\n\n"- f"保存内容:\n{clipped_output}\n\n"- f"元数据:{clipped_metadata or '(none)'}\n\n"- "请输出 80-180 字的中文摘要。要求:"- "1. 优先概括知识主题与关键信息;"- "2. 如果内容是草稿或中间过程,要说明当前完成度;"- "3. 如果内容适合后续复用,要点明可复用角度。"- )- return (- f"Record type: {record_type}\n"- f"Type hint: {record_hint}\n"- f"Title: {title or '(untitled)'}\n"- f"User input:\n{clipped_query}\n\n"- f"Saved content:\n{clipped_output}\n\n"- f"Metadata: {clipped_metadata or '(none)'}\n\n"- "Write an 80-180 word summary. Focus on the topic, key information, current completion state, "- "and what makes this record useful for future reuse."+ clipped_metadata = _clip_text(str(metadata or {}), 1000) or "(none)"+ template = str(self._prompts.get("user_template", "")).strip()+ return template.format(+ record_type=record_type,+ record_hint=self._record_hint(record_type),+ title=title or "(untitled)",+ user_query=clipped_query,+ output=clipped_output,+ metadata=clipped_metadata,)def _record_hint(self, record_type: str) -> str:- hints = {- "chat": {- "zh": "一段完整聊天历史,重点提炼问题、结论与后续行动。",- "en": "A full chat transcript; focus on the question, conclusion, and next actions.",- },- "co_writer": {- "zh": "一份写作草稿,重点提炼主题、结构、当前完成度与可继续扩展方向。",- "en": "A writing draft; focus on theme, structure, current completeness, and expansion paths.",- },- "guided_learning": {- "zh": "一段引导式学习记录,重点提炼学习主题、知识点结构与阶段性产出。",- "en": "A guided learning record; focus on topic, knowledge structure, and partial/final output.",- },- }- localized = hints.get(record_type, {})- return localized.get(self.language, "Summarize the most reusable information in this record.")+ hints = self._prompts.get("record_hints") or {}+ if not isinstance(hints, dict):+ hints = {}+ if record_type in hints:+ return str(hints[record_type])+ return str(hints.get("default", ""))diff --git a/deeptutor/agents/question/prompts/en/answer_now.yaml b/deeptutor/agents/question/prompts/en/answer_now.yamlnew file mode 100644index 000000000..cd17ab3f8--- /dev/null+++ b/deeptutor/agents/question/prompts/en/answer_now.yaml@@ -0,0 +1,21 @@+system: |+ You are DeepTutor's question generator. The user is waiting, so produce+ a complete question set in one shot using the context already gathered.+ Output strictly the JSON schema {"questions": [{"question_id": "q_1",+ "question": "...", "question_type": "choice|written|coding", "options":+ {"A": "..."}, "correct_answer": "...", "explanation": "...", "difficulty":+ "...", "concentration": "..."}, ...]}. Omit ``options`` when the type is+ not ``choice``.++user_template: |+ Topic: {topic}++ Number of questions requested: {num_questions}+ Preferred type: {question_type} (auto = free choice)+ Preferred difficulty: {difficulty}++ {current_draft}++ {execution_trace}++ Emit the JSON object now, no surrounding prose.diff --git a/deeptutor/agents/question/prompts/zh/answer_now.yaml b/deeptutor/agents/question/prompts/zh/answer_now.yamlnew file mode 100644index 000000000..9cd0bdbbe--- /dev/null+++ b/deeptutor/agents/question/prompts/zh/answer_now.yaml@@ -0,0 +1,21 @@+system: |+ 你是 DeepTutor 的题目生成器。用户已经在等待,请基于现有信息直接输出一组题目。+ 严格输出 JSON:{"questions": [{"question_id": "q_1",+ "question": "...", "question_type": "choice|written|coding",+ "options": {"A": "..."}, "correct_answer": "...",+ "explanation": "...", "difficulty": "...",+ "concentration": "..."}, ...]}。+ 若不是 choice 题,options 字段可省略。所有字符串使用 UTF-8。++user_template: |+ 用户原始问题/主题:{topic}++ 题量要求:{num_questions}+ 题型偏好:{question_type}(auto 表示自由选择)+ 难度偏好:{difficulty}++ {current_draft}++ {execution_trace}++ 立即输出符合上述 JSON schema 的题目集合,不要包含其他文字。diff --git a/deeptutor/agents/research/prompts/en/answer_now.yaml b/deeptutor/agents/research/prompts/en/answer_now.yamlnew file mode 100644index 000000000..be475d6f1--- /dev/null+++ b/deeptutor/agents/research/prompts/en/answer_now.yaml@@ -0,0 +1,16 @@+system: |+ You are DeepTutor's research-report writer. The user is waiting, so+ produce a structured research report right now from whatever evidence+ has streamed so far (rephrase, decompose, search hits, notes/outline,+ ...). Do not retrieve more evidence and do not call tools. If coverage+ is thin, say so explicitly in the report. Use Markdown with: 1) intro,+ 2) body sections (one per identifiable subtopic), 3) conclusion.++user_template: |+ Research topic: {original}++ {current_draft}++ {research_trace}++ Produce the final research report from this material now.diff --git a/deeptutor/agents/research/prompts/zh/answer_now.yaml b/deeptutor/agents/research/prompts/zh/answer_now.yamlnew file mode 100644index 000000000..85bb91669--- /dev/null+++ b/deeptutor/agents/research/prompts/zh/answer_now.yaml@@ -0,0 +1,15 @@+system: |+ 你是 DeepTutor 的研究报告写作组件。用户已经在等待,+ 请根据当前已经收集到的研究 trace(包括 rephrase、decompose、检索结果、+ 笔记/纲要等)直接输出一篇结构清晰的研究报告。+ 不要再继续检索或调用工具。如果证据稀薄,请在报告中标注信息覆盖度。+ 使用 Markdown,包含 1) 引言、2) 主体小节(按你能识别的子主题)、3) 结论。++user_template: |+ 研究主题:{original}++ {current_draft}++ {research_trace}++ 请基于以上材料立即输出最终报告。diff --git a/deeptutor/agents/solve/prompts/en/answer_now.yaml b/deeptutor/agents/solve/prompts/en/answer_now.yamlnew file mode 100644index 000000000..b2e25269a--- /dev/null+++ b/deeptutor/agents/solve/prompts/en/answer_now.yaml@@ -0,0 +1,17 @@+system: |+ You are the writer component of DeepTutor. The user is already waiting,+ so produce the final user-facing answer right now using only the partial+ reasoning trace that has streamed so far. Do not plan further or call+ tools, and do not mention internal stages. If something is still+ uncertain, acknowledge it briefly while still giving the most useful+ answer you can.++user_template: |+ Original user request:+ {original}++ {current_draft}++ {execution_trace}++ Produce the final user-facing answer using only this context.diff --git a/deeptutor/agents/solve/prompts/zh/answer_now.yaml b/deeptutor/agents/solve/prompts/zh/answer_now.yamlnew file mode 100644index 000000000..385244595--- /dev/null+++ b/deeptutor/agents/solve/prompts/zh/answer_now.yaml@@ -0,0 +1,15 @@+system: |+ 你是 DeepTutor 的写作组件。用户已经在等待,+ 你必须基于当前已经收集到的推理与工具调用轨迹直接输出最终答复。+ 不要再做新的规划或调用工具,不要提到内部阶段。+ 如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能给出当前最有用的回答。++user_template: |+ 用户原始问题:+ {original}++ {current_draft}++ {execution_trace}++ 请基于以上材料立即生成给用户的最终回答。diff --git a/deeptutor/agents/visualize/prompts/en/answer_now.yaml b/deeptutor/agents/visualize/prompts/en/answer_now.yamlnew file mode 100644index 000000000..e762f74ce--- /dev/null+++ b/deeptutor/agents/visualize/prompts/en/answer_now.yaml@@ -0,0 +1,16 @@+system: |+ You are DeepTutor's visualization code generator. The user is waiting,+ so emit the final renderable code in one shot. Output strictly the JSON+ {"render_type": "svg|chartjs|mermaid", "code": "..."}, where ``code`` is+ the renderable source (SVG markup, Chart.js JS, or Mermaid DSL).++user_template: |+ User request: {original}++ render_mode hint: {render_mode}++ {current_draft}++ {execution_trace}++ Emit the JSON now.diff --git a/deeptutor/agents/visualize/prompts/zh/answer_now.yaml b/deeptutor/agents/visualize/prompts/zh/answer_now.yamlnew file mode 100644index 000000000..05c9f8c6e--- /dev/null+++ b/deeptutor/agents/visualize/prompts/zh/answer_now.yaml@@ -0,0 +1,17 @@+system: |+ 你是 DeepTutor 的可视化代码生成器。用户已经在等待,+ 请直接输出最终可渲染的代码。+ 严格输出 JSON:{"render_type": "svg|chartjs|mermaid",+ "code": "..."}。+ code 字段是可直接渲染的源代码(SVG 标签 / Chart.js JS 代码 / Mermaid 文本)。++user_template: |+ 用户请求:{original}++ render_mode:{render_mode}++ {current_draft}++ {execution_trace}++ 立即输出符合 schema 的 JSON。diff --git a/deeptutor/capabilities/_answer_now.py b/deeptutor/capabilities/_answer_now.pyindex 2bd31126c..f28f45c3b 100644--- a/deeptutor/capabilities/_answer_now.py+++ b/deeptutor/capabilities/_answer_now.py@@ -37,6 +37,7 @@ from deeptutor.services.llm import (get_token_limit_kwargs,stream as llm_stream,)+from deeptutor.services.prompt.manager import get_prompt_manager# Per-event content cap. The trace can grow unbounded (especially for@@ -238,12 +239,26 @@ def join_chunks(chunks: list[str]) -> str:return clean_thinking_tags(text, binding, model)+def load_answer_now_prompts(module: str, language: str) -> dict[str, Any]:+ """Load the bilingual ``answer_now.yaml`` prompts for a capability.++ All capability fast paths share the same payload contract+ (``original``, ``current_draft``, ``execution_trace``); each one only+ differs in tone and JSON schema. Centralizing the loader keeps+ ``deeptutor/capabilities/*.py`` free of any per-language strings — the+ Python code only formats the user template with capability-specific+ variables.+ """+ return get_prompt_manager().load_prompts(module, "answer_now", language)++__all__ = ["build_answer_now_trace_metadata","extract_answer_now_context","format_trace_summary","join_chunks","labeled_block",+ "load_answer_now_prompts","make_skip_notice","stream_synthesis",]diff --git a/deeptutor/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.pyindex df8a1ca0b..69ab0434b 100644--- a/deeptutor/capabilities/deep_question.py+++ b/deeptutor/capabilities/deep_question.py@@ -215,11 +215,11 @@ class DeepQuestionCapability(BaseCapability):format_trace_summary,join_chunks,labeled_block,+ load_answer_now_prompts,make_skip_notice,stream_synthesis,)- is_zh = context.language.lower().startswith("zh")original = str(payload.get("original_user_message") or context.user_message).strip()partial = str(payload.get("partial_response") or "").strip()trace_summary = format_trace_summary(payload.get("events"), language=context.language)@@ -230,46 +230,16 @@ class DeepQuestionCapability(BaseCapability):difficulty = str(overrides.get("difficulty", "") or "auto")question_type = str(overrides.get("question_type", "") or "auto")- if is_zh:- system_prompt = (- "你是 DeepTutor 的题目生成器。用户已经在等待,请基于现有信息直接输出一组题目。"- "严格输出 JSON:{\"questions\": [{\"question_id\": \"q_1\", "- "\"question\": \"...\", \"question_type\": \"choice|written|coding\", "- "\"options\": {\"A\": \"...\"}, \"correct_answer\": \"...\", "- "\"explanation\": \"...\", \"difficulty\": \"...\", "- "\"concentration\": \"...\"}, ...]}。"- "若不是 choice 题,options 字段可省略。所有字符串使用 UTF-8。"- )- user_prompt = (- f"用户原始问题/主题:{topic}\n\n"- f"题量要求:{num_questions}\n"- f"题型偏好:{question_type}(auto 表示自由选择)\n"- f"难度偏好:{difficulty}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Execution Trace', trace_summary)}\n\n"- "立即输出符合上述 JSON schema 的题目集合,不要包含其他文字。"- )- else:- system_prompt = (- "You are DeepTutor's question generator. The user is waiting, "- "so produce a complete question set in one shot using the "- "context already gathered. Output strictly the JSON schema "- "{\"questions\": [{\"question_id\": \"q_1\", \"question\": "- "\"...\", \"question_type\": \"choice|written|coding\", "- "\"options\": {\"A\": \"...\"}, \"correct_answer\": \"...\", "- "\"explanation\": \"...\", \"difficulty\": \"...\", "- "\"concentration\": \"...\"}, ...]}. Omit ``options`` when the "- "type is not ``choice``."- )- user_prompt = (- f"Topic: {topic}\n\n"- f"Number of questions requested: {num_questions}\n"- f"Preferred type: {question_type} (auto = free choice)\n"- f"Preferred difficulty: {difficulty}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Execution Trace', trace_summary)}\n\n"- "Emit the JSON object now, no surrounding prose."- )+ prompts = load_answer_now_prompts("question", context.language)+ system_prompt = str(prompts.get("system", "")).strip()+ user_prompt = str(prompts.get("user_template", "")).format(+ topic=topic,+ num_questions=num_questions,+ question_type=question_type,+ difficulty=difficulty,+ current_draft=labeled_block("Current Draft", partial),+ execution_trace=labeled_block("Execution Trace", trace_summary),+ )trace_meta = build_answer_now_trace_metadata(capability=self.name, phase="generation", label="Answer now"diff --git a/deeptutor/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.pyindex 928ebfba2..340952f10 100644--- a/deeptutor/capabilities/deep_research.py+++ b/deeptutor/capabilities/deep_research.py@@ -398,45 +398,22 @@ class DeepResearchCapability(BaseCapability):format_trace_summary,join_chunks,labeled_block,+ load_answer_now_prompts,make_skip_notice,stream_synthesis,)- is_zh = context.language.lower().startswith("zh")original = str(payload.get("original_user_message") or context.user_message).strip()partial = str(payload.get("partial_response") or "").strip()trace_summary = format_trace_summary(payload.get("events"), language=context.language)- if is_zh:- system_prompt = (- "你是 DeepTutor 的研究报告写作组件。用户已经在等待,"- "请根据当前已经收集到的研究 trace(包括 rephrase、decompose、检索结果、"- "笔记/纲要等)直接输出一篇结构清晰的研究报告。"- "不要再继续检索或调用工具。如果证据稀薄,请在报告中标注信息覆盖度。"- "使用 Markdown,包含 1) 引言、2) 主体小节(按你能识别的子主题)、3) 结论。"- )- user_prompt = (- f"研究主题:{original}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Research Trace', trace_summary)}\n\n"- "请基于以上材料立即输出最终报告。"- )- else:- system_prompt = (- "You are DeepTutor's research-report writer. The user is "- "waiting, so produce a structured research report right now "- "from whatever evidence has streamed so far (rephrase, "- "decompose, search hits, notes/outline, ...). Do not retrieve "- "more evidence and do not call tools. If coverage is thin, "- "say so explicitly in the report. Use Markdown with: 1) intro, "- "2) body sections (one per identifiable subtopic), 3) conclusion."- )- user_prompt = (- f"Research topic: {original}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Research Trace', trace_summary)}\n\n"- "Produce the final research report from this material now."- )+ prompts = load_answer_now_prompts("research", context.language)+ system_prompt = str(prompts.get("system", "")).strip()+ user_prompt = str(prompts.get("user_template", "")).format(+ original=original,+ current_draft=labeled_block("Current Draft", partial),+ research_trace=labeled_block("Research Trace", trace_summary),+ )trace_meta = build_answer_now_trace_metadata(capability=self.name, phase="reporting", label="Answer now"diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.pyindex 423591b50..342b97ced 100644--- a/deeptutor/capabilities/deep_solve.py+++ b/deeptutor/capabilities/deep_solve.py@@ -309,46 +309,23 @@ class DeepSolveCapability(BaseCapability):format_trace_summary,join_chunks,labeled_block,+ load_answer_now_prompts,make_skip_notice,stream_synthesis,)- is_zh = context.language.lower().startswith("zh")original = str(payload.get("original_user_message") or context.user_message).strip()partial = str(payload.get("partial_response") or "").strip()trace_summary = format_trace_summary(payload.get("events"), language=context.language)- if is_zh:- system_prompt = (- "你是 DeepTutor 的写作组件。用户已经在等待,"- "你必须基于当前已经收集到的推理与工具调用轨迹直接输出最终答复。"- "不要再做新的规划或调用工具,不要提到内部阶段。"- "如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能给出当前最有用的回答。"- )- user_prompt = (- f"用户原始问题:\n{original}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Execution Trace', trace_summary)}\n\n"- "请基于以上材料立即生成给用户的最终回答。"- )- notice_label = "Writing"- else:- system_prompt = (- "You are the writer component of DeepTutor. The user is "- "already waiting, so produce the final user-facing answer "- "right now using only the partial reasoning trace that has "- "streamed so far. Do not plan further or call tools, and do "- "not mention internal stages. If something is still uncertain, "- "acknowledge it briefly while still giving the most useful "- "answer you can."- )- user_prompt = (- f"Original user request:\n{original}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Execution Trace', trace_summary)}\n\n"- "Produce the final user-facing answer using only this context."- )- notice_label = "Writing"+ prompts = load_answer_now_prompts("solve", context.language)+ system_prompt = str(prompts.get("system", "")).strip()+ user_prompt = str(prompts.get("user_template", "")).format(+ original=original,+ current_draft=labeled_block("Current Draft", partial),+ execution_trace=labeled_block("Execution Trace", trace_summary),+ )+ notice_label = "Writing"trace_meta = build_answer_now_trace_metadata(capability=self.name, phase="writing", label="Answer now"diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.pyindex f962ae698..5f8dded1c 100644--- a/deeptutor/capabilities/visualize.py+++ b/deeptutor/capabilities/visualize.py@@ -160,11 +160,11 @@ class VisualizeCapability(BaseCapability):format_trace_summary,join_chunks,labeled_block,+ load_answer_now_prompts,make_skip_notice,stream_synthesis,)- is_zh = context.language.lower().startswith("zh")original = str(payload.get("original_user_message") or context.user_message).strip()partial = str(payload.get("partial_response") or "").strip()trace_summary = format_trace_summary(payload.get("events"), language=context.language)@@ -173,37 +173,14 @@ class VisualizeCapability(BaseCapability):context.config_overrides.get("render_mode", "auto") or "auto").strip().lower()- if is_zh:- system_prompt = (- "你是 DeepTutor 的可视化代码生成器。用户已经在等待,"- "请直接输出最终可渲染的代码。"- "严格输出 JSON:{\"render_type\": \"svg|chartjs|mermaid\", "- "\"code\": \"...\"}。"- "code 字段是可直接渲染的源代码(SVG 标签 / Chart.js JS 代码 / Mermaid 文本)。"- )- user_prompt = (- f"用户请求:{original}\n\n"- f"render_mode:{render_mode}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Execution Trace', trace_summary)}\n\n"- "立即输出符合 schema 的 JSON。"- )- else:- system_prompt = (- "You are DeepTutor's visualization code generator. The user "- "is waiting, so emit the final renderable code in one shot. "- "Output strictly the JSON {\"render_type\": "- "\"svg|chartjs|mermaid\", \"code\": \"...\"}, where ``code`` "- "is the renderable source (SVG markup, Chart.js JS, or "- "Mermaid DSL)."- )- user_prompt = (- f"User request: {original}\n\n"- f"render_mode hint: {render_mode}\n\n"- f"{labeled_block('Current Draft', partial)}\n\n"- f"{labeled_block('Execution Trace', trace_summary)}\n\n"- "Emit the JSON now."- )+ prompts = load_answer_now_prompts("visualize", context.language)+ system_prompt = str(prompts.get("system", "")).strip()+ user_prompt = str(prompts.get("user_template", "")).format(+ original=original,+ render_mode=render_mode,+ current_draft=labeled_block("Current Draft", partial),+ execution_trace=labeled_block("Execution Trace", trace_summary),+ )trace_meta = build_answer_now_trace_metadata(capability=self.name, phase="generating", label="Answer now"diff --git a/deeptutor/services/prompt/manager.py b/deeptutor/services/prompt/manager.pyindex c1820554a..7c355d5d9 100644--- a/deeptutor/services/prompt/manager.py+++ b/deeptutor/services/prompt/manager.py@@ -25,7 +25,17 @@ class PromptManager:}# Supported modules- MODULES = ["research", "solve", "guide", "question", "co_writer", "math_animator"]+ MODULES = [+ "research",+ "solve",+ "guide",+ "question",+ "co_writer",+ "math_animator",+ "notebook",+ "visualize",+ "chat",+ ]# Modules that are not under deeptutor/agents/ directoryNON_AGENT_MODULES: dict[str, str] = {}diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxindex b31024ddc..9c0de9c7b 100644--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@ -895,7 +895,7 @@ function SettingsPageContent() {: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}>- {v === "en" ? "English" : "中文"}+ {v === "en" ? t("language.english") : t("language.chinese")}</button>))}</div>diff --git a/web/components/Mermaid.tsx b/web/components/Mermaid.tsxindex 5285a4929..054631b88 100644--- a/web/components/Mermaid.tsx+++ b/web/components/Mermaid.tsx@@ -91,7 +91,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {} catch (err) {cleanupMermaidOrphans(id);if (!cancelled) {- setError(err instanceof Error ? err.message : "Failed to render diagram");+ setError(err instanceof Error ? err.message : t("Failed to render diagram"));}}};@@ -100,7 +100,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {return () => {cancelled = true;};- }, [stable, chart, id]);+ }, [stable, chart, id, t]);if (error) {return (diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex ffa13de92..3608068a8 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -57,7 +57,9 @@ interface NotebookReferenceGroup {count: number;}-function getModeBadgeLabel(capability?: string | null) {+// Returns the i18n key (and a sensible fallback) for the capability badge+// shown above the user's message. Callers must run `t(...)` on the result.+function getModeBadgeLabel(capability?: string | null): string {if (!capability || capability === "chat") return "Chat";if (capability === "deep_solve") return "Deep Solve";if (capability === "deep_question") return "Quiz Generation";@@ -196,6 +198,7 @@ const AnswerNowRow = memo(function AnswerNowRow({AnswerNowRow.displayName = "AnswerNowRow";function CostFooter({ cost, tokens, calls }: { cost: number; tokens: number; calls: number }) {+ const { t } = useTranslation();const formatCost = (usd: number) => {if (usd < 0.01) return `$${usd.toFixed(4)}`;return `$${usd.toFixed(2)}`;@@ -209,9 +212,9 @@ function CostFooter({ cost, tokens, calls }: { cost: number; tokens: number; cal<Coins size={10} strokeWidth={1.5} className="shrink-0" /><span>{formatCost(cost)}</span><span className="opacity-40">·</span>- <span>{formatTokens(tokens)} tokens</span>+ <span>{formatTokens(tokens)} {t("tokens")}</span><span className="opacity-40">·</span>- <span>{calls} calls</span>+ <span>{calls} {t("calls")}</span></div>);}@@ -255,7 +258,7 @@ const UserMessage = memo(function UserMessage({<div className="max-w-[75%] space-y-1.5"><div className="flex justify-end pr-1"><span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">- {getModeBadgeLabel(msg.capability)}+ {t(getModeBadgeLabel(msg.capability))}</span></div>{msg.attachments?.some((a) => a.type === "image") && (@@ -500,13 +503,13 @@ export const ChatMessageList = memo(function ChatMessageList({<div className="flex gap-2"><RoughActionButtonicon={Copy}- label="Copy"+ label={t("Copy")}onClick={() => void onCopyAssistantMessage(msg.content)}/>{showRetry && (<RoughActionButtonicon={RotateCcw}- label="Retry"+ label={t("Retry")}onClick={() => onRetryMessage(pairedUserMessage?.requestSnapshot)}/>)}diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsxindex 1ffbe2f30..da53c77ee 100644--- a/web/components/chat/home/TracePanels.tsx+++ b/web/components/chat/home/TracePanels.tsx@@ -35,18 +35,42 @@ type TraceMetadata = {sources?: Array<Record<string, unknown>>;};+type ResearchStageId = "understand" | "decompose" | "evidence" | "result";+type ResearchStageCard = {- id: "understand" | "decompose" | "evidence" | "result";+ id: ResearchStageId;title: string;hint: string;events: StreamEvent[];};-const RESEARCH_STAGE_SPECS: Array<Pick<ResearchStageCard, "id" | "title" | "hint">> = [- { id: "understand", title: "理解问题", hint: "先澄清主题与研究目标。" },- { id: "decompose", title: "拆解主题", hint: "把问题拆成可检索、可学习的子主题。" },- { id: "evidence", title: "检索证据", hint: "结合所选 sources 收集和整理证据。" },- { id: "result", title: "形成结果", hint: "把证据整理成最终输出。" },+// `title` and `hint` are i18n keys resolved via `t(...)` at render time so the+// stage banner follows the active UI language instead of being locked to one.+const RESEARCH_STAGE_SPECS: Array<{+ id: ResearchStageId;+ titleKey: string;+ hintKey: string;+}> = [+ {+ id: "understand",+ titleKey: "research.stage.understand.title",+ hintKey: "research.stage.understand.hint",+ },+ {+ id: "decompose",+ titleKey: "research.stage.decompose.title",+ hintKey: "research.stage.decompose.hint",+ },+ {+ id: "evidence",+ titleKey: "research.stage.evidence.title",+ hintKey: "research.stage.evidence.hint",+ },+ {+ id: "result",+ titleKey: "research.stage.result.title",+ hintKey: "research.stage.result.hint",+ },];type TraceItem = { callId: string; events: StreamEvent[] };@@ -62,21 +86,23 @@ function titleCase(value: string) {return value.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());}-function humanizeQuestionId(value: string) {- return value.replace(/\bq_(\d+)\b/gi, "Question $1");+function humanizeQuestionId(value: string, t?: (key: string, opts?: Record<string, unknown>) => string) {+ return value.replace(/\bq_(\d+)\b/gi, (_match, n) =>+ t ? t("Question {{n}}", { n }) : `Question ${n}`,+ );}export function getTraceMeta(event: StreamEvent): TraceMetadata {return (event.metadata ?? {}) as TraceMetadata;}-function getTraceLabel(events: StreamEvent[]) {+function getTraceLabel(events: StreamEvent[], t?: (key: string, opts?: Record<string, unknown>) => string) {for (const event of events) {const meta = getTraceMeta(event);- if (meta.label) return humanizeQuestionId(String(meta.label));+ if (meta.label) return humanizeQuestionId(String(meta.label), t);}const fallback = events[0]?.stage || "trace";- return humanizeQuestionId(titleCase(fallback));+ return humanizeQuestionId(titleCase(fallback), t);}function getTraceCallKind(events: StreamEvent[]) {@@ -141,8 +167,13 @@ function isTracePending(events: StreamEvent[]) {return hasRunning && !hasTerminal;}-function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: boolean, t: (key: string) => string = (k) => k) {- const label = getTraceLabel(events);+function getTraceHeader(+ events: StreamEvent[],+ nowSeconds?: number,+ nested?: boolean,+ t: (key: string, opts?: Record<string, unknown>) => string = (k) => k,+) {+ const label = getTraceLabel(events, t);const role = getTraceRole(events);const group = getTraceGroup(events);const kind = getTraceCallKind(events);@@ -170,10 +201,10 @@ function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: bootitle = t("Tool call");} else if (group === "react_round") {if (nested) {- title = meta.round ? `Round ${meta.round}` : label;+ title = meta.round ? t("Round {{n}}", { n: meta.round }) : label;} else {- const step = meta.step_id ? `Step ${meta.step_id}` : "";- const round = meta.round ? `Round ${meta.round}` : label;+ const step = meta.step_id ? t("Step {{n}}", { n: meta.step_id }) : "";+ const round = meta.round ? t("Round {{n}}", { n: meta.round }) : label;title = [step, round].filter(Boolean).join(" · ");}} else if (role === "plan" && kind === "llm_planning") {@@ -185,11 +216,14 @@ function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: boo} else if (role === "thought" || kind === "llm_reasoning") {title = t("Thought");} else if (kind === "llm_generation") {- if (/^generate\s+/i.test(label)) title = label.replace(/^generate\s+/i, "Generating ");- else if (/^write\s+/i.test(label)) title = label.replace(/^write\s+/i, "Writing ");+ if (/^generate\s+/i.test(label)) {+ title = t("Generating {{label}}", { label: label.replace(/^generate\s+/i, "") });+ } else if (/^write\s+/i.test(label)) {+ title = t("Writing {{label}}", { label: label.replace(/^write\s+/i, "") });+ }}- return duration ? `${title} for ${duration}` : title;+ return duration ? t("{{title}} for {{duration}}", { title, duration }) : title;}function getTraceText(events: StreamEvent[], eventTypes: Array<StreamEvent["type"]>) {@@ -928,12 +962,15 @@ export function ResearchStagePanel({events: StreamEvent[];isStreaming?: boolean;}) {+ const { t } = useTranslation();const cards = useMemo<ResearchStageCard[]>(() => {return RESEARCH_STAGE_SPECS.map((spec) => ({- ...spec,+ id: spec.id,+ title: t(spec.titleKey),+ hint: t(spec.hintKey),events: events.filter((event) => getResearchStageId(event) === spec.id),})).filter((card) => card.events.length > 0);- }, [events]);+ }, [events, t]);if (!cards.length) return null;diff --git a/web/components/math-animator/MathAnimatorConfigPanel.tsx b/web/components/math-animator/MathAnimatorConfigPanel.tsxindex 11dae0be2..9f8cb89f9 100644--- a/web/components/math-animator/MathAnimatorConfigPanel.tsx+++ b/web/components/math-animator/MathAnimatorConfigPanel.tsx@@ -33,11 +33,11 @@ export default function MathAnimatorConfigPanel({return (<CollapsibleConfigSectioncollapsed={collapsed}- summary={summarizeMathAnimatorConfig(value)}+ summary={summarizeMathAnimatorConfig(value, t)}onToggleCollapsed={onToggleCollapsed}bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5">- <Field label="Output" width="w-[100px]">+ <Field label={t("Output")} width="w-[100px]"><selectvalue={value.output_mode}onChange={(e) => update("output_mode", e.target.value as MathAnimatorFormConfig["output_mode"])}@@ -48,7 +48,7 @@ export default function MathAnimatorConfigPanel({</select></Field>- <Field label="Quality" width="w-[100px]">+ <Field label={t("Quality")} width="w-[100px]"><selectvalue={value.quality}onChange={(e) => update("quality", e.target.value as MathAnimatorFormConfig["quality"])}@@ -60,7 +60,7 @@ export default function MathAnimatorConfigPanel({</select></Field>- <Field label="Style Hint" width="min-w-[160px] flex-1">+ <Field label={t("Style Hint")} width="min-w-[160px] flex-1"><inputtype="text"value={value.style_hint}diff --git a/web/components/quiz/QuizConfigPanel.tsx b/web/components/quiz/QuizConfigPanel.tsxindex 588a0b194..a7dc14fcc 100644--- a/web/components/quiz/QuizConfigPanel.tsx+++ b/web/components/quiz/QuizConfigPanel.tsx@@ -45,7 +45,7 @@ export default function QuizConfigPanel({return (<CollapsibleConfigSectioncollapsed={collapsed}- summary={summarizeQuizConfig(value)}+ summary={summarizeQuizConfig(value, t)}onToggleCollapsed={onToggleCollapsed}bodyClassName="px-3.5 pb-2.5 space-y-2.5">@@ -68,7 +68,7 @@ export default function QuizConfigPanel({{value.mode === "custom" ? (<div className="flex flex-wrap items-end gap-x-3 gap-y-2">- <Field label="Count" width="w-[60px]">+ <Field label={t("Count")} width="w-[60px]"><inputtype="number"min={1}@@ -81,7 +81,7 @@ export default function QuizConfigPanel({/></Field>- <Field label="Difficulty" width="w-[100px]">+ <Field label={t("Difficulty")} width="w-[100px]"><selectvalue={value.difficulty}onChange={(e) => update("difficulty", e.target.value)}@@ -94,7 +94,7 @@ export default function QuizConfigPanel({</select></Field>- <Field label="Type" width="w-[110px]">+ <Field label={t("Type")} width="w-[110px]"><selectvalue={value.question_type}onChange={(e) => update("question_type", e.target.value)}@@ -107,7 +107,7 @@ export default function QuizConfigPanel({</select></Field>- <Field label="Preference" width="min-w-[140px] flex-1">+ <Field label={t("Preference")} width="min-w-[140px] flex-1"><inputtype="text"value={value.preference}@@ -119,7 +119,7 @@ export default function QuizConfigPanel({</div>) : (<div className="flex flex-wrap items-end gap-x-3 gap-y-2">- <Field label="Paper" width="min-w-[180px] flex-[1.3]">+ <Field label={t("Paper")} width="min-w-[180px] flex-[1.3]">{uploadedPdf ? (<div className="flex h-[30px] items-center gap-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px]"><FileText size={12} className="shrink-0 text-[var(--primary)]/60" />@@ -175,7 +175,7 @@ export default function QuizConfigPanel({)}</Field>- <Field label="Parsed Dir" width="min-w-[120px] flex-1">+ <Field label={t("Parsed Dir")} width="min-w-[120px] flex-1"><inputtype="text"value={value.paper_path}@@ -188,7 +188,7 @@ export default function QuizConfigPanel({/></Field>- <Field label="Max" width="w-[60px]">+ <Field label={t("Max")} width="w-[60px]"><inputtype="number"min={1}diff --git a/web/components/research/ResearchConfigPanel.tsx b/web/components/research/ResearchConfigPanel.tsxindex 3ca3f957b..b14a92c67 100644--- a/web/components/research/ResearchConfigPanel.tsx+++ b/web/components/research/ResearchConfigPanel.tsx@@ -21,6 +21,8 @@ interface ResearchConfigPanelProps {onToggleCollapsed: () => void;}+// Note: `label` values are i18n keys resolved via `t(...)` at render time so+// the dropdown options match the active UI language.const MODE_OPTIONS: Array<{ value: Exclude<ResearchMode, "">; label: string }> = [{ value: "notes", label: "Study Notes" },{ value: "report", label: "Report" },@@ -80,8 +82,8 @@ export default function ResearchConfigPanel({next: DeepResearchFormConfig[K],) => onChange({ ...value, [key]: next });- const rawSummary = summarizeResearchConfig(value);- const summary = rawSummary === "Incomplete settings" ? undefined : rawSummary;+ const rawSummary = summarizeResearchConfig(value, t);+ const summary = rawSummary === t("Incomplete settings") ? undefined : rawSummary;return (<CollapsibleConfigSection@@ -91,7 +93,7 @@ export default function ResearchConfigPanel({bodyClassName="space-y-2 px-3.5 pb-2.5"><div className="flex flex-wrap items-end gap-x-3 gap-y-2">- <Field label="Mode" width="min-w-[130px] flex-1">+ <Field label={t("Mode")} width="min-w-[130px] flex-1"><selectvalue={value.mode}onChange={(e) => update("mode", e.target.value as ResearchMode)}@@ -100,12 +102,12 @@ export default function ResearchConfigPanel({<option value="">{t("Select...")}</option>{MODE_OPTIONS.map((option) => (<option key={option.value} value={option.value}>- {option.label}+ {t(option.label)}</option>))}</select></Field>- <Field label="Depth" width="min-w-[130px] flex-1">+ <Field label={t("Depth")} width="min-w-[130px] flex-1"><selectvalue={value.depth}onChange={(e) => update("depth", e.target.value as ResearchDepth)}@@ -114,7 +116,7 @@ export default function ResearchConfigPanel({<option value="">{t("Select...")}</option>{DEPTH_OPTIONS.map((option) => (<option key={option.value} value={option.value}>- {option.label}+ {t(option.label)}</option>))}</select>@@ -123,14 +125,14 @@ export default function ResearchConfigPanel({{value.depth === "manual" && (<div className="space-y-1.5 rounded-md bg-[var(--muted-foreground)]/5 px-3 py-2"><NumberSlider- label="Sub-topics"+ label={t("Sub-topics")}value={value.manual_subtopics ?? 3}min={1}max={10}onChange={(n) => update("manual_subtopics", n)}/><NumberSlider- label="Iterations"+ label={t("Iterations")}value={value.manual_max_iterations ?? 3}min={1}max={8}diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsxindex 7899ed079..77b04b71d 100644--- a/web/components/visualize/VisualizationViewer.tsx+++ b/web/components/visualize/VisualizationViewer.tsx@@ -7,6 +7,7 @@ import { Mermaid } from "@/components/Mermaid";import type { VisualizeResult } from "@/lib/visualize-types";function ChartJsRenderer({ config }: { config: string }) {+ const { t } = useTranslation();const canvasRef = useRef<HTMLCanvasElement>(null);const chartRef = useRef<unknown>(null);const [error, setError] = useState<string | null>(null);@@ -35,7 +36,7 @@ function ChartJsRenderer({ config }: { config: string }) {setError(null);} catch (err) {if (!cancelled) {- setError(err instanceof Error ? err.message : "Failed to render chart");+ setError(err instanceof Error ? err.message : t("Failed to render chart"));}}}@@ -49,13 +50,13 @@ function ChartJsRenderer({ config }: { config: string }) {chartRef.current = null;}};- }, [config]);+ }, [config, t]);if (error) {return (<div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900/60 dark:bg-red-950/30"><p className="text-sm font-medium text-red-600 dark:text-red-400">- Chart rendering error+ {t("Chart rendering error")}</p><pre className="mt-2 whitespace-pre-wrap text-xs text-red-500">{error}</pre></div>@@ -70,24 +71,25 @@ function ChartJsRenderer({ config }: { config: string }) {}function SvgRenderer({ svg }: { svg: string }) {+ const { t } = useTranslation();const containerRef = useRef<HTMLDivElement>(null);const [error, setError] = useState<string | null>(null);const sanitizedSvg = useMemo(() => {const trimmed = svg.trim();if (!trimmed.startsWith("<svg")) {- setError("Invalid SVG: does not start with <svg");+ setError(t("Invalid SVG: does not start with <svg"));return "";}setError(null);return trimmed;- }, [svg]);+ }, [svg, t]);if (error) {return (<div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900/60 dark:bg-red-950/30"><p className="text-sm font-medium text-red-600 dark:text-red-400">- SVG rendering error+ {t("SVG rendering error")}</p><pre className="mt-2 whitespace-pre-wrap text-xs text-red-500">{error}</pre></div>diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsxindex a57e4aa3a..cce6dc761 100644--- a/web/components/visualize/VisualizeConfigPanel.tsx+++ b/web/components/visualize/VisualizeConfigPanel.tsx@@ -29,11 +29,11 @@ export default function VisualizeConfigPanel({return (<CollapsibleConfigSectioncollapsed={collapsed}- summary={summarizeVisualizeConfig(value)}+ summary={summarizeVisualizeConfig(value, t)}onToggleCollapsed={onToggleCollapsed}bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5">- <Field label="Render Mode" width="w-[120px]">+ <Field label={t("Render Mode")} width="w-[120px]"><selectvalue={value.render_mode}onChange={(e) =>diff --git a/web/lib/math-animator-types.ts b/web/lib/math-animator-types.tsindex 013453885..0aa93648f 100644--- a/web/lib/math-animator-types.ts+++ b/web/lib/math-animator-types.ts@@ -68,10 +68,16 @@ function titleCase(value: string): string {/*** One-line summary of the math-animator form, shown next to the collapsed- * `Settings` chevron in the composer.+ * `Settings` chevron in the composer. Pass `translate` (typically `t` from+ * `react-i18next`) so the summary follows the active UI language.*/-export function summarizeMathAnimatorConfig(cfg: MathAnimatorFormConfig): string {- return [titleCase(cfg.output_mode), titleCase(cfg.quality)].join(" · ");+export function summarizeMathAnimatorConfig(+ cfg: MathAnimatorFormConfig,+ translate?: (key: string) => string,+): string {+ const output = titleCase(cfg.output_mode);+ const quality = titleCase(cfg.quality);+ return [translate ? translate(output) : output, translate ? translate(quality) : quality].join(" · ");}export function extractMathAnimatorResult(diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.tsindex e31bad212..b40348e12 100644--- a/web/lib/quiz-types.ts+++ b/web/lib/quiz-types.ts@@ -125,18 +125,23 @@ function titleCase(value: string): string {/*** One-line summary of the quiz form, shown next to the collapsed `Settings`- * chevron in the composer.+ * chevron in the composer. Pass `translate` (`t` from `react-i18next`) so the+ * summary follows the active UI language.*/-export function summarizeQuizConfig(cfg: DeepQuestionFormConfig): string {+export function summarizeQuizConfig(+ cfg: DeepQuestionFormConfig,+ translate?: (key: string) => string,+): string {+ const tr = translate ?? ((s: string) => s);if (cfg.mode === "mimic") {- const target = cfg.paper_path.trim() || "no paper";- return ["Mimic", target, `max ${cfg.max_questions}`].join(" · ");+ const target = cfg.paper_path.trim() || tr("no paper");+ return [tr("Mimic Paper"), target, `${tr("Max")} ${cfg.max_questions}`].join(" · ");}return [- "Custom",- `${cfg.num_questions}q`,- titleCase(cfg.difficulty || "auto"),- titleCase(cfg.question_type || "auto"),+ tr("Custom"),+ `${cfg.num_questions} ${tr("questions")}`,+ tr(titleCase(cfg.difficulty || "auto")),+ tr(titleCase(cfg.question_type || "auto")),].join(" · ");}diff --git a/web/lib/research-types.ts b/web/lib/research-types.tsindex 9d55f9714..d2f15741a 100644--- a/web/lib/research-types.ts+++ b/web/lib/research-types.ts@@ -97,13 +97,29 @@ export function buildResearchWSConfig(return result;}-export function summarizeResearchConfig(cfg: DeepResearchFormConfig): string {+const RESEARCH_MODE_LABELS: Record<string, string> = {+ notes: "Study Notes",+ report: "Report",+ comparison: "Comparison",+ learning_path: "Learning Path",+};++const RESEARCH_DEPTH_LABELS: Record<string, string> = {+ quick: "Quick",+ standard: "Standard",+ deep: "Deep",+ manual: "Manual",+};++export function summarizeResearchConfig(+ cfg: DeepResearchFormConfig,+ translate?: (key: string) => string,+): string {const validation = validateResearchConfig(cfg);- if (!validation.valid) return "Incomplete settings";- const sourceSummary = cfg.sources.length ? cfg.sources.join("+") : "llm-only";- return [- cfg.mode.replace("_", " "),- cfg.depth,- sourceSummary,- ].join(" · ");+ const tr = translate ?? ((s: string) => s);+ if (!validation.valid) return tr("Incomplete settings");+ const sourceSummary = cfg.sources.length ? cfg.sources.join("+") : tr("llm-only");+ const modeLabel = RESEARCH_MODE_LABELS[cfg.mode] ?? cfg.mode.replace("_", " ");+ const depthLabel = RESEARCH_DEPTH_LABELS[cfg.depth] ?? cfg.depth;+ return [tr(modeLabel), tr(depthLabel), sourceSummary].join(" · ");}diff --git a/web/lib/visualize-types.ts b/web/lib/visualize-types.tsindex f7feab709..e31680cc7 100644--- a/web/lib/visualize-types.ts+++ b/web/lib/visualize-types.ts@@ -24,10 +24,16 @@ const VISUALIZE_RENDER_LABELS: Record<VisualizeRenderMode, string> = {/*** One-line summary of the visualize form, shown next to the collapsed- * `Settings` chevron in the composer.+ * `Settings` chevron in the composer. Pass `translate` (typically the+ * `t` function from `react-i18next`) so the summary follows the active+ * UI language.*/-export function summarizeVisualizeConfig(cfg: VisualizeFormConfig): string {- return VISUALIZE_RENDER_LABELS[cfg.render_mode] ?? cfg.render_mode;+export function summarizeVisualizeConfig(+ cfg: VisualizeFormConfig,+ translate?: (key: string) => string,+): string {+ const label = VISUALIZE_RENDER_LABELS[cfg.render_mode] ?? cfg.render_mode;+ return translate ? translate(label) : label;}export interface VisualizeResult {diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 3d5086830..5df5b144c 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -925,5 +925,99 @@"Retry": "Retry","Your pick": "Your pick","No categories yet.": "No categories yet.",- "Original Session": "Original Session"+ "Original Session": "Original Session",+ "Visualize": "Visualize",+ "Generate SVG, Chart.js, or Mermaid visualizations": "Generate SVG, Chart.js, or Mermaid visualizations",+ "Render Mode": "Render Mode",+ "Chart.js": "Chart.js",+ "SVG": "SVG",+ "Mermaid": "Mermaid",+ "Reference": "Reference",+ "Describe the chart or diagram you want to visualize...": "Describe the chart or diagram you want to visualize...",+ "Show code": "Show code",+ "Hide code": "Hide code",+ "Copy code": "Copy code",+ "Copied": "Copied",+ "Review": "Review",+ "Failed to render chart": "Failed to render chart",+ "Chart rendering error": "Chart rendering error",+ "SVG rendering error": "SVG rendering error",+ "Invalid SVG: does not start with <svg": "Invalid SVG: does not start with <svg",+ "Failed to render diagram": "Failed to render diagram",+ "image": "image",+ "calls": "calls",+ "Output": "Output",+ "Quality": "Quality",+ "Style Hint": "Style Hint",+ "Paper": "Paper",+ "Parsed Dir": "Parsed Dir",+ "Max": "Max",+ "Depth": "Depth",+ "Sub-topics": "Sub-topics",+ "Iterations": "Iterations",+ "Study Notes": "Study Notes",+ "Comparison": "Comparison",+ "Learning Path": "Learning Path",+ "Quick": "Quick",+ "Standard": "Standard",+ "Deep": "Deep",+ "Manual": "Manual",+ "Round {{n}}": "Round {{n}}",+ "Step {{n}}": "Step {{n}}",+ "Generating {{label}}": "Generating {{label}}",+ "Writing {{label}}": "Writing {{label}}",+ "{{title}} for {{duration}}": "{{title}} for {{duration}}",+ "Question {{n}}": "Question {{n}}",+ "research.stage.understand.title": "Understand the question",+ "research.stage.understand.hint": "Clarify the topic and research goal first.",+ "research.stage.decompose.title": "Decompose the topic",+ "research.stage.decompose.hint": "Split the question into searchable, learnable sub-topics.",+ "research.stage.evidence.title": "Gather evidence",+ "research.stage.evidence.hint": "Collect and organize evidence from the selected sources.",+ "research.stage.result.title": "Form the result",+ "research.stage.result.hint": "Compose the gathered evidence into the final output.",+ "Notebook Context": "Notebook Context",+ "Generate learning plan": "Generate learning plan",+ "Describe what you want to learn": "Describe what you want to learn",+ "Describe what you want to learn on the left, and your guided learning sessions will appear here.": "Describe what you want to learn on the left, and your guided learning sessions will appear here.",+ "For example: Teach me linear algebra from the basics, with intuition, key formulas, and common mistakes.": "For example: Teach me linear algebra from the basics, with intuition, key formulas, and common mistakes.",+ "Learning History": "Learning History",+ "Loading history...": "Loading history...",+ "No learning history yet": "No learning history yet",+ "Untitled Session": "Untitled Session",+ "Untitled": "Untitled",+ "Knowledge Point": "Knowledge Point",+ "Open": "Open",+ "Open any page once it is ready. Early stages are prioritized.": "Open any page once it is ready. Early stages are prioritized.",+ "Generation failed": "Generation failed",+ "This page failed to generate. You can retry it from the tab bar.": "This page failed to generate. You can retry it from the tab bar.",+ "Waiting for the selected interactive page...": "Waiting for the selected interactive page...",+ "Generating interactive page...": "Generating interactive page...",+ "Write a short learning request, and the system will design a progressive guided learning plan for you.": "Write a short learning request, and the system will design a progressive guided learning plan for you.",+ "pages ready": "pages ready",+ "Current page": "Current page",+ "Ready to open": "Ready to open",+ "Waiting in queue": "Waiting in queue",+ "In Progress": "In Progress",+ "Completed": "Completed",+ "Planned": "Planned",+ "Reset session": "Reset session",+ "Starting...": "Starting...",+ "Summary": "Summary",+ "Channels": "Channels",+ "Delivery": "Delivery",+ "Enabled": "Enabled",+ "Save failed": "Save failed",+ "Channels saved": "Channels saved",+ "Select a channel.": "Select a channel.",+ "Stream progress text to channels": "Stream progress text to channels",+ "Stream tool hints to channels": "Stream tool hints to channels",+ "Config is saved on disk; stop and start the bot to apply.": "Config is saved on disk; stop and start the bot to apply.",+ "Invalid channel configuration": "Invalid channel configuration",+ "Channel listeners failed to restart:": "Channel listeners failed to restart:",+ "Complete": "Complete",+ "no paper": "no paper",+ "Incomplete settings": "Incomplete settings",+ "llm-only": "llm-only",+ "Copy": "Copy"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 789ed5365..470f0ded1 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -925,5 +925,99 @@"Retry": "重试","Your pick": "你的选择","No categories yet.": "暂无分类。",- "Original Session": "原始会话"+ "Original Session": "原始会话",+ "Visualize": "可视化",+ "Generate SVG, Chart.js, or Mermaid visualizations": "生成 SVG、Chart.js 或 Mermaid 可视化",+ "Render Mode": "渲染模式",+ "Chart.js": "Chart.js",+ "SVG": "SVG",+ "Mermaid": "Mermaid",+ "Reference": "引用",+ "Describe the chart or diagram you want to visualize...": "描述你想要可视化的图表或示意图…",+ "Show code": "显示代码",+ "Hide code": "隐藏代码",+ "Copy code": "复制代码",+ "Copied": "已复制",+ "Review": "审阅",+ "Failed to render chart": "图表渲染失败",+ "Chart rendering error": "图表渲染错误",+ "SVG rendering error": "SVG 渲染错误",+ "Invalid SVG: does not start with <svg": "无效的 SVG:不是以 <svg 开头",+ "Failed to render diagram": "示意图渲染失败",+ "image": "图片",+ "calls": "次调用",+ "Output": "输出",+ "Quality": "质量",+ "Style Hint": "风格提示",+ "Paper": "试卷",+ "Parsed Dir": "解析目录",+ "Max": "上限",+ "Depth": "深度",+ "Sub-topics": "子主题数",+ "Iterations": "迭代次数",+ "Study Notes": "学习笔记",+ "Comparison": "对比分析",+ "Learning Path": "学习路径",+ "Quick": "快速",+ "Standard": "标准",+ "Deep": "深度",+ "Manual": "手动",+ "Round {{n}}": "第 {{n}} 轮",+ "Step {{n}}": "第 {{n}} 步",+ "Generating {{label}}": "正在生成 {{label}}",+ "Writing {{label}}": "正在撰写 {{label}}",+ "{{title}} for {{duration}}": "{{title}} · 用时 {{duration}}",+ "Question {{n}}": "问题 {{n}}",+ "research.stage.understand.title": "理解问题",+ "research.stage.understand.hint": "先澄清主题与研究目标。",+ "research.stage.decompose.title": "拆解主题",+ "research.stage.decompose.hint": "把问题拆成可检索、可学习的子主题。",+ "research.stage.evidence.title": "检索证据",+ "research.stage.evidence.hint": "结合所选 sources 收集和整理证据。",+ "research.stage.result.title": "形成结果",+ "research.stage.result.hint": "把证据整理成最终输出。",+ "Notebook Context": "笔记本上下文",+ "Generate learning plan": "生成学习计划",+ "Describe what you want to learn": "描述你想学习的内容",+ "Describe what you want to learn on the left, and your guided learning sessions will appear here.": "在左侧描述你想学习的内容,引导式学习会话会显示在这里。",+ "For example: Teach me linear algebra from the basics, with intuition, key formulas, and common mistakes.": "例如:从基础开始教我线性代数,包括直觉、关键公式以及常见错误。",+ "Learning History": "学习历史",+ "Loading history...": "正在加载历史…",+ "No learning history yet": "暂无学习历史",+ "Untitled Session": "未命名会话",+ "Untitled": "未命名",+ "Knowledge Point": "知识点",+ "Open": "打开",+ "Open any page once it is ready. Early stages are prioritized.": "页面就绪后即可打开,优先打开靠前的阶段。",+ "Generation failed": "生成失败",+ "This page failed to generate. You can retry it from the tab bar.": "该页面生成失败,可在标签栏重试。",+ "Waiting for the selected interactive page...": "正在等待所选交互页面…",+ "Generating interactive page...": "正在生成交互页面…",+ "Write a short learning request, and the system will design a progressive guided learning plan for you.": "写一段简短的学习需求,系统会为你设计循序渐进的引导式学习计划。",+ "pages ready": "页已就绪",+ "Current page": "当前页面",+ "Ready to open": "可以打开",+ "Waiting in queue": "排队中",+ "In Progress": "进行中",+ "Completed": "已完成",+ "Planned": "已规划",+ "Reset session": "重置会话",+ "Starting...": "正在启动…",+ "Summary": "总结",+ "Channels": "频道",+ "Delivery": "投递",+ "Enabled": "已启用",+ "Save failed": "保存失败",+ "Channels saved": "频道已保存",+ "Select a channel.": "请选择一个频道。",+ "Stream progress text to channels": "向频道推送进度文本",+ "Stream tool hints to channels": "向频道推送工具提示",+ "Config is saved on disk; stop and start the bot to apply.": "配置已写入磁盘,需停止并重启机器人后生效。",+ "Invalid channel configuration": "频道配置无效",+ "Channel listeners failed to restart:": "频道监听器重启失败:",+ "Complete": "完成",+ "no paper": "未上传试卷",+ "Incomplete settings": "设置不完整",+ "llm-only": "仅 LLM",+ "Copy": "复制"}