DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(agent-loop): recover bounded reasoning-only finishes (#1402)
evan188199-tech24d3db124c91
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex f98664b8b..a129d194c 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -114,6 +114,10 @@ loop:Your previous round produced only internal reasoning — no tool call andno user-facing answer. Continue now: either call the tools to executeyour plan, or write the final user-facing answer directly.+ repeat_reasoning_only_nudge: |-+ Your previous rounds produced only internal reasoning — no tool call and+ no user-facing answer. Do not reason further. Select the most likely next+ action and produce it now.knowledge_base_seed:header: |-@@ -143,6 +147,7 @@ notices:ask_questions_fallback_prompt: "What is the most important goal or constraint I should account for?"image_fallback: "Model does not support image input; retrying without images."empty_final_response: "I could not produce a useful response from the model output. Please try again or narrow the request."+ reasoning_only_final_response: "The model produced internal reasoning but no usable answer. Please try again or narrow the request."empty_finish_nudged: "The round produced only internal reasoning; asked the model to continue."empty:diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex 378928355..6be0a2d46 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -79,6 +79,9 @@ loop:finish_empty_nudge: |-你上一轮只输出了内部推理——既没有调用工具,也没有写出面向用户的回答。现在继续:要么调用工具执行你计划好的步骤,要么直接写出最终回答。+ repeat_reasoning_only_nudge: |-+ 前几轮都只有内部推理,没有工具调用,也没有面向用户的回答。不要再继续推演;+ 请选择最可能的下一步行动,并立即产出它。knowledge_base_seed:header: |-@@ -107,6 +110,7 @@ notices:ask_questions_fallback_prompt: "我最需要了解的目标或限制条件是什么?"image_fallback: "当前模型不支持图片输入;将去除图片后重试。"empty_final_response: "未能从模型输出中得到有效回答。请重试或缩小问题范围。"+ reasoning_only_final_response: "模型产生了内部推理,但没有可用回答。请重试或缩小问题范围。"empty_finish_nudged: "模型这一轮只有内部推理,已提示其继续执行。"empty:diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex 75fe6caaa..dc1aacc88 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -79,6 +79,11 @@ LOOP_STAGE = "responding"# A single additional tool-less hard finish follows if all of these rounds# still request tools, making the total upper bound ``exploration + 4``.MAX_SETTLEMENT_ROUNDS = 3+# Reasoning-only completions can recur when a model rewrites its plan instead+# of acting. Give it a stronger directive on the second miss, then use the+# forced tool-less finish instead of spending the full exploration budget on+# the same failure.+MAX_REASONING_ONLY_RECOVERIES = 2_TRUNCATED_FINISH_REASONS = frozenset({"length", "max_tokens", "max_output_tokens"})# The SDK already retries failures that happen before response headers. These# short outer retries also cover SSE connections that fail before yielding any@@ -291,7 +296,7 @@ class AgentLoop:settlement_label = self.pipeline._t("labels.final_response", default="Final response")exploration_budget = max(1, self.pipeline.effective_max_rounds(self.context))settlement_started = False- nudged_empty_finish = False+ reasoning_only_recoveries = 0finish_redirect_used = Falsecontinued_answer_parts: list[str] = []while True:@@ -408,13 +413,20 @@ class AgentLoop:)self._append_loop_instruction(messages, instruction)continue- if not final_text and not nudged_empty_finish:+ if not final_text:# The round produced only internal reasoning (e.g. the# whole reply inside <think>) — the model planned but# never acted. Keep its raw text in-conversation (the- # plan/script lives there) and nudge it once to act- # instead of falling back to an empty answer.- nudged_empty_finish = True+ # plan/script lives there) and ask it to act instead of+ # accepting an empty answer.+ reasoning_only_recoveries += 1+ logger.warning(+ "agent loop finish produced reasoning only "+ "(round=%d, finish_reason=%s, reasoning_chars=%d)",+ state.rounds,+ result.finish_reason or "none",+ len(result.reasoning_content) + len(result.text),+ )await self.stream.progress(self.pipeline._t("notices.empty_finish_nudged",@@ -429,6 +441,24 @@ class AgentLoop:)if result.text:messages.append(_assistant_round_message(result))+ if reasoning_only_recoveries >= MAX_REASONING_ONLY_RECOVERIES:+ self._append_loop_instruction(+ messages,+ self.pipeline._t(+ "loop.repeat_reasoning_only_nudge",+ default=(+ "Your previous rounds produced only internal "+ "reasoning — no tool call and no user-facing "+ "answer. Do not reason further. Select the most "+ "likely next action and produce it now."+ ),+ ),+ )+ return await self._forced_finish(+ messages,+ state,+ continued_answer_parts=continued_answer_parts,+ )self._append_loop_instruction(messages,self.pipeline._t(@@ -678,10 +708,14 @@ class AgentLoop:continued_answer_parts=continued_answer_parts,)state.rounds += 1+ reasoning_without_answer = bool(result.reasoning_content) or bool(+ result.text.strip() and not self._clean(result.text)+ )return await self._finalize_finish(result.text,visible_text=result.visible_text,continued_answer_parts=continued_answer_parts,+ empty_response_kind=("reasoning_only" if reasoning_without_answer else None),provider_response_state=_provider_response_state(result.response_output_items,result.reasoning_content,@@ -696,6 +730,7 @@ class AgentLoop:visible_text: str | None = None,continued_answer_parts: list[str] | None = None,allow_empty: bool = False,+ empty_response_kind: str | None = None,provider_response_state: dict[str, Any] | None = None,) -> LoopOutcome:cleaned_text = self._clean(raw_text)@@ -709,13 +744,22 @@ class AgentLoop:if not final_text and not allow_empty:# The finish round produced no usable text; nothing streamed to# the user, so emit a fallback answer here.- final_text = self.pipeline._t(- "notices.empty_final_response",- default=(- "I could not produce a useful response from the model "- "output. Please try again or narrow the request."- ),- )+ if empty_response_kind == "reasoning_only":+ final_text = self.pipeline._t(+ "notices.reasoning_only_final_response",+ default=(+ "The model produced internal reasoning but no usable "+ "answer. Please try again or narrow the request."+ ),+ )+ else:+ final_text = self.pipeline._t(+ "notices.empty_final_response",+ default=(+ "I could not produce a useful response from the model "+ "output. Please try again or narrow the request."+ ),+ )await self.pipeline._emit_protocol_fallback_final_response(self.stream, final_text)return LoopOutcome(final_text=final_text,diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex 38048cc04..b11fb0692 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -2504,15 +2504,16 @@ async def test_length_finish_reason_continues_within_bounded_settlement(@pytest.mark.asyncio-async def test_repeated_empty_finish_stops_after_one_nudge(+async def test_repeated_reasoning_only_finishes_are_bounded(monkeypatch: pytest.MonkeyPatch,) -> None:- """An empty provider response gets one recovery chance, never a loop."""+ """A second reasoning-only miss gets a stronger directive and a hard finish."""registry = _Registry()client = _ScriptedChatClient([[_llm_chunk(content="<think>first empty</think>")],[_llm_chunk(content="<think>still empty</think>")],+ [_llm_chunk(content="Recovered after the hard finish.")],])pipeline = AgenticChatPipeline(language="en")@@ -2523,10 +2524,42 @@ async def test_repeated_empty_finish_stops_after_one_nudge(events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="Answer"))- assert client.call_count == 2+ assert client.call_count == 3+ forced_request = client.calls[2]["messages"]+ forced_instruction = str(forced_request[-1]["content"])+ assert "Do not reason further" in forced_instruction+ assert "Stop calling tools" in forced_instruction+ result = _result(events)+ assert result.metadata["response"] == "Recovered after the hard finish."+ assert result.metadata["completed"] is True+ assert result.metadata["settlement_rounds"] == 1+++async def test_reasoning_only_hard_finish_has_distinct_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Reasoning without an answer is not reported as an opaque model failure."""+ registry = _Registry()+ client = _ScriptedChatClient(+ [+ [_llm_chunk(content="<think>first empty</think>")],+ [_llm_chunk(content="<think>still empty</think>")],+ [_llm_chunk(content="<think>reasoned away the hard finish</think>")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ pipeline._max_rounds = 1+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="Answer"))++ assert client.call_count == 3result = _result(events)assert result.metadata["response"] == (- "I could not produce a useful response from the model output. "+ "The model produced internal reasoning but no usable answer. ""Please try again or narrow the request.")assert result.metadata["completed"] is True