From aeb0e852a10bfc7cdbfd1fe40049a647a5da27fd Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:45:14 +0800 Subject: [PATCH 1/2] fix(agent): ask once for the final answer when a run would end empty When a run ends with no tool calls and no user-visible content (an empty completion, or reasoning with no answer text), the runner marked the run DONE and yielded nothing, so the respond stage skipped delivery and the user saw silence. Tool-dense runs hit this whenever the model answers empty right after the last tool result (#10298). The provider layer only raises EmptyModelOutputError when a response has no text, no reasoning, and no tool calls, so a reasoning-only final slips through; and the plain tool-loop path had no guard for the shape (the skills_like re-query path already repairs exactly this). Append an EMPTY_FINAL_REPAIR_PROMPT user message and run one more step before completing. Guards: at most one repair per run; no repair when the model already delivered through send_message_to_user this run; a final carrying media but no text still counts as a real answer. Refs #10298 --- .../agent/runners/tool_loop_agent_runner.py | 40 +++- tests/test_tool_loop_agent_runner.py | 184 ++++++++++++++++++ 2 files changed, 223 insertions(+), 1 deletion(-) diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index ed5bb3df628..21c29087563 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -29,7 +29,7 @@ from astrbot.core.agent.tool import FunctionTool, ToolSet from astrbot.core.agent.tool_image_cache import tool_image_cache from astrbot.core.exceptions import EmptyModelOutputError -from astrbot.core.message.components import Json +from astrbot.core.message.components import Json, Plain from astrbot.core.message.message_event_result import ( MessageChain, ) @@ -129,6 +129,12 @@ class ToolLoopAgentRunner(BaseAgentRunner[TContext]): "step budget. Optionally, they can raise the tool-call round limit in " "AstrBot WebUI to allow longer runs." ) + EMPTY_FINAL_REPAIR_PROMPT = ( + "[SYSTEM NOTICE: Empty final response] " + "Your previous reply had no user-visible content, and nothing reached the " + "user this turn. Give the final answer now, based on the tool results and " + "context above. Do not call tools unless one is strictly necessary." + ) SKILLS_LIKE_REQUERY_INSTRUCTION_TEMPLATE = ( "You have decided to call tool(s): {tool_names}. Now call the tool(s) " "with required arguments using the tool schema, and follow the existing " @@ -289,6 +295,10 @@ async def reset( self._step_budget_max: int | None = None self._step_budget_used = 0 self._step_budget_notified: set[int] = set() + # Per-run guards for the empty-final repair: repair at most once, and + # never when the model already delivered via send_message_to_user. + self._empty_final_repaired = False + self._delivered_via_message_tool = False # These two are used for tool schema mode handling # We now have two modes: @@ -921,6 +931,27 @@ async def step(self): return if not llm_resp.tools_call_name: + # An empty final answer is only expected when the model already + # delivered its reply through send_message_to_user in this run. + # Otherwise (empty completion, or reasoning with no answer text) the + # user would see silence, so ask for the answer once before finishing. + has_media = bool(llm_resp.result_chain) and any( + not isinstance(comp, Plain) for comp in llm_resp.result_chain.chain + ) + if ( + not (llm_resp.completion_text or "").strip() + and not has_media + and not self._empty_final_repaired + and not self._delivered_via_message_tool + ): + self._empty_final_repaired = True + logger.warning( + "LLM finished with an empty final response; asking for the answer once more." + ) + self.run_context.messages.append( + Message(role="user", content=self.EMPTY_FINAL_REPAIR_PROMPT) + ) + return await self._complete_with_assistant_response(llm_resp) # 返回 LLM 结果 @@ -1420,6 +1451,13 @@ def _append_tool_call_result(tool_call_id: str, content: str) -> None: if len(tool_call_result_blocks) > tool_result_blocks_start: tool_result_content = str(tool_call_result_blocks[-1].content) + # A successful send_message_to_user means the reply already + # reached the user this run; a later empty final is intentional. + if ( + func_tool_name == "send_message_to_user" + and not tool_result_content.startswith("error:") + ): + self._delivered_via_message_tool = True yield _HandleFunctionToolsResult.from_message_chain( MessageChain( type="tool_call_result", diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index ef8e818bb5c..9b1206c8e5e 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -2398,3 +2398,187 @@ async def test_small_step_budgets_and_reset( ) assert runner._step_budget_used == 0 assert runner._step_budget_notified == set() + + +class EmptyFinalProvider(MockProvider): + """First call runs a tool; the next ``empty_streak`` calls return an empty + final response (no text, no tool calls); later calls answer normally.""" + + def __init__(self, empty_streak: int = 1, first_tool: str = "test_tool"): + super().__init__() + self.empty_streak = empty_streak + self.first_tool = first_tool + self.received_contexts = [] + + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + self.received_contexts.append(list(kwargs.get("contexts") or [])) + if self.call_count == 1: + return LLMResponse( + role="assistant", + completion_text="", + tools_call_name=[self.first_tool], + tools_call_args=[{"query": "test"}], + tools_call_ids=["call_empty_final"], + usage=TokenUsage(input_other=10, output=5), + ) + if self.call_count <= 1 + self.empty_streak: + return LLMResponse( + role="assistant", + completion_text="", + usage=TokenUsage(input_other=10, output=5), + ) + return LLMResponse( + role="assistant", + completion_text="补救后的最终回答", + usage=TokenUsage(input_other=10, output=5), + ) + + +@pytest.mark.asyncio +async def test_empty_final_response_is_repaired_once( + runner, provider_request, mock_tool_executor, mock_hooks +): + """An empty final with no tool calls must be repaired once, not silenced.""" + provider = EmptyFinalProvider(empty_streak=1) + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + async def passthrough(messages, trusted_token_usage=0): + return list(messages) + + runner.request_context_manager.process = passthrough + + responses = [resp async for resp in runner.step_until_done(10)] + + assert runner.done() + assert provider.call_count == 3 + repair_contexts = provider.received_contexts[2] + assert repair_contexts[-1].role == "user" + assert repair_contexts[-1].content == runner.EMPTY_FINAL_REPAIR_PROMPT + final_texts = [ + resp.data["chain"].get_plain_text() + for resp in responses + if resp.type == "llm_result" + ] + assert any("补救后的最终回答" in text for text in final_texts) + + +@pytest.mark.asyncio +async def test_empty_final_response_repair_is_not_repeated( + runner, provider_request, mock_tool_executor, mock_hooks +): + """If the repair also returns empty, finish quietly instead of looping.""" + provider = EmptyFinalProvider(empty_streak=100) + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + async def passthrough(messages, trusted_token_usage=0): + return list(messages) + + runner.request_context_manager.process = passthrough + + async for _ in runner.step_until_done(10): + pass + + assert runner.done() + assert provider.call_count == 3 + repairs = sum( + 1 + for ctx in provider.received_contexts + if ctx + and ctx[-1].role == "user" + and ctx[-1].content == runner.EMPTY_FINAL_REPAIR_PROMPT + ) + assert repairs == 1 + + +@pytest.mark.asyncio +async def test_empty_final_after_send_message_to_user_is_not_repaired( + runner, mock_tool_executor, mock_hooks +): + """A deliberate empty final after send_message_to_user stays silent.""" + send_tool = FunctionTool( + name="send_message_to_user", + description="发送消息给用户", + parameters={"type": "object", "properties": {"text": {"type": "string"}}}, + handler=AsyncMock(), + ) + request = ProviderRequest( + prompt="把结果发给用户", + func_tool=ToolSet(tools=[send_tool]), + contexts=[], + ) + provider = EmptyFinalProvider(empty_streak=100, first_tool="send_message_to_user") + await runner.reset( + provider=provider, + request=request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + async def passthrough(messages, trusted_token_usage=0): + return list(messages) + + runner.request_context_manager.process = passthrough + + async for _ in runner.step_until_done(10): + pass + + assert runner.done() + assert provider.call_count == 2 + assert all( + not ( + ctx + and ctx[-1].role == "user" + and ctx[-1].content == runner.EMPTY_FINAL_REPAIR_PROMPT + ) + for ctx in provider.received_contexts + ) + + +@pytest.mark.asyncio +async def test_media_only_final_response_is_not_repaired( + runner, provider_request, mock_tool_executor, mock_hooks +): + """A final message carrying media but no text is a real answer.""" + from astrbot.core.message.components import At + + class MediaFinalProvider(MockProvider): + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + return LLMResponse( + role="assistant", + result_chain=MessageChain(chain=[At(qq="123")]), + usage=TokenUsage(input_other=10, output=5), + ) + + provider = MediaFinalProvider() + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + async for _ in runner.step_until_done(5): + pass + + assert runner.done() + assert provider.call_count == 1 From 92fbbb6fea10e28cea1907d39cd13afe51c45bc7 Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Fri, 2 Oct 2026 01:13:40 +0800 Subject: [PATCH 2/2] fix(agent): complete the forced-final repair step and only count same-session sends Three follow-ups from review: - An empty final on the forced last step (after max_step) scheduled the one-shot repair and returned, but no further step was driven, leaving the run in RUNNING with no answer. step_until_done now drives that single repair step. - A successful send_message_to_user aimed at another session no longer suppresses the empty-final repair for the current run; only sends to the run's own session count as delivered, and an unverifiable target counts as elsewhere so the repair still fires. - The skills_like re-query check now treats a media-only reply as a real answer, matching the main final path, instead of firing the stronger-instruction retry. --- .../agent/runners/tool_loop_agent_runner.py | 43 +++- tests/test_tool_loop_agent_runner.py | 215 ++++++++++++++++++ 2 files changed, 252 insertions(+), 6 deletions(-) diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index 21c29087563..5f45aa21529 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -1202,8 +1202,15 @@ async def step_until_done( ) ) # 再执行最后一步 + repair_armed = not self._empty_final_repaired async for resp in self.step(): yield resp + # The forced step does not finish on an empty final; it schedules + # the one-shot repair instead. Drive that single repair step so + # the run actually completes instead of staying RUNNING forever. + if not self.done() and repair_armed and self._empty_final_repaired: + async for resp in self.step(): + yield resp async def _handle_function_tools( self, @@ -1453,11 +1460,32 @@ def _append_tool_call_result(tool_call_id: str, content: str) -> None: tool_result_content = str(tool_call_result_blocks[-1].content) # A successful send_message_to_user means the reply already # reached the user this run; a later empty final is intentional. - if ( - func_tool_name == "send_message_to_user" - and not tool_result_content.startswith("error:") + # It only counts when aimed at this run's own session: a + # proactive send to another session leaves the current user + # waiting. Unverifiable target counts as elsewhere, so the + # empty-final repair still fires rather than risking silence. + if func_tool_name == "send_message_to_user" and not ( + tool_result_content.startswith("error:") ): - self._delivered_via_message_tool = True + target_session = (func_tool_args or {}).get("session") + if target_session: + event = getattr( + getattr(self.run_context, "context", None), "event", None + ) + current_session = getattr(event, "unified_msg_origin", None) + target_session = str(target_session) + if current_session and ( + target_session == str(current_session) + or ( + ":" not in target_session + and target_session + == str(current_session).rsplit(":", 1)[-1] + ) + ): + self._delivered_via_message_tool = True + else: + # No session argument: the tool targets the current one. + self._delivered_via_message_tool = True yield _HandleFunctionToolsResult.from_message_chain( MessageChain( type="tool_call_result", @@ -1502,8 +1530,11 @@ def _build_tool_requery_context( @staticmethod def _has_meaningful_assistant_reply(llm_resp: LLMResponse) -> bool: - text = (llm_resp.completion_text or "").strip() - return bool(text) + if (llm_resp.completion_text or "").strip(): + return True + # A media-only reply is a real answer too, same as in the final path. + chain = llm_resp.result_chain + return bool(chain) and any(not isinstance(comp, Plain) for comp in chain.chain) def _build_tool_subset(self, tool_set: ToolSet, tool_names: list[str]) -> ToolSet: """Build a subset of tools from the given tool set based on tool names.""" diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index 9b1206c8e5e..e887e2bcdbf 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -2582,3 +2582,218 @@ async def text_chat(self, **kwargs) -> LLMResponse: assert runner.done() assert provider.call_count == 1 + + +class ForcedEmptyFinalProvider(MockProvider): + """Calls a tool on every call while tools are attached; with tools + stripped (the forced final step) returns an empty final, and answers only + once the empty-final repair prompt shows up.""" + + def __init__(self): + super().__init__() + self.received_contexts = [] + + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + self.received_contexts.append(list(kwargs.get("contexts") or [])) + if kwargs.get("func_tool") is not None: + return LLMResponse( + role="assistant", + completion_text="", + tools_call_name=["test_tool"], + tools_call_args=[{"query": "test"}], + tools_call_ids=[f"call_forced_{self.call_count}"], + usage=TokenUsage(input_other=10, output=5), + ) + contexts = self.received_contexts[-1] + if ( + contexts + and contexts[-1].role == "user" + and contexts[-1].content == ToolLoopAgentRunner.EMPTY_FINAL_REPAIR_PROMPT + ): + return LLMResponse( + role="assistant", + completion_text="补救后的最终回答", + usage=TokenUsage(input_other=10, output=5), + ) + return LLMResponse( + role="assistant", + completion_text="", + usage=TokenUsage(input_other=10, output=5), + ) + + +@pytest.mark.asyncio +async def test_forced_final_empty_response_still_runs_repair( + runner, provider_request, mock_tool_executor, mock_hooks +): + """An empty final on the forced last step must still get its one repair + step; ending right after scheduling the repair would leave the run in + RUNNING and the user staring at silence.""" + provider = ForcedEmptyFinalProvider() + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + async def passthrough(messages, trusted_token_usage=0): + return list(messages) + + runner.request_context_manager.process = passthrough + + responses = [resp async for resp in runner.step_until_done(3)] + + assert runner.done() + # 3 budgeted tool steps + 1 forced final (empty) + 1 repair step. + assert provider.call_count == 5 + repairs = sum( + 1 + for ctx in provider.received_contexts + if ctx + and ctx[-1].role == "user" + and ctx[-1].content == runner.EMPTY_FINAL_REPAIR_PROMPT + ) + assert repairs == 1 + final_texts = [ + resp.data["chain"].get_plain_text() + for resp in responses + if resp.type == "llm_result" + ] + assert any("补救后的最终回答" in text for text in final_texts) + + +@pytest.mark.asyncio +async def test_empty_final_after_cross_session_send_is_repaired( + runner, mock_tool_executor, mock_hooks +): + """send_message_to_user aimed at another session must not silence this run.""" + send_tool = FunctionTool( + name="send_message_to_user", + description="发送消息给用户", + parameters={"type": "object", "properties": {"text": {"type": "string"}}}, + handler=AsyncMock(), + ) + request = ProviderRequest( + prompt="把结果发给另一个会话", + func_tool=ToolSet(tools=[send_tool]), + contexts=[], + ) + + class CrossSessionProvider(MockProvider): + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + if self.call_count == 1: + return LLMResponse( + role="assistant", + completion_text="", + tools_call_name=["send_message_to_user"], + tools_call_args=[ + { + "messages": [{"type": "plain", "text": "hi"}], + "session": "aiocqhttp:FriendMessage:someone_else", + } + ], + tools_call_ids=["call_cross_session"], + usage=TokenUsage(input_other=10, output=5), + ) + if self.call_count == 2: + return LLMResponse( + role="assistant", + completion_text="", + usage=TokenUsage(input_other=10, output=5), + ) + return LLMResponse( + role="assistant", + completion_text="当前会话的回答", + usage=TokenUsage(input_other=10, output=5), + ) + + provider = CrossSessionProvider() + event = MockEvent(umo="aiocqhttp:FriendMessage:u123", sender_id="u123") + await runner.reset( + provider=provider, + request=request, + run_context=ContextWrapper(context=MockAgentContext(event)), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + async def passthrough(messages, trusted_token_usage=0): + return list(messages) + + runner.request_context_manager.process = passthrough + + async for _ in runner.step_until_done(10): + pass + + # The cross-session send must not count as delivering this run's reply, + # so the empty final triggers the one-shot repair and the run answers. + assert runner.done() + assert provider.call_count == 3 + + +@pytest.mark.asyncio +async def test_skills_like_media_only_requery_is_meaningful(runner, mock_hooks): + """A skills_like re-query that comes back with media but no text is a real + reply, not a failure to follow the tool-use instruction.""" + from astrbot.core.message.components import At + + class MediaRequeryProvider(MockProvider): + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + if self.call_count == 1: + return LLMResponse( + role="assistant", + completion_text="选择工具", + tools_call_name=["test_tool"], + tools_call_args=[{"query": "test"}], + tools_call_ids=["call_1"], + usage=TokenUsage(input_other=10, output=5), + ) + # The re-query answers with media only. + return LLMResponse( + role="assistant", + result_chain=MessageChain(chain=[At(qq="123")]), + usage=TokenUsage(input_other=10, output=5), + ) + + provider = MediaRequeryProvider() + tool = FunctionTool( + name="test_tool", + description="测试", + parameters={"type": "object", "properties": {"query": {"type": "string"}}}, + handler=AsyncMock(), + ) + req = ProviderRequest( + prompt="发一张图", + func_tool=ToolSet(tools=[tool]), + contexts=[], + ) + event = MockEvent(umo="test_umo", sender_id="test_sender") + await runner.reset( + provider=provider, + request=req, + run_context=ContextWrapper(context=MockAgentContext(event)), + tool_executor=cast(Any, MockToolExecutor()), + agent_hooks=mock_hooks, + tool_schema_mode="skills_like", + streaming=False, + ) + + async def passthrough(messages, trusted_token_usage=0): + return list(messages) + + runner.request_context_manager.process = passthrough + + async for _ in runner.step_until_done(5): + pass + + assert runner.done() + # call 1 picks the tool, call 2 is the re-query; a third call would mean + # the media-only reply was misjudged and the stronger-instruction repair ran. + assert provider.call_count == 2