Skip to content
18 changes: 16 additions & 2 deletions astrbot/core/agent/runners/tool_loop_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1301,8 +1302,21 @@ async def _step(self) -> T.AsyncGenerator[RunnerEventPayload | AgentResponse, No
if llm_resp.reasoning_content:
content.append(ReasoningOutput(text=llm_resp.reasoning_content))
if llm_resp.result_chain:
content.extend(content_from_chain(llm_resp.result_chain))
elif llm_resp.completion_text:
# Providers that wrap the reply in result_chain need the same
# whitespace-only preamble skip as completion_text. 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):
content.extend(content_from_chain(llm_resp.result_chain))
elif llm_resp.completion_text and (
not llm_resp.tools_call_name or llm_resp.completion_text.strip()
):
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
# 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.
content.append(PlainOutput(text=llm_resp.completion_text))
if content:
self._message_content = tuple(content)
Expand Down
179 changes: 179 additions & 0 deletions tests/test_tool_loop_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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用于测试"""

Expand Down Expand Up @@ -338,6 +356,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__()
Expand Down Expand Up @@ -2473,6 +2518,140 @@ async def test_small_step_budgets_and_reset(
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 = completed_texts(responses)
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 = completed_texts(responses)
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 = completed_texts(responses)
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)]

completed = [resp for resp in responses if isinstance(resp, MessageCompleted)]
assert any(
isinstance(part, ExtensionOutput)
and part.namespace == "astrbot.platform"
and part.name == "At"
and part.value.get("qq") == 123
for event in completed
for part in event.content
)
assert completed_texts(completed)[-1] == "最终回复"


@pytest.mark.asyncio
@pytest.mark.parametrize("exit_kind", ["provider_error", "exception", "stop"])
async def test_lifecycle_terminal_paths_notify_once(
Expand Down
Loading