Skip to content

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

fix: make ask questions card deterministic

SeleiXi5c45c38e4a53
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index e1689120a..4d0a51680 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -314,6 +314,9 @@ class AgentLoop:
max_tokens=self.pipeline.loop_max_tokens,
tool_schemas=self.tool_schemas,
defer_visible_output=self.pipeline._has_capability_finish_guard(self.context),
+ tool_choice=(
+ self.pipeline.initial_tool_choice if state.rounds == 0 else None
+ ),
)
except Exception as exc:
# A mid-loop LLM failure (timeout / transient network) must not
@@ -666,6 +669,7 @@ class AgentLoop:
max_tokens: int,
tool_schemas: list[dict[str, Any]] | None = None,
defer_visible_output: bool = False,
+ tool_choice: str | None = None,
) -> LLMCallResult:
await self.pipeline._guard_context_window(messages, self.stream)
stage = LOOP_STAGE
@@ -701,7 +705,20 @@ class AgentLoop:
kwargs["stream_options"] = {"include_usage": True}
if tool_schemas:
kwargs["tools"] = tool_schemas
- kwargs["tool_choice"] = "auto"
+ available_tools = {
+ str((schema.get("function") or {}).get("name") or "")
+ for schema in tool_schemas
+ if isinstance(schema, dict)
+ }
+ kwargs["tool_choice"] = (
+ {
+ "type": "function",
+ "function": {"name": tool_choice},
+ }
+ if tool_choice and tool_choice in available_tools
+ else "auto"
+ )
+ forced_tool_choice = isinstance(kwargs.get("tool_choice"), dict)
# What this request actually carried, pinned now: the loop keeps
# appending to ``messages`` and the deferred loader keeps appending to
# ``tool_schemas``, so the turn's context budget is read off the last
@@ -790,7 +807,7 @@ class AgentLoop:
# <think> segments remain trace-only while DSML markup
# and its argument payload never enter either channel.
visible_content = dsml_filter.feed(content)
- if visible_content:
+ if visible_content and not forced_tool_choice:
await _emit_segments(think_filter.feed(visible_content))
for tc_delta in getattr(delta, "tool_calls", None) or []:
@@ -865,9 +882,10 @@ class AgentLoop:
break
dsml_tail = dsml_filter.flush()
- if dsml_tail:
- await _emit_segments(think_filter.feed(dsml_tail))
- await _emit_segments(think_filter.flush())
+ if not forced_tool_choice:
+ if dsml_tail:
+ await _emit_segments(think_filter.feed(dsml_tail))
+ await _emit_segments(think_filter.flush())
text = "".join(text_parts)
record_streamed_usage(
self.pipeline.usage,
@@ -910,6 +928,14 @@ class AgentLoop:
completion_metadata["answer_visible"] = True
completion_event_metadata = merge_trace_metadata(trace_meta, completion_metadata)
+ if forced_tool_choice and not tool_calls and text:
+ # Some compatibility providers accept ``tool_choice`` but ignore
+ # it. Do not lose their answer merely because it was buffered.
+ fallback_dsml = DSMLStreamFilter()
+ fallback_filter = InlineThinkFilter()
+ visible = fallback_dsml.feed(text) + fallback_dsml.flush()
+ await _emit_segments(fallback_filter.feed(visible) + fallback_filter.flush())
+
if not defer_visible_output:
await self.stream.progress(
"",
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 0c8e045b3..2096e7713 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -195,6 +195,7 @@ class AgenticChatPipeline:
max_rounds: int | None = None,
temperature: float | None = None,
max_tokens: int | None = None,
+ initial_tool_choice: str | None = None,
) -> None:
self.language = "zh" if language.lower().startswith("zh") else "en"
self.llm_config = get_llm_config()
@@ -214,6 +215,9 @@ class AgenticChatPipeline:
self._deferred_pool: list[Any] = []
self._exec_enabled = False
self._kb_manifests: list[KbManifest] = []
+ # A selected capability may require one specific tool on the first
+ # internal loop round. Later rounds return to model-directed selection.
+ self.initial_tool_choice = (initial_tool_choice or "").strip() or None
# The blocks the turn's system prompt was rendered from, kept for the
# context-budget breakdown (see ``measure_context_budget``).
self._last_prompt_blocks: list[PromptBlock] = []
diff --git a/deeptutor/capabilities/ask_questions/capability.py b/deeptutor/capabilities/ask_questions/capability.py
index 9551e5c0b..f856f1e26 100644
--- a/deeptutor/capabilities/ask_questions/capability.py
+++ b/deeptutor/capabilities/ask_questions/capability.py
@@ -10,7 +10,7 @@ from deeptutor.runtime.request_contracts import get_capability_request_schema
class AskQuestionsCapability(BaseCapability):
- """Let the model ask context-aware questions whenever they become useful."""
+ """Start the selected turn with a context-aware question card."""
manifest = CapabilityManifest(
name="ask_questions",
@@ -26,10 +26,13 @@ class AskQuestionsCapability(BaseCapability):
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)
+ # This is the first *agent-loop round of the selected turn*, not the
+ # first turn in the conversation. The prompt still receives the full
+ # history, so a turn selected much later asks a new, contextual question.
+ pipeline = AgenticChatPipeline(
+ language=context.language,
+ initial_tool_choice="ask_user",
+ )
await pipeline.run(context, stream)
diff --git a/deeptutor/capabilities/ask_questions/prompts/en/system.md b/deeptutor/capabilities/ask_questions/prompts/en/system.md
index 280588052..252e17647 100644
--- a/deeptutor/capabilities/ask_questions/prompts/en/system.md
+++ b/deeptutor/capabilities/ask_questions/prompts/en/system.md
@@ -1,8 +1,8 @@
# 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.
+The user explicitly selected Ask Questions for this turn. Begin this selected turn by calling `ask_user` exactly once with a useful question card. Do not write any answer, preamble, explanation, or narration before the tool call. "Begin this turn" refers to the current selected turn, which may be the second, third, tenth, or any later turn in the conversation—not the beginning of the whole conversation.
-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 choosing the question, study all available context: the current request, the full prior conversation, earlier `ask_user` questions and answers, memory, persona, attachments, selected sources, and knowledge-base context. Ask about the most valuable remaining unknown that only the user can supply. Even when substantial context already exists, use the card to refine a relevant goal, constraint, priority, difficulty, or preference instead of skipping the question.
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.
diff --git a/deeptutor/capabilities/ask_questions/prompts/zh/system.md b/deeptutor/capabilities/ask_questions/prompts/zh/system.md
index ed10a91f0..bd9612829 100644
--- a/deeptutor/capabilities/ask_questions/prompts/zh/system.md
+++ b/deeptutor/capabilities/ask_questions/prompts/zh/system.md
@@ -1,8 +1,8 @@
# 主动提问模式
-用户明确选择了此模式,希望你在对话中主动发现信息缺口,并在合适的时机向他们提问。此模式会持续用于后续对话轮次;它不要求你在每个请求开头提问。
+用户为当前 turn 明确选择了 Ask Questions。这个被选中的 turn 必须以一次 `ask_user` 调用开始,生成一张有价值的问题卡片。工具调用之前不要输出答案、开场白、解释或旁白。“当前 turn 开始”指本次选中模式后的内部首轮;它可以发生在整段对话的第 2、3、10 轮或更晚,而不是只指整段对话的开局。
-在每个 agent loop 轮次重新判断现有信息是否足够。先审视全部可用上下文:当前请求、此前所有对话、较早的 `ask_user` 问答、记忆、persona、附件、选中的来源、知识库内容,以及本轮工具刚发现的新情况。如果一个只有用户知道的答案会实质性改善准确性、个性化程度或教学效果,就调用 `ask_user`;这个时机可以出现在当前请求的第一轮,也可以在后续工具调用暴露信息缺口之后,或在未来第 2、3、10 个对话轮次。若信息已经足够,则直接继续,不要为了体现模式存在而提问。
+选择问题前,先审视全部可用上下文:当前请求、此前所有对话、较早的 `ask_user` 问答、记忆、persona、附件、选中的来源和知识库内容。询问当前最有价值、且只能由用户补充的未知信息。即使已有 context 很丰富,也不要跳过卡片;应进一步澄清与当前请求相关的目标、限制、优先级、难点或偏好。
调用前必须检查历史澄清记录,不要重复询问用户已经回答或明确说明的事实。若新情况与旧答案冲突,只询问发生变化的部分,并明确指出需要更新的原因。不要问空泛套话,不要为了拖延而要求确认。问题应少而具体,一次集中提出 1–4 个高信息量问题;只有在选项确实有帮助时才提供简洁且有意义的选项,否则允许自由输入。可关注真实目标、已有知识、约束条件、此前尝试、具体卡点、目标受众,以及期望的深度或输出形式。
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index 86896ec01..fce384656 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -1329,6 +1329,64 @@ async def test_ask_user_available_every_round(monkeypatch: pytest.MonkeyPatch) -
assert loop_tools == {"web_search", "ask_user"}
+async def test_initial_tool_choice_only_forces_first_round_and_hides_preamble(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _PausingRegistry(_Registry):
+ async def execute(self, name: str, **kwargs):
+ self.executed.append({"name": name, "kwargs": kwargs})
+ return ToolResult(
+ content="Asked the user.",
+ success=True,
+ pause_for_user={"questions": [{"id": "q1", "prompt": "What matters most?"}]},
+ )
+
+ registry = _PausingRegistry()
+ client = _ScriptedChatClient(
+ [
+ [
+ _llm_chunk(content="Let me ask one thing first."),
+ _llm_chunk(
+ tool_calls=[
+ {
+ "id": "call-1",
+ "name": "ask_user",
+ "arguments": json.dumps(
+ {"questions": [{"id": "q1", "prompt": "What matters most?"}]}
+ ),
+ }
+ ]
+ ),
+ ],
+ [_llm_chunk(content="Completed with the added context.")],
+ ]
+ )
+ pipeline = AgenticChatPipeline(language="en", initial_tool_choice="ask_user")
+ pipeline.registry = registry
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["ask_user"])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ async def _waiter():
+ return {"text": "Accuracy"}
+
+ events = await _run(
+ pipeline,
+ UnifiedContext(
+ session_id="s1",
+ user_message="Help with this task",
+ metadata={"wait_for_user_reply": _waiter},
+ ),
+ )
+
+ assert client.calls[0]["tool_choice"] == {
+ "type": "function",
+ "function": {"name": "ask_user"},
+ }
+ assert client.calls[1]["tool_choice"] == "auto"
+ assert _contents(events) == ["Completed with the added context."]
+
+
@pytest.mark.asyncio
async def test_ask_user_pause_resumes_and_streams_interleaved(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.py
index d1402e2f3..537223a45 100644
--- a/tests/agents/chat/test_language_prompts.py
+++ b/tests/agents/chat/test_language_prompts.py
@@ -97,12 +97,13 @@ def test_ask_questions_plugin_system_prompt_uses_localized_fallback(
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_user` 调用开始" in zh_prompt
+ assert "第 2、3、10 轮" in zh_prompt
+ assert "此前所有对话" in zh_prompt
assert "## ask_questions" in en_prompt
assert "Ask Questions mode" in en_prompt
assert "second, third, tenth" in en_prompt
+ assert "calling `ask_user` exactly once" in en_prompt
def test_legacy_chat_agent_system_prompt_uses_selected_language() -> None:
diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.py
index c1c5d3c54..021d276f1 100644
--- a/tests/core/test_capabilities_runtime.py
+++ b/tests/core/test_capabilities_runtime.py
@@ -82,7 +82,7 @@ def test_builtin_capability_registry_covers_documented_capabilities() -> None:
@pytest.mark.asyncio
-async def test_ask_questions_capability_keeps_tool_selection_model_directed(
+async def test_ask_questions_capability_forces_card_on_selected_turn(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured: dict[str, Any] = {}
@@ -92,8 +92,10 @@ async def test_ask_questions_capability_keeps_tool_selection_model_directed(
self,
*,
language: str = "en",
+ initial_tool_choice: str | None = None,
) -> None:
captured["language"] = language
+ captured["initial_tool_choice"] = initial_tool_choice
async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
captured["ask_questions_mode"] = context.metadata.get("ask_questions_mode")
@@ -110,6 +112,7 @@ async def test_ask_questions_capability_keeps_tool_selection_model_directed(
assert captured == {
"language": "zh",
+ "initial_tool_choice": "ask_user",
"ask_questions_mode": True,
}
assert any(event.type == StreamEventType.CONTENT for event in events)