From dcdf9cae902ba44b76154dc710877fd2b75113dd Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Thu, 1 Oct 2026 05:41:23 +0800 Subject: [PATCH 1/4] fix(agent): skip a whitespace-only tool preamble in the tool loop runner When a model returns a response that is only whitespace plus tool calls, the runner yielded it as an intermediate llm_result, and the respond stage then logged "Prepare to send" followed by "The message is empty; skipping" for a message that was never worth sending. Treat the preamble as empty in that case so nothing reaches the respond stage; a real preamble and a whitespace final reply are both untouched. Refs #10236 --- .../agent/runners/tool_loop_agent_runner.py | 7 +- tests/test_tool_loop_agent_runner.py | 82 +++++++++++++++++++ 2 files changed, 88 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..3028a4bdbec 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -938,7 +938,12 @@ async def step(self): type="llm_result", data=AgentResponseData(chain=llm_resp.result_chain), ) - elif llm_resp.completion_text: + elif llm_resp.completion_text and ( + not llm_resp.tools_call_name or llm_resp.completion_text.strip() + ): + # A whitespace-only preamble carries no information. When tool + # calls follow, skip it so no empty message reaches the respond + # stage; without tool calls keep the model's reply untouched. yield AgentResponse( type="llm_result", data=AgentResponseData( diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index ef8e818bb5c..e1992729964 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -324,6 +324,33 @@ async def text_chat(self, **kwargs) -> LLMResponse: ) +class PreambleToolProvider(MockProvider): + """First call returns a tool call carrying the given preamble text as + completion_text; the second call returns the final answer.""" + + def __init__(self, tool_name: str, preamble: str): + super().__init__() + self.tool_name = tool_name + self.preamble = preamble + + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + if self.call_count > 1: + return LLMResponse( + role="assistant", + completion_text="最终回复", + usage=TokenUsage(input_other=10, output=5), + ) + return LLMResponse( + role="assistant", + completion_text=self.preamble, + tools_call_name=[self.tool_name], + tools_call_args=[{"query": "test"}], + tools_call_ids=["call_preamble"], + usage=TokenUsage(input_other=10, output=5), + ) + + class CapturingToolLoopProvider(MockProvider): def __init__(self, tool_name: str): super().__init__() @@ -2398,3 +2425,58 @@ async def test_small_step_budgets_and_reset( ) assert runner._step_budget_used == 0 assert runner._step_budget_notified == set() + + +@pytest.mark.asyncio +async def test_whitespace_preamble_with_tool_call_is_not_yielded( + provider_request, mock_tool_executor, mock_hooks +): + """A whitespace-only completion_text followed by tool calls must not + produce an intermediate llm_result; the respond stage would only log it + as an empty message (see #10236).""" + provider = PreambleToolProvider("test_tool", preamble=" ") + runner = ToolLoopAgentRunner() + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + responses = [resp async for resp in runner.step_until_done(5)] + + texts = [ + resp.data["chain"].get_plain_text() + for resp in responses + if resp.type == "llm_result" + ] + assert texts == ["最终回复"] + + +@pytest.mark.asyncio +async def test_non_empty_preamble_with_tool_call_is_still_yielded( + provider_request, mock_tool_executor, mock_hooks +): + """A real preamble before tool calls keeps flowing; tool progress UX + depends on it.""" + provider = PreambleToolProvider("test_tool", preamble="先查一下天气。") + runner = ToolLoopAgentRunner() + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + responses = [resp async for resp in runner.step_until_done(5)] + + texts = [ + resp.data["chain"].get_plain_text() + for resp in responses + if resp.type == "llm_result" + ] + assert texts == ["先查一下天气。", "最终回复"] From d315d1766df258cf4ad1718a81f3104e0faa752c Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Fri, 2 Oct 2026 01:16:48 +0800 Subject: [PATCH 2/4] fix(agent): skip a blank result_chain preamble when tool calls follow Providers that wrap the reply text in result_chain (e.g. OpenAI's non-streaming path builds MessageChain from completion_text) bypassed the completion_text guard, so the whitespace-only preamble still reached the respond stage on those adapters. A chain of only blank Plain components now gets the same skip; chains carrying any non-Plain component are untouched. --- .../agent/runners/tool_loop_agent_runner.py | 17 +++- tests/test_tool_loop_agent_runner.py | 87 +++++++++++++++++++ 2 files changed, 100 insertions(+), 4 deletions(-) diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index 3028a4bdbec..6a2fc1c18fa 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, ) @@ -934,10 +934,19 @@ async def step(self): ), ) if llm_resp.result_chain: - yield AgentResponse( - type="llm_result", - data=AgentResponseData(chain=llm_resp.result_chain), + # Providers that wrap the reply in result_chain (e.g. OpenAI's + # non-streaming path) need the same whitespace-only preamble skip + # as the completion_text branch below; chains carrying media or + # any non-Plain component stay untouched. + blank_text_chain = ( + all(isinstance(comp, Plain) for comp in llm_resp.result_chain.chain) + and not llm_resp.result_chain.get_plain_text().strip() ) + if not (llm_resp.tools_call_name and blank_text_chain): + yield AgentResponse( + type="llm_result", + data=AgentResponseData(chain=llm_resp.result_chain), + ) elif llm_resp.completion_text and ( not llm_resp.tools_call_name or llm_resp.completion_text.strip() ): diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index e1992729964..cfd9e19ce71 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -2480,3 +2480,90 @@ async def test_non_empty_preamble_with_tool_call_is_still_yielded( if resp.type == "llm_result" ] assert texts == ["先查一下天气。", "最终回复"] + + +class PreambleChainToolProvider(MockProvider): + """First call returns a tool call with the preamble wrapped in + result_chain (the OpenAI non-streaming shape); the second call returns + the final answer as plain completion_text.""" + + def __init__(self, preamble_chain): + super().__init__() + self.preamble_chain = preamble_chain + + async def text_chat(self, **kwargs) -> LLMResponse: + self.call_count += 1 + if self.call_count > 1: + return LLMResponse( + role="assistant", + completion_text="最终回复", + usage=TokenUsage(input_other=10, output=5), + ) + return LLMResponse( + role="assistant", + completion_text="", + result_chain=MessageChain(chain=self.preamble_chain), + tools_call_name=["test_tool"], + tools_call_args=[{"query": "test"}], + tools_call_ids=["call_preamble_chain"], + usage=TokenUsage(input_other=10, output=5), + ) + + +@pytest.mark.asyncio +async def test_whitespace_preamble_chain_with_tool_call_is_not_yielded( + provider_request, mock_tool_executor, mock_hooks +): + """A result_chain holding only blank Plain components is the same + whitespace preamble and must be skipped when tool calls follow.""" + from astrbot.core.message.components import Plain as PlainComp + + provider = PreambleChainToolProvider([PlainComp(" \n ")]) + runner = ToolLoopAgentRunner() + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + responses = [resp async for resp in runner.step_until_done(5)] + + texts = [ + resp.data["chain"].get_plain_text() + for resp in responses + if resp.type == "llm_result" + ] + assert texts == ["最终回复"] + + +@pytest.mark.asyncio +async def test_media_preamble_chain_with_tool_call_is_still_yielded( + provider_request, mock_tool_executor, mock_hooks +): + """A result_chain carrying media next to blank text is real content and + must reach the respond stage even when tool calls follow.""" + from astrbot.core.message.components import At + from astrbot.core.message.components import Plain as PlainComp + + provider = PreambleChainToolProvider([PlainComp(" "), At(qq="123")]) + runner = ToolLoopAgentRunner() + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + responses = [resp async for resp in runner.step_until_done(5)] + + yielded = [resp for resp in responses if resp.type == "llm_result"] + assert any( + any(not isinstance(comp, PlainComp) for comp in resp.data["chain"].chain) + for resp in yielded + ) + assert yielded[-1].data["chain"].get_plain_text() == "最终回复" From 04c3fd20913437153cc0730d7937f4995f9e5d3c Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:55:16 +0800 Subject: [PATCH 3/4] test(agent): verify preambles through native runner events Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com> --- tests/test_tool_loop_agent_runner.py | 47 +++++++++++++++++----------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index b7c45b0eada..ee469ff3957 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 ExtensionOutput, 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,22 @@ async def collect_events(iterator): return [event async for event in iterator] +def completed_texts(events): + """Collect completed plain output from native runner events. + + Args: + events: Events emitted by the runner. + + Returns: + The completed messages' plain text in emission order. + """ + 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用于测试""" @@ -2443,11 +2461,7 @@ async def test_whitespace_preamble_with_tool_call_is_not_yielded( responses = [resp async for resp in runner.step_until_done(5)] - texts = [ - resp.data["chain"].get_plain_text() - for resp in responses - if resp.type == "llm_result" - ] + texts = completed_texts(responses) assert texts == ["最终回复"] @@ -2470,11 +2484,7 @@ async def test_non_empty_preamble_with_tool_call_is_still_yielded( responses = [resp async for resp in runner.step_until_done(5)] - texts = [ - resp.data["chain"].get_plain_text() - for resp in responses - if resp.type == "llm_result" - ] + texts = completed_texts(responses) assert texts == ["先查一下天气。", "最终回复"] @@ -2527,11 +2537,7 @@ async def test_whitespace_preamble_chain_with_tool_call_is_not_yielded( responses = [resp async for resp in runner.step_until_done(5)] - texts = [ - resp.data["chain"].get_plain_text() - for resp in responses - if resp.type == "llm_result" - ] + texts = completed_texts(responses) assert texts == ["最终回复"] @@ -2557,12 +2563,15 @@ async def test_media_preamble_chain_with_tool_call_is_still_yielded( responses = [resp async for resp in runner.step_until_done(5)] - yielded = [resp for resp in responses if resp.type == "llm_result"] + completed = [resp for resp in responses if isinstance(resp, MessageCompleted)] assert any( - any(not isinstance(comp, PlainComp) for comp in resp.data["chain"].chain) - for resp in yielded + isinstance(part, ExtensionOutput) + and part.namespace == "astrbot.platform" + and part.value.get("qq") == "123" + for event in completed + for part in event.content ) - assert yielded[-1].data["chain"].get_plain_text() == "最终回复" + assert completed_texts(completed)[-1] == "最终回复" @pytest.mark.asyncio From eec158e949840a8de85d840ffa4e4b8f6bb9197f Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:39:44 +0800 Subject: [PATCH 4/4] test: use a stable mention value across pydantic versions Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com> --- tests/test_tool_loop_agent_runner.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index ee469ff3957..e42e6237973 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -2550,7 +2550,7 @@ async def test_media_preamble_chain_with_tool_call_is_still_yielded( from astrbot.core.message.components import At from astrbot.core.message.components import Plain as PlainComp - provider = PreambleChainToolProvider([PlainComp(" "), At(qq="123")]) + provider = PreambleChainToolProvider([PlainComp(" "), At(qq=123)]) runner = ToolLoopAgentRunner() await runner.reset( provider=provider, @@ -2567,7 +2567,8 @@ async def test_media_preamble_chain_with_tool_call_is_still_yielded( assert any( isinstance(part, ExtensionOutput) and part.namespace == "astrbot.platform" - and part.value.get("qq") == "123" + and part.name == "At" + and part.value.get("qq") == 123 for event in completed for part in event.content )