Skip to content

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

fix(question): tell a starved plan apart from an empty one, and retry it

Bingxi Zhao (Frank)0027051b3264
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index 1f9522fc8..8548e00f4 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -79,6 +79,7 @@ from deeptutor.runtime.registry.tool_registry import get_tool_registry
from deeptutor.runtime.stream_bus import StreamBus
from deeptutor.services.config import parse_language
from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages
+from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
from deeptutor.services.prompt import get_prompt_manager
from deeptutor.services.prompt.language import append_language_directive
from deeptutor.services.sandbox import exec_capability_available
@@ -138,7 +139,15 @@ DEFAULT_MAX_EXPLORE_ITERATIONS = 8
DEFAULT_MAX_QUIZ_ITERATIONS_PER_QUESTION = 5
DEFAULT_MAX_TOKENS = 4000
EXPLORE_FINISH_MAX_TOKENS = 3000
-PLAN_MAX_TOKENS = 2000
+# Plan is the one step asked for a whole JSON object in a single shot, and it
+# was the tightest budget in this file — below even the 4096 the ``question``
+# capability ships with. A reasoning model pays for its hidden tokens out of
+# this same allowance, so on a rich exploration trace it could spend the lot
+# deliberating and end the stream before writing a single template (#1318).
+# Reachable, not generous: the plan itself is a few hundred tokens, the rest
+# is headroom to think in, and the low-effort retry below covers the models
+# that want more than any fixed number.
+PLAN_MAX_TOKENS = 6000
QUIZ_FINISH_MAX_TOKENS = 3000
REPAIR_MAX_TOKENS = 2500
FINALIZATION_REPAIR_ATTEMPTS = 2
@@ -748,6 +757,36 @@ class QuestionPipeline:
iter_meta=iter_meta,
max_tokens=PLAN_MAX_TOKENS,
)
+ if step.reasoning_only:
+ # The round was all thinking and no plan. Parsing it would hand
+ # back an empty object indistinguishable from a model that had
+ # nothing to say, and phase 3 iterates the templates — so a quiz
+ # of zero questions would ship with no error anywhere (#1318).
+ # Ask once more with thinking turned down, which is what frees
+ # the budget for the answer.
+ await stream.progress(
+ self._t(
+ "notices.plan_reasoning_retry",
+ default=(
+ "The planner spent its whole budget reasoning; "
+ "asking again with less thinking."
+ ),
+ ),
+ source=SOURCE,
+ stage=STAGE_PLANNING,
+ metadata={"trace_kind": "warning"},
+ )
+ step = await self._run_labeled_step(
+ client=client,
+ messages=messages,
+ tool_schemas=None,
+ protocol=_PROTOCOL_PLAN,
+ stream=stream,
+ stage=STAGE_PLANNING,
+ iter_meta=iter_meta,
+ max_tokens=PLAN_MAX_TOKENS,
+ reasoning_effort=RETRY_REASONING_EFFORT,
+ )
plan = self._parse_plan(
step.text,
requested=num_questions,
@@ -1681,13 +1720,18 @@ class QuestionPipeline:
# ------------------------------------------------------------------
# LLM call helpers
# ------------------------------------------------------------------
- def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:
+ def _completion_kwargs(
+ self, max_tokens: int, reasoning_effort: str | None = None
+ ) -> dict[str, Any]:
return build_completion_kwargs(
temperature=self._temperature,
model=self.model,
max_tokens=max_tokens,
binding=self.binding,
- reasoning_effort=self.reasoning_effort,
+ # A step may turn thinking down for one call (a retry after the
+ # model spent the whole budget on it); otherwise the configured
+ # level stands.
+ reasoning_effort=reasoning_effort or self.reasoning_effort,
)
async def _run_labeled_step(
@@ -1701,6 +1745,7 @@ class QuestionPipeline:
stage: str,
iter_meta: dict[str, Any],
max_tokens: int = DEFAULT_MAX_TOKENS,
+ reasoning_effort: str | None = None,
final_meta: dict[str, Any] | None = None,
eager_sub_trace: bool = True,
) -> LabeledStepResult:
@@ -1708,7 +1753,7 @@ class QuestionPipeline:
client=client,
model=self.model,
messages=messages,
- completion_kwargs=self._completion_kwargs(max_tokens),
+ completion_kwargs=self._completion_kwargs(max_tokens, reasoning_effort),
tool_schemas=tool_schemas,
allowed_labels=protocol.allowed,
final_labels=protocol.final,
diff --git a/deeptutor/agents/question/prompts/en/pipeline.yaml b/deeptutor/agents/question/prompts/en/pipeline.yaml
index 2a20b3420..cb8eb30f6 100644
--- a/deeptutor/agents/question/prompts/en/pipeline.yaml
+++ b/deeptutor/agents/question/prompts/en/pipeline.yaml
@@ -328,6 +328,7 @@ notices:
context_window_guard: "Trimmed older tool results to keep within the model's context window."
final_protocol_failed: "The model still did not produce a valid FINISH reply after the finalization prompt."
plan_count_mismatch: "Plan returned {got} templates instead of {requested}; proceeding with what we have."
+ plan_reasoning_retry: "The planner spent its whole budget reasoning and produced no plan; asking again with less thinking."
repair_attempted: "The previous question payload was invalid; repairing the schema once."
repair_failed: "Repair did not fully fix the question; emitting the best-effort version."
tool_summarizer_failed: "Tool summarizer could not produce a summary; passing raw tool result forward."
diff --git a/deeptutor/agents/question/prompts/zh/pipeline.yaml b/deeptutor/agents/question/prompts/zh/pipeline.yaml
index 9c643b102..546f5f1db 100644
--- a/deeptutor/agents/question/prompts/zh/pipeline.yaml
+++ b/deeptutor/agents/question/prompts/zh/pipeline.yaml
@@ -309,6 +309,7 @@ notices:
context_window_guard: "为了保持在模型上下文窗口内,裁剪了较早的工具结果。"
final_protocol_failed: "最终化提示之后模型仍未给出有效的 FINISH 回复。"
plan_count_mismatch: "规划返回了 {got} 个 template(要求 {requested} 个),按实际数量继续。"
+ plan_reasoning_retry: "规划阶段把预算全部用在思考上,没有产出方案;正在降低思考强度重试。"
repair_attempted: "上一轮题目载荷不合法;做一次 schema 修复。"
repair_failed: "修复未能完全修正题目;使用尽力版本输出。"
tool_summarizer_failed: "工具结果概括失败;将把原始工具结果传给下一轮。"
diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.py
index 8224e453c..0aa268efb 100644
--- a/deeptutor/book/blocks/_llm_writer.py
+++ b/deeptutor/book/blocks/_llm_writer.py
@@ -18,10 +18,11 @@ from deeptutor.services.llm import (
from deeptutor.services.llm import (
complete as llm_complete,
)
+from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
from deeptutor.services.prompt.language import append_language_directive
from deeptutor.utils.json_parser import parse_json_response
-from ..json_retry import RETRY_REASONING_EFFORT, json_payload_is_usable
+from ..json_retry import json_payload_is_usable
async def llm_text(
diff --git a/deeptutor/book/json_retry.py b/deeptutor/book/json_retry.py
index 17bda8d98..7ac5b2784 100644
--- a/deeptutor/book/json_retry.py
+++ b/deeptutor/book/json_retry.py
@@ -10,9 +10,9 @@ degrades silently — most visibly the spine, which collapses to one placeholder
"Overview" chapter (#1316).
The escape hatch is to ask the same model for the same thing with its thinking
-turned down, which frees the budget for the answer. ``"low"`` rather than
-``"minimal"``: local/Qwen models served via vLLM reject ``"minimal"``, and it
-disables thinking outright.
+turned down, which frees the budget for the answer — at
+:data:`~deeptutor.services.llm.reasoning_params.RETRY_REASONING_EFFORT`, which
+is where the choice of level and its reason live.
This is the shared half of what ``blocks/_llm_writer.llm_json`` already did for
block generators; the pipeline agents (ideation, source explorer, spine
@@ -25,12 +25,9 @@ from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import Any
+from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
from deeptutor.utils.json_parser import parse_json_response
-#: Reasoning level used for the second attempt. Not ``"minimal"`` — see module
-#: docstring.
-RETRY_REASONING_EFFORT = "low"
-
def json_payload_is_usable(payload: Any, expected_key: str | None) -> bool:
"""Whether a parsed payload is worth keeping without a retry."""
@@ -73,7 +70,6 @@ async def json_with_reasoning_retry(
__all__ = [
- "RETRY_REASONING_EFFORT",
"json_payload_is_usable",
"json_with_reasoning_retry",
]
diff --git a/deeptutor/runtime/agentic/labeled_step.py b/deeptutor/runtime/agentic/labeled_step.py
index af83c9c45..ccd7af20c 100644
--- a/deeptutor/runtime/agentic/labeled_step.py
+++ b/deeptutor/runtime/agentic/labeled_step.py
@@ -121,6 +121,19 @@ class LabeledStepResult:
# Anthropic's signed thinking blocks, which must be replayed verbatim and
# cannot be reconstructed from text.
thinking_blocks: tuple[dict[str, Any], ...] = ()
+ # The round was all thinking and no answer: no label was ever emitted,
+ # ``text`` came back empty, and the model *did* reason (inline ``<think>``
+ # or the provider's own reasoning channel). A reasoning model pays for its
+ # hidden tokens out of the same ``max_tokens`` as its answer, so a long
+ # enough deliberation ends the stream before the label.
+ #
+ # Callers need this because ``text == ""`` cannot say which happened: the
+ # scratchpad is stripped on the way out precisely so a truncated one never
+ # reaches a reader, which leaves "starved mid-thought" and "the model
+ # genuinely said nothing" byte-identical. Only the first is worth asking
+ # again with thinking turned down. Quiz's plan step read the empty string
+ # as a plan of zero questions and emitted no quiz at all (#1318).
+ reasoning_only: bool = False
async def run_labeled_step(
@@ -191,6 +204,9 @@ async def run_labeled_step(
# existing behavior; we always force the cleanup when a prelude was
# detected so the synthetic markers we recorded don't leak out.
saw_pre_label_think = False
+ # No label ever arrived, so ``LABEL_UNKNOWN`` below is our word rather
+ # than the model's. Half of ``reasoning_only``; see the field's docstring.
+ never_labelled = False
sub_trace_opened = False
content_acc: list[str] = []
# A reasoning model may open a ``<think>`` block *after* the protocol
@@ -593,6 +609,7 @@ async def run_labeled_step(
await _emit_text(after_label)
if label is None:
label = LABEL_UNKNOWN
+ never_labelled = True
if label_buf:
await _emit_text(label_buf)
label_buf = ""
@@ -627,12 +644,22 @@ async def run_labeled_step(
text = clean_thinking_tags(text, binding, model)
ordered_tool_calls = tc_acc.ordered()
ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]
+ reasoning_acc_text = "".join(reasoning_acc)
return LabeledStepResult(
label=label,
text=text,
tool_calls=ordered_tool_calls,
finish_reason=finish_reason_seen,
stream_idle_timeout=stream_idle_timeout,
- reasoning_content="".join(reasoning_acc),
+ reasoning_content=reasoning_acc_text,
thinking_blocks=tuple(thinking_blocks),
+ # Tool calls count as reaching the answer: the round acted, it just
+ # did not narrate. Only a round that produced nothing but thinking
+ # is worth asking again.
+ reasoning_only=(
+ never_labelled
+ and not text
+ and not ordered_tool_calls
+ and bool(reasoning_acc_text or saw_pre_label_think)
+ ),
)
diff --git a/deeptutor/services/llm/reasoning_params.py b/deeptutor/services/llm/reasoning_params.py
index 560d73be0..17739ab38 100644
--- a/deeptutor/services/llm/reasoning_params.py
+++ b/deeptutor/services/llm/reasoning_params.py
@@ -4,6 +4,12 @@ from __future__ import annotations
from typing import Any
+#: Reasoning level to ask for on a second attempt, after a first one spent its
+#: whole ``max_tokens`` budget thinking and returned no answer. ``"low"``
+#: rather than ``"minimal"``: local/Qwen models served via vLLM reject
+#: ``"minimal"``, and it disables thinking outright rather than trimming it.
+RETRY_REASONING_EFFORT = "low"
+
_THINKING_STYLE_MAP = {
"thinking_type": lambda enabled: {"thinking": {"type": "enabled" if enabled else "disabled"}},
"enable_thinking": lambda enabled: {"enable_thinking": enabled},
@@ -174,6 +180,7 @@ def build_openai_compatible_reasoning_kwargs(
__all__ = [
+ "RETRY_REASONING_EFFORT",
"build_openai_compatible_reasoning_kwargs",
"default_reasoning_effort_for",
]
diff --git a/tests/agents/question/test_pipeline.py b/tests/agents/question/test_pipeline.py
index 26a20d49c..69a3baf85 100644
--- a/tests/agents/question/test_pipeline.py
+++ b/tests/agents/question/test_pipeline.py
@@ -24,6 +24,8 @@ from deeptutor.agents.question.pipeline import (
QuizPlan,
QuizTemplate,
)
+from deeptutor.runtime.agentic import LabeledStepResult
+from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
# ---------------------------------------------------------------------------
# Test helpers
@@ -1028,3 +1030,103 @@ def test_parse_quiz_payload_tolerates_trailing_brace_prose() -> None:
assert parsed["question"] == "What is 2+2?"
assert parsed["correct_answer"] == "4"
assert parsed["explanation"] == "basic arithmetic"
+
+
+# ---------------------------------------------------------------------------
+# plan starvation (#1318)
+# ---------------------------------------------------------------------------
+
+
+async def _plan_with_steps(
+ steps: list[LabeledStepResult],
+) -> tuple[QuizPlan, list[dict[str, Any]], list[dict[str, Any]]]:
+ """Drive ``_plan`` against scripted labeled-step outcomes.
+
+ Returns the plan, the bus's progress events, and the kwargs each
+ ``_run_labeled_step`` call was made with.
+ """
+ pipeline = _make_pipeline()
+ bus = _StubStreamBus()
+ calls: list[dict[str, Any]] = []
+ remaining = list(steps)
+
+ async def _fake_step(**kwargs: Any) -> LabeledStepResult:
+ calls.append(kwargs)
+ return remaining.pop(0)
+
+ with patch.object(QuestionPipeline, "_run_labeled_step", side_effect=_fake_step):
+ plan = await pipeline._plan(
+ user_message="quiz me on gradients",
+ exploration_trace="",
+ num_questions=2,
+ difficulty="medium",
+ allowed_types=[],
+ per_type_counts={},
+ stream=bus,
+ client=object(),
+ )
+ return plan, bus.progress_events, calls
+
+
+_PLAN_JSON = json.dumps(
+ {
+ "analysis": "two ideas",
+ "templates": [
+ {"question_id": "q1", "topic": "chain rule", "question_type": "short_answer"},
+ {"question_id": "q2", "topic": "gradients", "question_type": "short_answer"},
+ ],
+ }
+)
+
+
+def test_plan_starved_by_reasoning_is_asked_again_with_less_thinking() -> None:
+ """The reporter's quiz: round one is all scratchpad, so no quiz shipped.
+
+ ``text=""`` alone could not justify a retry — it is also what a model
+ with nothing to say returns — so the plan step degraded to zero templates
+ and phase 3, which iterates them, emitted no questions at all.
+ """
+ plan, progress, calls = asyncio.run(
+ _plan_with_steps(
+ [
+ LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
+ LabeledStepResult(label="FINISH", text=_PLAN_JSON),
+ ]
+ )
+ )
+
+ assert [t.topic for t in plan.templates] == ["chain rule", "gradients"]
+ assert len(calls) == 2
+ assert calls[0].get("reasoning_effort") is None
+ assert calls[1]["reasoning_effort"] == RETRY_REASONING_EFFORT
+ assert any("reasoning" in event["message"].lower() for event in progress)
+
+
+def test_plan_that_answers_first_time_is_not_asked_twice() -> None:
+ """The retry costs a whole LLM round; a healthy plan must not pay it."""
+ plan, _progress, calls = asyncio.run(
+ _plan_with_steps([LabeledStepResult(label="FINISH", text=_PLAN_JSON)])
+ )
+
+ assert len(plan.templates) == 2
+ assert len(calls) == 1
+
+
+def test_plan_still_empty_after_the_retry_keeps_the_existing_behaviour() -> None:
+ """Two starved rounds change nothing about what ``_plan`` returns.
+
+ Whether an under-filled plan should warn or fail is a separate product
+ question (#1325); this pins that the retry did not quietly answer it.
+ """
+ plan, progress, calls = asyncio.run(
+ _plan_with_steps(
+ [
+ LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
+ LabeledStepResult(label="UNKNOWN", text="", reasoning_only=True),
+ ]
+ )
+ )
+
+ assert plan.templates == []
+ assert len(calls) == 2
+ assert any("2" in event["message"] or "0" in event["message"] for event in progress)
diff --git a/tests/core/test_labeled_step_think_prelude.py b/tests/core/test_labeled_step_think_prelude.py
index 46a79b334..419d949c2 100644
--- a/tests/core/test_labeled_step_think_prelude.py
+++ b/tests/core/test_labeled_step_think_prelude.py
@@ -632,3 +632,63 @@ async def test_post_label_think_split_across_chunks_is_not_leaked() -> None:
assert "hidden" not in content
assert "hidden" in thinking
assert content.strip() == "ok done".strip()
+
+
+# ------------------- "all thinking, no answer" -------------------
+#
+# A reasoning model pays for its hidden tokens out of the same ``max_tokens``
+# as its answer, so a long enough deliberation ends the stream before the
+# protocol label. What comes back is ``label=UNKNOWN, text=""`` — byte-for-byte
+# what a model that genuinely said nothing returns, because the scratchpad is
+# stripped on the way out. Only the first is worth asking again with thinking
+# turned down, so the step has to say which it was (#1318).
+
+
+async def test_stream_ending_inside_the_prelude_reports_reasoning_only() -> None:
+ """Budget gone mid-``<think>``: no label, no text, but the model did think."""
+ _events, result = await _run([_chunk("<think>Let me work through the "), _chunk("topics")])
+
+ assert result.text == ""
+ assert result.reasoning_only is True
+
+
+async def test_reasoning_channel_without_an_answer_reports_reasoning_only() -> None:
+ """Same starvation on providers that stream reasoning out of band."""
+ _events, result = await _run([_reasoning_chunk("planning"), _reasoning_chunk(" more")])
+
+ assert result.text == ""
+ assert result.reasoning_only is True
+
+
+async def test_a_genuinely_empty_round_is_not_reasoning_only() -> None:
+ """Nothing to retry at lower effort: the model never spent budget thinking."""
+ _events, result = await _run([_chunk("")])
+
+ assert result.text == ""
+ assert result.reasoning_only is False
+
+
+async def test_a_round_that_reached_its_label_is_not_reasoning_only() -> None:
+ """Thinking that finished and answered is the normal path, not a failure."""
+ _events, result = await _run([_chunk("<think>weighing it</think>"), _chunk("FINISH: done")])
+
+ assert result.text.strip() == "done"
+ assert result.reasoning_only is False
+
+
+async def test_thinking_that_ends_in_a_tool_call_is_not_reasoning_only() -> None:
+ """The round acted; it just never narrated. Re-asking would repeat the call."""
+ _events, result = await _run(
+ [
+ _reasoning_chunk("which tool?"),
+ _tc_chunk(index=0, tc_id="c1", name="rag", arguments='{"query":"x"}'),
+ ]
+ )
+
+ assert result.tool_calls
+ assert result.reasoning_only is False