Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat: add context-aware ask questions mode

SeleiXi4c9df02a97a3
diff --git a/deeptutor/capabilities/ask_questions/__init__.py b/deeptutor/capabilities/ask_questions/__init__.py
new file mode 100644
index 000000000..8534aa92f
--- /dev/null
+++ b/deeptutor/capabilities/ask_questions/__init__.py
@@ -0,0 +1,5 @@
+"""Ask Questions capability exports."""
+
+from deeptutor.capabilities.ask_questions.loop import AskQuestionsLoopCapability
+
+__all__ = ["AskQuestionsLoopCapability"]
diff --git a/deeptutor/capabilities/ask_questions/capability.py b/deeptutor/capabilities/ask_questions/capability.py
new file mode 100644
index 000000000..9551e5c0b
--- /dev/null
+++ b/deeptutor/capabilities/ask_questions/capability.py
@@ -0,0 +1,36 @@
+"""Ask Questions capability — an explicit user-selected interview mode."""
+
+from __future__ import annotations
+
+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream_bus import StreamBus
+from deeptutor.runtime.request_contracts import get_capability_request_schema
+
+
+class AskQuestionsCapability(BaseCapability):
+ """Let the model ask context-aware questions whenever they become useful."""
+
+ manifest = CapabilityManifest(
+ name="ask_questions",
+ description=(
+ "Ask the user high-value questions to fill in missing context, "
+ "then complete the original request with their answers."
+ ),
+ stages=["responding"],
+ tools_used=["ask_user"],
+ cli_aliases=["ask"],
+ request_schema=get_capability_request_schema("chat"),
+ )
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ context.metadata["ask_questions_mode"] = True
+ # Tool selection stays model-directed. The capability's system block
+ # changes *when* ask_user is appropriate; it must not force a question
+ # at the beginning of every user turn.
+ pipeline = AgenticChatPipeline(language=context.language)
+ await pipeline.run(context, stream)
+
+
+__all__ = ["AskQuestionsCapability"]
diff --git a/deeptutor/capabilities/ask_questions/loop.py b/deeptutor/capabilities/ask_questions/loop.py
new file mode 100644
index 000000000..c10b29133
--- /dev/null
+++ b/deeptutor/capabilities/ask_questions/loop.py
@@ -0,0 +1,53 @@
+"""Chat-loop hooks for the Ask Questions capability."""
+
+from __future__ import annotations
+
+from importlib import resources
+from typing import Any
+
+from deeptutor.capabilities.protocol import PromptBlock
+from deeptutor.core.context import UnifiedContext
+
+
+class AskQuestionsLoopCapability:
+ """Contribute an adaptive questioning policy to the normal chat loop."""
+
+ name = "ask_questions"
+ owned_tools: tuple[str, ...] = ()
+
+ def is_active(self, context: UnifiedContext) -> bool:
+ return bool(context.metadata.get("ask_questions_mode"))
+
+ def system_block(
+ self,
+ context: UnifiedContext,
+ *,
+ language: str,
+ prompts: dict[str, Any],
+ ) -> PromptBlock | None:
+ _ = prompts
+ if not self.is_active(context):
+ return None
+ return PromptBlock("ask_questions", _load_system_prompt(language))
+
+ def augment_kwargs(
+ self,
+ tool_name: str,
+ kwargs: dict[str, Any],
+ context: UnifiedContext,
+ ) -> dict[str, Any]:
+ _ = tool_name, context
+ return kwargs
+
+ def pre_loop_seed(self, context: UnifiedContext) -> str:
+ _ = context
+ return ""
+
+
+def _load_system_prompt(language: str) -> str:
+ lang = "zh" if language.lower().startswith("zh") else "en"
+ prompt = resources.files(__package__).joinpath("prompts", lang, "system.md")
+ return prompt.read_text(encoding="utf-8").strip()
+
+
+__all__ = ["AskQuestionsLoopCapability"]
diff --git a/deeptutor/capabilities/ask_questions/prompts/en/system.md b/deeptutor/capabilities/ask_questions/prompts/en/system.md
new file mode 100644
index 000000000..280588052
--- /dev/null
+++ b/deeptutor/capabilities/ask_questions/prompts/en/system.md
@@ -0,0 +1,9 @@
+# Ask Questions mode
+
+The user explicitly chose this mode because they want you to notice information gaps and ask them useful questions at the right time. The mode persists across later conversation turns; it does not require a question at the start of every request.
+
+At every agent-loop round, reassess whether the available information is sufficient. First study all available context: the current request, the full prior conversation, earlier `ask_user` questions and answers, memory, persona, attachments, selected sources, knowledge-base context, and anything tools just discovered. Call `ask_user` when an answer only the user can provide would materially improve accuracy, personalization, or teaching effectiveness. This may happen on the first loop round, after later tool work exposes a gap, or on the second, third, tenth, or any later conversation turn. If the context is already sufficient, continue directly; never ask merely to demonstrate that the mode is enabled.
+
+Before calling the tool, check the clarification history and never repeat a question the user already answered or a fact they already supplied. If new evidence conflicts with an older answer, ask only what changed and explain why an update is needed. Do not ask generic filler or request confirmation merely to delay action. Ask 1–4 specific, high-information questions in one call. Use concise, meaningful options only when options genuinely help; otherwise allow free text. Useful targets include the user's real goal, existing knowledge, constraints, prior attempts, point of confusion, audience, and preferred depth or output.
+
+After the user answers, continue the original request in the same turn using the new context; do not end with a bare acknowledgment. Ask again later only if an answer or subsequent tool result exposes another material information gap.
diff --git a/deeptutor/capabilities/ask_questions/prompts/zh/system.md b/deeptutor/capabilities/ask_questions/prompts/zh/system.md
new file mode 100644
index 000000000..ed10a91f0
--- /dev/null
+++ b/deeptutor/capabilities/ask_questions/prompts/zh/system.md
@@ -0,0 +1,9 @@
+# 主动提问模式
+
+用户明确选择了此模式,希望你在对话中主动发现信息缺口,并在合适的时机向他们提问。此模式会持续用于后续对话轮次;它不要求你在每个请求开头提问。
+
+在每个 agent loop 轮次重新判断现有信息是否足够。先审视全部可用上下文:当前请求、此前所有对话、较早的 `ask_user` 问答、记忆、persona、附件、选中的来源、知识库内容,以及本轮工具刚发现的新情况。如果一个只有用户知道的答案会实质性改善准确性、个性化程度或教学效果,就调用 `ask_user`;这个时机可以出现在当前请求的第一轮,也可以在后续工具调用暴露信息缺口之后,或在未来第 2、3、10 个对话轮次。若信息已经足够,则直接继续,不要为了体现模式存在而提问。
+
+调用前必须检查历史澄清记录,不要重复询问用户已经回答或明确说明的事实。若新情况与旧答案冲突,只询问发生变化的部分,并明确指出需要更新的原因。不要问空泛套话,不要为了拖延而要求确认。问题应少而具体,一次集中提出 1–4 个高信息量问题;只有在选项确实有帮助时才提供简洁且有意义的选项,否则允许自由输入。可关注真实目标、已有知识、约束条件、此前尝试、具体卡点、目标受众,以及期望的深度或输出形式。
+
+用户回答后,在同一个 turn 中根据新增上下文继续原始请求,不要只回复一句确认收到。只有当回答或后续工具结果又暴露了新的实质性信息缺口时,才在之后再次提问。
diff --git a/deeptutor/capabilities/registry.py b/deeptutor/capabilities/registry.py
index ed1705c44..d29a5da35 100644
--- a/deeptutor/capabilities/registry.py
+++ b/deeptutor/capabilities/registry.py
@@ -7,6 +7,7 @@ import inspect
import logging
from typing import Any
+from deeptutor.capabilities.ask_questions import AskQuestionsLoopCapability
from deeptutor.capabilities.explore_context import ExploreContextCapability
from deeptutor.capabilities.ima import ImaCapability
from deeptutor.capabilities.marginnote4 import MarginNoteCapability
@@ -25,6 +26,7 @@ logger = logging.getLogger(__name__)
LOOP_CAPABILITIES_GROUP = "deeptutor.loop_capabilities"
LOOP_CAPABILITIES: tuple[LoopCapability, ...] = (
+ AskQuestionsLoopCapability(),
MasteryLoopCapability(),
SolveLoopCapability(),
ObsidianCapability(),
diff --git a/deeptutor/runtime/bootstrap/builtin_capabilities.py b/deeptutor/runtime/bootstrap/builtin_capabilities.py
index f9a252029..f57cf847f 100644
--- a/deeptutor/runtime/bootstrap/builtin_capabilities.py
+++ b/deeptutor/runtime/bootstrap/builtin_capabilities.py
@@ -2,6 +2,7 @@
BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {
"chat": "deeptutor.agents.chat.capability:ChatCapability",
+ "ask_questions": ("deeptutor.capabilities.ask_questions.capability:AskQuestionsCapability"),
"deep_solve": "deeptutor.capabilities.solve.capability:DeepSolveCapability",
"deep_question": "deeptutor.agents.question.capability:DeepQuestionCapability",
"deep_research": "deeptutor.agents.research.capability:DeepResearchCapability",
diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.py
index ff2c7bd9d..b386869c8 100644
--- a/deeptutor/services/session/context_builder.py
+++ b/deeptutor/services/session/context_builder.py
@@ -56,6 +56,64 @@ def trim_incomplete_tail(text: str) -> str:
return text.rstrip()
+def extract_ask_user_clarifications(message: dict[str, Any]) -> str:
+ """Recover resolved ask_user exchanges from a persisted assistant row.
+
+ Card replies resume the same backend turn, so they are stored in the
+ assistant message's event trace rather than as standalone user messages.
+ Rehydrate them into future model context or later turns would forget the
+ answers and could ask the same questions again.
+ """
+
+ pending_questions: dict[str, str] = {}
+ exchanges: list[tuple[str, str]] = []
+ for event in message.get("events") or []:
+ if not isinstance(event, dict):
+ continue
+ metadata = event.get("metadata") or {}
+ if not isinstance(metadata, dict):
+ continue
+ if event.get("type") == "tool_result":
+ tool_metadata = metadata.get("tool_metadata") or {}
+ ask_user = (
+ tool_metadata.get("ask_user") if isinstance(tool_metadata, dict) else None
+ ) or metadata.get("ask_user")
+ if not isinstance(ask_user, dict):
+ continue
+ pending_questions = {
+ str(question.get("id") or ""): str(question.get("prompt") or "").strip()
+ for question in ask_user.get("questions") or []
+ if isinstance(question, dict) and str(question.get("prompt") or "").strip()
+ }
+ continue
+ if not metadata.get("ask_user_resolved"):
+ continue
+ answers = metadata.get("answers") or []
+ resolved = False
+ for answer in answers:
+ if not isinstance(answer, dict):
+ continue
+ question_id = str(answer.get("questionId") or answer.get("question_id") or "")
+ answer_text = str(answer.get("text") or "").strip()
+ question_text = pending_questions.get(question_id, question_id).strip()
+ if question_text and answer_text:
+ exchanges.append((question_text, answer_text))
+ resolved = True
+ if not resolved:
+ preview = str(metadata.get("reply_preview") or "").strip()
+ if preview:
+ question_text = next(iter(pending_questions.values()), "User clarification")
+ exchanges.append((question_text, preview))
+ pending_questions = {}
+
+ if not exchanges:
+ return ""
+ lines = ["[Earlier ask_user clarification — treat these answers as user-provided context]"]
+ for question, answer in exchanges:
+ lines.extend((f"- Question: {question}", f" User answer: {answer}"))
+ return "\n".join(lines)
+
+
def format_messages_as_transcript(messages: list[dict[str, Any]]) -> str:
lines: list[str] = []
role_map = {
@@ -65,10 +123,12 @@ def format_messages_as_transcript(messages: list[dict[str, Any]]) -> str:
}
for item in messages:
content = str(item.get("content", "") or "").strip()
- if not content:
- continue
- role = role_map.get(str(item.get("role", "user")), "User")
- lines.append(f"{role}: {content}")
+ if content:
+ role = role_map.get(str(item.get("role", "user")), "User")
+ lines.append(f"{role}: {content}")
+ clarification = extract_ask_user_clarifications(item)
+ if clarification:
+ lines.append(f"User: {clarification}")
return "\n\n".join(lines)
@@ -167,15 +227,14 @@ class ContextBuilder:
cleaned_summary = summary.strip()
if cleaned_summary:
history.append({"role": "system", "content": cleaned_summary})
- history.extend(
- {
- "role": item.get("role", "user"),
- "content": str(item.get("content", "") or ""),
- }
- for item in messages
- if item.get("role") in {"user", "assistant"}
- and str(item.get("content", "") or "").strip()
- )
+ for item in messages:
+ role = item.get("role")
+ content = str(item.get("content", "") or "")
+ if role in {"user", "assistant"} and content.strip():
+ history.append({"role": role, "content": content})
+ clarification = extract_ask_user_clarifications(item)
+ if clarification:
+ history.append({"role": "user", "content": clarification})
return history
async def _append_event(
@@ -197,7 +256,8 @@ class ContextBuilder:
total = 0
for item in reversed(messages):
content = str(item.get("content", "") or "")
- tokens = count_tokens(content)
+ clarification = extract_ask_user_clarifications(item)
+ tokens = count_tokens(f"{content}\n{clarification}" if clarification else content)
if selected and total + tokens > recent_budget:
break
selected.insert(0, item)
@@ -500,5 +560,6 @@ __all__ = [
"build_history_text",
"count_tokens",
"format_messages_as_transcript",
+ "extract_ask_user_clarifications",
"trim_incomplete_tail",
]
diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.py
index c87ef39c0..d1402e2f3 100644
--- a/tests/agents/chat/test_language_prompts.py
+++ b/tests/agents/chat/test_language_prompts.py
@@ -77,6 +77,34 @@ def test_mastery_plugin_system_prompt_uses_localized_fallback(
assert "Mastery Tutor mode" in en_prompt
+def test_ask_questions_plugin_system_prompt_uses_localized_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FakeRegistry:
+ def build_prompt_text(self, *_args, **_kwargs) -> str:
+ return "- tool"
+
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_tool_registry",
+ lambda: FakeRegistry(),
+ )
+
+ from deeptutor.core.context import UnifiedContext
+
+ ctx = UnifiedContext(metadata={"ask_questions_mode": True})
+ zh_prompt = AgenticChatPipeline(language="zh")._build_system_prompt([], ctx)
+ en_prompt = AgenticChatPipeline(language="en")._build_system_prompt([], ctx)
+
+ assert "## ask_questions" in zh_prompt
+ assert "主动提问模式" in zh_prompt
+ assert "不要求你在每个请求开头提问" in zh_prompt
+ assert "第 2、3、10 个对话轮次" in zh_prompt
+ assert "第一轮必须" not in zh_prompt
+ assert "## ask_questions" in en_prompt
+ assert "Ask Questions mode" in en_prompt
+ assert "second, third, tenth" in en_prompt
+
+
def test_legacy_chat_agent_system_prompt_uses_selected_language() -> None:
zh_messages = ChatAgent(language="zh", config={}).build_messages(
message="解释梯度下降",
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index f341eecba..d5fe21a89 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -78,6 +78,7 @@ def test_builtin_capability_aliases_resolve_to_canonical_names() -> None:
runtime = DeepTutorApp()
assert runtime.resolve_capability("solve") == "deep_solve"
+ assert runtime.resolve_capability("ask") == "ask_questions"
assert runtime.resolve_capability("quiz") == "deep_question"
assert runtime.resolve_capability("research") == "deep_research"
assert runtime.resolve_capability("viz") == "visualize"
diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.py
index afd51c173..c1c5d3c54 100644
--- a/tests/core/test_capabilities_runtime.py
+++ b/tests/core/test_capabilities_runtime.py
@@ -15,6 +15,7 @@ from deeptutor.agents.question.capability import DeepQuestionCapability
from deeptutor.agents.research.capability import DeepResearchCapability
from deeptutor.agents.visualize.capability import VisualizeCapability
import deeptutor.agents.visualize.pipeline as visualize_pipeline
+from deeptutor.capabilities.ask_questions.capability import AskQuestionsCapability
from deeptutor.capabilities.solve.capability import DeepSolveCapability
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.core.stream import StreamEvent, StreamEventType
@@ -69,6 +70,7 @@ async def _collect_events(run_coro) -> list[StreamEvent]:
def test_builtin_capability_registry_covers_documented_capabilities() -> None:
assert set(BUILTIN_CAPABILITY_CLASSES) == {
"chat",
+ "ask_questions",
"deep_solve",
"deep_question",
"deep_research",
@@ -79,6 +81,40 @@ def test_builtin_capability_registry_covers_documented_capabilities() -> None:
}
+async def test_ask_questions_capability_keeps_tool_selection_model_directed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, Any] = {}
+
+ class FakePipeline:
+ def __init__(
+ self,
+ *,
+ language: str = "en",
+ ) -> None:
+ captured["language"] = language
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ captured["ask_questions_mode"] = context.metadata.get("ask_questions_mode")
+ await stream.content("question", source="chat", stage="responding")
+
+ monkeypatch.setattr(
+ "deeptutor.capabilities.ask_questions.capability.AgenticChatPipeline",
+ FakePipeline,
+ )
+
+ context = UnifiedContext(user_message="Help me plan", language="zh")
+ capability = AskQuestionsCapability()
+ events = await _collect_events(lambda bus: capability.run(context, bus))
+
+ assert captured == {
+ "language": "zh",
+ "ask_questions_mode": True,
+ }
+ assert any(event.type == StreamEventType.CONTENT for event in events)
+
+
@pytest.mark.asyncio
async def test_chat_capability_streams_content_and_geogebra_context(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/services/session/test_context_builder.py b/tests/services/session/test_context_builder.py
index 2d0e4b1a9..a6836ba59 100644
--- a/tests/services/session/test_context_builder.py
+++ b/tests/services/session/test_context_builder.py
@@ -15,6 +15,7 @@ from deeptutor.services.session.context_builder import (
ContextBuildResult,
build_history_text,
count_tokens,
+ extract_ask_user_clarifications,
format_messages_as_transcript,
trim_incomplete_tail,
)
@@ -258,6 +259,47 @@ class TestBuildHistory:
)
assert len(history) == 1
+ def test_resolved_ask_user_answers_are_rehydrated_as_user_context(self) -> None:
+ message = {
+ "role": "assistant",
+ "content": "I adapted the explanation.",
+ "events": [
+ {
+ "type": "tool_result",
+ "metadata": {
+ "tool_metadata": {
+ "ask_user": {
+ "questions": [
+ {"id": "level", "prompt": "What have you studied?"},
+ {"id": "goal", "prompt": "What is your goal?"},
+ ]
+ }
+ }
+ },
+ },
+ {
+ "type": "progress",
+ "metadata": {
+ "ask_user_resolved": True,
+ "answers": [
+ {"questionId": "level", "text": "High-school calculus"},
+ {"questionId": "goal", "text": "Understand the intuition"},
+ ],
+ },
+ },
+ ],
+ }
+
+ clarification = extract_ask_user_clarifications(message)
+ assert "What have you studied?" in clarification
+ assert "High-school calculus" in clarification
+
+ history = ContextBuilder(store=MagicMock())._build_history("", [message])
+ assert history == [
+ {"role": "assistant", "content": "I adapted the explanation."},
+ {"role": "user", "content": clarification},
+ ]
+
# ---------------------------------------------------------------------------
# ContextBuilder._select_recent_messages
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 6dd2d08ae..63d2ce132 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -15,6 +15,7 @@ import {
BarChart3,
BookOpenText,
BrainCircuit,
+ CircleHelp,
Clapperboard,
Code2,
Compass,
@@ -259,6 +260,24 @@ const CAPABILITIES: CapabilityDef[] = [
defaultTools: ["web_search", "code_execution", "reason"],
secondary: true,
},
+ {
+ value: "ask_questions",
+ label: "Ask Questions",
+ description: "Let the model ask you questions to fill in missing context",
+ icon: CircleHelp,
+ allowedTools: [
+ "brainstorm",
+ "geogebra_analysis",
+ "web_search",
+ "code_execution",
+ "reason",
+ "paper_search",
+ "imagegen",
+ "videogen",
+ ],
+ defaultTools: [],
+ loopEngine: true,
+ },
{
value: "deep_question",
label: "Quiz",
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 89acde006..f15b33e47 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -110,6 +110,7 @@ interface NotebookReferenceGroup {
// the same wording the bubble carries.
export function getModeBadgeLabel(capability?: string | null): string {
if (!capability || capability === "chat") return "Chat";
+ if (capability === "ask_questions") return "Ask Questions";
if (capability === "deep_solve") return "Deep Solve";
if (capability === "deep_question") return "Quiz Generation";
if (capability === "deep_research") return "Deep Research";
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ccecc02a4..0cd2ec5fc 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -284,6 +284,8 @@
"Solve": "Solve",
"More Capabilities": "More Capabilities",
"Agent-loop driven modes": "Agent-loop driven modes",
+ "Ask Questions": "Ask Questions",
+ "Let the model ask you questions to fill in missing context": "Let the model ask you questions to fill in missing context",
"Question": "Question",
"No notebooks yet": "No notebooks yet",
"Create your first notebook": "Create your first notebook",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 73fa6edf3..767360e96 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -284,6 +284,8 @@
"Solve": "解题",
"More Capabilities": "更多能力",
"Agent-loop driven modes": "由对话引擎驱动的模式",
+ "Ask Questions": "主动提问",
+ "Let the model ask you questions to fill in missing context": "让模型向你提问,补充它尚不了解的上下文",
"Question": "题目",
"No notebooks yet": "暂无笔记本",
"Create your first notebook": "创建您的第一个笔记本",