diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index 4d158b37d6..dc410ada7e 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -37,6 +37,7 @@ from astrbot.core.agent.tool_image_cache import tool_image_cache from astrbot.core.agent_output_content import content_from_chain from astrbot.core.exceptions import ConversationPersistenceError, EmptyModelOutputError +from astrbot.core.message.components import Plain from astrbot.core.provider.entities import ( LLMResponse, ProviderRequest, @@ -138,6 +139,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 " @@ -371,6 +378,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: @@ -1295,6 +1306,27 @@ async def _step(self) -> T.AsyncGenerator[RunnerEventPayload | AgentResponse, No 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) content = [] @@ -1524,9 +1556,17 @@ async def _step_until_done( [Message(role="user", content=self.MAX_STEPS_REACHED_PROMPT)] ) # 再执行最后一步 + repair_armed = not self._empty_final_repaired async with aclosing(self.step()) as responses: async for resp in responses: 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 with aclosing(self.step()) as responses: + async for resp in responses: + yield resp async def _handle_function_tools( self, @@ -1800,6 +1840,34 @@ 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. + # 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:") + ): + 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 logger.info(f"Tool `{func_tool_name}` Result: {tool_result_content}") # 处理函数调用响应 @@ -1830,8 +1898,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 7eb879512e..1f8fad51d0 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -12,9 +12,11 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from astrbot.core.agent.agent import Agent +from astrbot.core.agent.events import MessageCompleted from astrbot.core.agent.handoff import HandoffTool from astrbot.core.agent.hooks import BaseAgentRunHooks from astrbot.core.agent.message import ImageURLPart, Message, TextPart +from astrbot.core.agent.output import PlainOutput from astrbot.core.agent.run_context import ContextWrapper from astrbot.core.agent.runners.tool_loop_agent_runner import ToolLoopAgentRunner from astrbot.core.agent.tool import FunctionTool, ToolSet @@ -39,6 +41,14 @@ async def collect_events(iterator): return [event async for event in iterator] +def completed_texts(events): + return [ + "".join(part.text for part in event.content if isinstance(part, PlainOutput)) + for event in events + if isinstance(event, MessageCompleted) + ] + + class MockProvider(Provider): """模拟Provider用于测试""" @@ -2473,6 +2483,397 @@ async def test_small_step_budgets_and_reset( 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 = completed_texts(responses) + 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 + + +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 = completed_texts(responses) + 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 + + @pytest.mark.asyncio @pytest.mark.parametrize("exit_kind", ["provider_error", "exception", "stop"]) async def test_lifecycle_terminal_paths_notify_once(