DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(llm): one rule for a structured call a reasoning model starved
Bingxi Zhao (Frank)c31bed8aeb1b
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.pyindex a0f902777..741027618 100644--- a/deeptutor/agents/research/pipeline.py+++ b/deeptutor/agents/research/pipeline.py@@ -90,6 +90,7 @@ from deeptutor.runtime.stream_bus import StreamBusfrom deeptutor.services.config import parse_languagefrom deeptutor.services.config.loader import get_capability_paramsfrom deeptutor.services.llm import get_llm_config, prepare_multimodal_messages+from deeptutor.services.llm.structured_retry import payload_with_reasoning_retryfrom deeptutor.services.prompt import get_prompt_managerfrom deeptutor.services.prompt.language import append_language_directivefrom deeptutor.services.sandbox import exec_capability_available@@ -302,6 +303,29 @@ class ReportOutline:# ---------------------------------------------------------------------------+def _outline_payload_is_usable(payload: Any) -> bool:+ """Whether a decompose response actually carries sub-topics.++ The parser accepts a bare array as well as an object, so "usable" cannot+ be the generic "is a non-empty dict" the object-shaped callers use — an+ array answer would be thrown away and retried for nothing.+ """+ if isinstance(payload, list):+ return bool(payload)+ if isinstance(payload, dict):+ return bool(payload.get("sub_topics") or payload.get("subtopics"))+ return False+++def _report_outline_payload_is_usable(payload: Any) -> bool:+ """Whether a report-outline response actually carries sections."""+ if isinstance(payload, list):+ return bool(payload)+ if isinstance(payload, dict):+ return bool(payload.get("sections"))+ return False++class ResearchPipeline:"""One-shot orchestrator: instantiate per turn, call :meth:`run` once.@@ -835,21 +859,32 @@ class ResearchPipeline:trace_group="plan",research_status_key="decompose_target",)- step = await self._run_labeled_step(- client=client,- messages=messages,- tool_schemas=None,- protocol=_PROTOCOL_DECOMPOSE,- stream=stream,- stage="decomposing",- iter_meta=iter_meta,- max_tokens=self._budgets["outline"]["max_tokens"],- eager_sub_trace=False,++ async def _attempt(reasoning_effort: str | None) -> str:+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_DECOMPOSE,+ stream=stream,+ stage="decomposing",+ iter_meta=iter_meta,+ max_tokens=self._budgets["outline"]["max_tokens"],+ reasoning_effort=reasoning_effort,+ eager_sub_trace=False,+ )+ return step.text++ # Decompose asks for the whole outline in one shot, so a reasoning+ # model that spends the budget thinking returns nothing to parse and+ # the topic silently degrades to a single sub-topic — research's+ # version of the one-chapter book (#1316).+ data = await payload_with_reasoning_retry(+ _attempt, is_usable=_outline_payload_is_usable, logger_instance=logger)- return self._parse_outline(topic, step.text)+ return self._parse_outline(topic, data)- def _parse_outline(self, topic: str, raw: str) -> list[SubTopicItem]:- data = parse_json_response(raw, logger_instance=logger, fallback={})+ def _parse_outline(self, topic: str, data: Any) -> list[SubTopicItem]:if isinstance(data, list):iterable: list[Any] = dataelif isinstance(data, dict):@@ -1505,23 +1540,32 @@ class ResearchPipeline:research_status_key="report_outline",report_part="outline",)- step = await self._run_labeled_step(- client=client,- messages=messages,- tool_schemas=None,- protocol=_PROTOCOL_REPORT_OUTLINE,- stream=stream,- stage="reporting",- iter_meta=iter_meta,- max_tokens=self._budgets["report_outline"]["max_tokens"],- eager_sub_trace=False,++ async def _attempt(reasoning_effort: str | None) -> str:+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_REPORT_OUTLINE,+ stream=stream,+ stage="reporting",+ iter_meta=iter_meta,+ max_tokens=self._budgets["report_outline"]["max_tokens"],+ reasoning_effort=reasoning_effort,+ eager_sub_trace=False,+ )+ return step.text++ # Same one-shot payload, same starvation: an empty outline here costs+ # the reader the whole report structure.+ data = await payload_with_reasoning_retry(+ _attempt, is_usable=_report_outline_payload_is_usable, logger_instance=logger)- return self._parse_report_outline(topic, step.text, blocks)+ return self._parse_report_outline(topic, data, blocks)def _parse_report_outline(- self, topic: str, raw: str, blocks: list[ResearchedBlock]+ self, topic: str, data: Any, blocks: list[ResearchedBlock]) -> ReportOutline:- data = parse_json_response(raw, logger_instance=logger, fallback={})valid_ids = {rb.block.block_id for rb in blocks}title_to_id = {rb.block.sub_topic.lower(): rb.block.block_id for rb in blocks}@@ -2105,13 +2149,18 @@ class ResearchPipeline:def _build_client(self) -> Any:return build_openai_client(self.client_config)- 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(@@ -2125,6 +2174,7 @@ class ResearchPipeline:stage: str,iter_meta: dict[str, Any],max_tokens: int | None = None,+ reasoning_effort: str | None = None,final_meta: dict[str, Any] | None = None,eager_sub_trace: bool = True,) -> LabeledStepResult:@@ -2135,7 +2185,7 @@ class ResearchPipeline: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/book/agents/ideation_agent.py b/deeptutor/book/agents/ideation_agent.pyindex 667ecab73..f646a3ca5 100644--- a/deeptutor/book/agents/ideation_agent.py+++ b/deeptutor/book/agents/ideation_agent.py@@ -11,9 +11,9 @@ from __future__ import annotationsfrom typing import Anyfrom deeptutor.agents.base_agent import BaseAgent+from deeptutor.services.llm.structured_retry import json_with_reasoning_retryfrom ..inputs import IdeationContext-from ..json_retry import json_with_reasoning_retryfrom ..models import BookProposaldiff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pyindex 10aaf9d37..7d5c78636 100644--- a/deeptutor/book/agents/source_explorer.py+++ b/deeptutor/book/agents/source_explorer.py@@ -36,8 +36,8 @@ from typing import Anyfrom deeptutor.agents.base_agent import BaseAgentfrom deeptutor.core.context import UnifiedContextfrom deeptutor.runtime.stream_bus import StreamBus+from deeptutor.services.llm.structured_retry import json_with_reasoning_retry-from ..json_retry import json_with_reasoning_retryfrom ..models import (BookInputs,BookProposal,diff --git a/deeptutor/book/agents/spine_synthesizer.py b/deeptutor/book/agents/spine_synthesizer.pyindex 697b45e28..4f83565da 100644--- a/deeptutor/book/agents/spine_synthesizer.py+++ b/deeptutor/book/agents/spine_synthesizer.py@@ -35,8 +35,8 @@ import loggingfrom typing import Anyfrom deeptutor.agents.base_agent import BaseAgent+from deeptutor.services.llm.structured_retry import json_with_reasoning_retry-from ..json_retry import json_with_reasoning_retryfrom ..models import (BookProposal,Chapter,diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.pyindex d41d3cce8..478896815 100644--- a/deeptutor/book/blocks/_llm_writer.py+++ b/deeptutor/book/blocks/_llm_writer.py@@ -19,11 +19,10 @@ from deeptutor.services.llm import (complete as llm_complete,)from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT+from deeptutor.services.llm.structured_retry import json_payload_is_usablefrom deeptutor.services.prompt.language import append_language_directivefrom deeptutor.utils.json_parser import parse_json_response-from ..json_retry import json_payload_is_usable-async def llm_text(*,@@ -142,7 +141,7 @@ async def llm_json(we first honor the configured reasoning mode, then retry once with lowreasoning effort if parsing fails or the expected top-level key is missing— the same rule the Book pipeline agents apply via- :func:`deeptutor.book.json_retry.json_with_reasoning_retry`.+ :func:`deeptutor.services.llm.structured_retry.json_with_reasoning_retry`.A caller that supplies an effort of its own (book reader-facing blocks pass``"none"``) keeps that value on the retry, so a round that was deliberatelydiff --git a/deeptutor/book/json_retry.py b/deeptutor/book/json_retry.pydeleted file mode 100644index 7ac5b2784..000000000--- a/deeptutor/book/json_retry.py+++ /dev/null@@ -1,75 +0,0 @@-"""One retry for a structured call a reasoning model failed to answer.--A reasoning model pays for its hidden tokens out of the same ``max_tokens``-budget as its visible answer. When a prompt is large and the requested payload-is a whole JSON object — a book proposal, a spine, a page plan — the thinking-phase can consume the budget before a single character of JSON is emitted. The-provider does not raise: it returns a truncated body, or none at all, and-``parse_json_response`` hands back the caller's fallback. Every Book stage then-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 — 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-synthesiser, page planner) each parsed their own response and had no retry at-all.-"""--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---def json_payload_is_usable(payload: Any, expected_key: str | None) -> bool:- """Whether a parsed payload is worth keeping without a retry."""- if not isinstance(payload, dict) or not payload:- return False- if expected_key is None:- return True- return bool(payload.get(expected_key))---async def json_with_reasoning_retry(- run: Callable[[str | None], Awaitable[str]],- *,- expected_key: str | None = None,- logger_instance: Any = None,-) -> dict[str, Any]:- """Run ``run`` for a JSON object, retrying once at low reasoning effort.-- ``run`` receives the ``reasoning_effort`` to use (``None`` on the first- attempt = whatever the model is configured for) and returns the raw- response text. Returns ``{}`` when neither attempt produced an object, so- callers keep their existing "empty means fall back" handling.- """- payload = parse_json_response(await run(None), logger_instance=logger_instance, fallback={})- if json_payload_is_usable(payload, expected_key):- return payload-- retried = parse_json_response(- await run(RETRY_REASONING_EFFORT),- logger_instance=logger_instance,- fallback={},- )- if json_payload_is_usable(retried, expected_key):- return retried-- for candidate in (payload, retried):- if isinstance(candidate, dict) and candidate:- return candidate- return {}---__all__ = [- "json_payload_is_usable",- "json_with_reasoning_retry",-]diff --git a/deeptutor/services/llm/structured_retry.py b/deeptutor/services/llm/structured_retry.pynew file mode 100644index 000000000..4ff6b18a4--- /dev/null+++ b/deeptutor/services/llm/structured_retry.py@@ -0,0 +1,111 @@+"""One retry for a structured call a reasoning model failed to answer.++This is the project's single rule for that failure. Any step that asks a+model for a whole structured payload in one shot should route through it+rather than growing its own retry, because every such step has the same+two indistinguishable outcomes and the same escape hatch.++A reasoning model pays for its hidden tokens out of the same ``max_tokens``+budget as its visible answer. When a prompt is large and the requested payload+is a whole JSON object — a book proposal, a spine, a page plan — the thinking+phase can consume the budget before a single character of JSON is emitted. The+provider does not raise: it returns a truncated body, or none at all, and+``parse_json_response`` hands back the caller's fallback. Every Book stage then+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 — at+:data:`~deeptutor.services.llm.reasoning_params.RETRY_REASONING_EFFORT`, which+is where the choice of level and its reason live.++The streaming half of the same rule lives in+:class:`~deeptutor.runtime.agentic.labeled_step.LabeledStepResult`, whose+``reasoning_only`` flag reports the same starvation for a step that emits+labelled text rather than a payload: a round that produced reasoning, no+visible text and no tool calls. Two detectors, one disease — a budget spent+on hidden tokens — and one remedy, which is to ask again with thinking+turned down.+"""++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+++def json_payload_is_usable(payload: Any, expected_key: str | None) -> bool:+ """Whether a parsed payload is worth keeping without a retry."""+ if not isinstance(payload, dict) or not payload:+ return False+ if expected_key is None:+ return True+ return bool(payload.get(expected_key))+++async def payload_with_reasoning_retry(+ run: Callable[[str | None], Awaitable[str]],+ *,+ is_usable: Callable[[Any], bool],+ logger_instance: Any = None,+) -> Any:+ """Run ``run`` for a parsed payload, retrying once at low reasoning effort.++ ``run`` receives the ``reasoning_effort`` to use (``None`` on the first+ attempt = whatever the model is configured for) and returns the raw+ response text.++ ``is_usable`` decides what "the model answered" means for this call site,+ and it belongs to the caller: a step expecting an object keyed by+ ``sections`` and a step that also accepts a bare array cannot share one+ definition, and hard-coding either would make the other silently discard a+ good answer. Returns the first usable payload, else the first non-empty+ one, else ``None``.+ """+ first = parse_json_response(await run(None), logger_instance=logger_instance, fallback=None)+ if is_usable(first):+ return first++ retried = parse_json_response(+ await run(RETRY_REASONING_EFFORT),+ logger_instance=logger_instance,+ fallback=None,+ )+ if is_usable(retried):+ return retried++ for candidate in (first, retried):+ if candidate:+ return candidate+ return None+++async def json_with_reasoning_retry(+ run: Callable[[str | None], Awaitable[str]],+ *,+ expected_key: str | None = None,+ logger_instance: Any = None,+) -> dict[str, Any]:+ """The object-shaped case of :func:`payload_with_reasoning_retry`.++ Guarantees a ``dict`` — callers index it directly — so a model that+ answered with a bare array is treated as not having answered. Returns+ ``{}`` when neither attempt produced an object, so callers keep their+ existing "empty means fall back" handling.+ """+ payload = await payload_with_reasoning_retry(+ run,+ is_usable=lambda value: json_payload_is_usable(value, expected_key),+ logger_instance=logger_instance,+ )+ return payload if isinstance(payload, dict) else {}+++__all__ = [+ "json_payload_is_usable",+ "json_with_reasoning_retry",+ "payload_with_reasoning_retry",+]diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.pyindex b82f1594e..c5d3b8714 100644--- a/deeptutor/services/setup/init.py+++ b/deeptutor/services/setup/init.py@@ -87,7 +87,8 @@ DEFAULT_AGENTS_SETTINGS = {# both (#1316). Matched to `research` rather than pushed higher: the# same "long structured output" shape, the same accepted risk against# providers that cap `max_tokens`, and the low-effort retry in- # `book/json_retry.py` is what actually rescues a starved round.+ # `services/llm/structured_retry.py` is what actually rescues a starved+ # round."book": {"temperature": 0.5, "max_tokens": 12000},"chat": {"temperature": 0.2,diff --git a/tests/agents/research/test_block_loop_host_append.py b/tests/agents/research/test_block_loop_host_append.pyindex 96ce611eb..c4f6af2bf 100644--- a/tests/agents/research/test_block_loop_host_append.py+++ b/tests/agents/research/test_block_loop_host_append.py@@ -511,27 +511,28 @@ def test_report_outline_parser_repairs_missing_block_coverage(ResearchedBlock(block=b3, knowledge="Operational rollout."),]+ # The parser takes the decoded payload now: decoding moved out to the+ # caller so a starved response can be retried at lower reasoning effort+ # before anything tries to read sections out of it.outline = pipeline._parse_report_outline("AI safety operations",- """{- "title": "AI Safety Operations",- "sections": [- {- "id": "S1",- "title": "Background",- "intent": "Definitions and history",- "block_ids": ["block_1"]- },- {- "id": "S2",- "title": "## [S2]:Deployment",- "intent": "Rollout plan",- "block_ids": []- }- ]- }- """,+ "title": "AI Safety Operations",+ "sections": [+ {+ "id": "S1",+ "title": "Background",+ "intent": "Definitions and history",+ "block_ids": ["block_1"],+ },+ {+ "id": "S2",+ "title": "## [S2]:Deployment",+ "intent": "Rollout plan",+ "block_ids": [],+ },+ ],+ },blocks,)diff --git a/tests/services/llm/test_structured_retry.py b/tests/services/llm/test_structured_retry.pynew file mode 100644index 000000000..0ed32aa40--- /dev/null+++ b/tests/services/llm/test_structured_retry.py@@ -0,0 +1,118 @@+"""The project's one rule for a structured call a reasoning model starved.++A reasoning model pays for hidden tokens out of the same ``max_tokens`` as its+answer, so a one-shot structured call can come back empty with no error —+Book's spine collapsing to a single "Overview" chapter (#1316), the quiz plan+emitting zero templates (#1318), a research topic decomposing to one+sub-topic. The remedy is always the same: ask again with thinking turned down.++These tests pin the two things that make it safe to share: the retry actually+happens, and deciding "the model answered" stays with the caller.+"""++from __future__ import annotations++from typing import Any++import pytest++from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT+from deeptutor.services.llm.structured_retry import (+ json_payload_is_usable,+ json_with_reasoning_retry,+ payload_with_reasoning_retry,+)+++def _recorder(*responses: str):+ """A ``run`` that returns the given bodies in order, logging the effort."""+ efforts: list[str | None] = []+ remaining = list(responses)++ async def run(reasoning_effort: str | None) -> str:+ efforts.append(reasoning_effort)+ return remaining.pop(0) if remaining else ""++ return run, efforts+++async def test_a_usable_first_answer_is_not_paid_for_twice() -> None:+ run, efforts = _recorder('{"spine": [1]}')+ result = await json_with_reasoning_retry(run, expected_key="spine")+ assert result == {"spine": [1]}+ assert efforts == [None], "a good answer must not trigger a second call"+++async def test_a_starved_answer_is_retried_with_thinking_turned_down() -> None:+ run, efforts = _recorder("", '{"spine": [1]}')+ result = await json_with_reasoning_retry(run, expected_key="spine")+ assert result == {"spine": [1]}+ assert efforts == [None, RETRY_REASONING_EFFORT]+++async def test_the_expected_key_is_what_counts_as_answered() -> None:+ """A well-formed object missing the key is still a starved answer.++ This is the #1316 shape exactly: valid JSON, no content, and a caller that+ would have degraded silently.+ """+ run, efforts = _recorder('{"notes": "thinking..."}', '{"spine": [1]}')+ result = await json_with_reasoning_retry(run, expected_key="spine")+ assert result == {"spine": [1]}+ assert efforts == [None, RETRY_REASONING_EFFORT]+++async def test_two_starved_attempts_return_the_callers_empty_fallback() -> None:+ run, _ = _recorder("", "")+ assert await json_with_reasoning_retry(run, expected_key="spine") == {}+++async def test_the_object_shaped_helper_never_hands_back_a_list() -> None:+ """Callers of the object form index the result, so it must be a dict."""+ run, _ = _recorder("[1, 2, 3]", "[4]")+ assert await json_with_reasoning_retry(run, expected_key=None) == {}+++async def test_a_caller_that_accepts_an_array_keeps_its_array() -> None:+ """The generic form must not impose the object shape on everyone.++ Research's decompose accepts a bare array of sub-topics. Judging that+ "unusable" would retry a perfectly good answer and then discard it — a+ regression the object-shaped helper would have caused if it were the only+ entry point.+ """++ def accepts_anything_non_empty(payload: Any) -> bool:+ return bool(payload)++ run, efforts = _recorder("[1, 2, 3]")+ result = await payload_with_reasoning_retry(run, is_usable=accepts_anything_non_empty)+ assert result == [1, 2, 3]+ assert efforts == [None]+++async def test_nothing_usable_and_nothing_non_empty_is_none() -> None:+ run, _ = _recorder("", "")+ assert await payload_with_reasoning_retry(run, is_usable=bool) is None+++ ("payload", "expected_key", "usable"),+ [+ ({"spine": [1]}, "spine", True),+ ({"spine": []}, "spine", False),+ ({}, None, False),+ ({"anything": 1}, None, True),+ ([1], None, False),+ ("not json", None, False),+ ],+)+def test_object_usability_rule(payload: Any, expected_key: str | None, usable: bool) -> None:+ assert json_payload_is_usable(payload, expected_key) is usable