Skip to content

fix(agent): skip a whitespace-only tool preamble in the tool loop runner - #10297

Open
he-yufeng wants to merge 7 commits into
AstrBotDevs:masterfrom
he-yufeng:fix/runner-whitespace-preamble
Open

he-yufeng wants to merge 7 commits into
AstrBotDevs:masterfrom
he-yufeng:fix/runner-whitespace-preamble

Conversation

@he-yufeng

@he-yufeng he-yufeng commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Refs #10236. Whitespace-only text before tool calls should not produce an empty intermediate message. Meaningful preambles, non-text content, and final replies remain intact.

Modifications / 改动点

  • Apply the whitespace check to both completion_text and text-only result_chain, preserving chains with non-text components.
  • Keep the four regressions on the runner's current public event API: MessageCompleted, PlainOutput, and ExtensionOutput. The media control verifies the platform namespace and retained qq value, not just the existence of an event.

The latest test-only update is eec158e94984. The production whitespace behavior is unchanged by these updates. The original four CI failures came from tests still filtering the retired llm_result event after the native-event migration. After that adaptation, all three Python 3.12 CI jobs exposed one additional assertion mismatch: numeric-string mentions are coerced to integers by the Pydantic v1 component model used on Python <3.14, whereas Python 3.14 uses Pydantic v2 and preserves the string. The media fixture now uses integer 123 explicitly and checks the exact At name and retained integer value on both paths.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

On the original PR head 5ead047ea012, all four preamble tests fail locally with the same empty-event assertions as hosted CI. With the event assertions updated:

pytest tests/test_tool_loop_agent_runner.py -q
78 passed

Ruff check, Ruff format check, and git diff --check pass for the touched file. Validation used Python 3.14 with the worktree's source and an existing same-project environment; no dependencies were installed.

The complete local tests/ run returned 5454 passed, 38 skipped, 11 failed. All 11 failures were rerun with the original PR test file restored and failed identically. They concern existing dashboard session revocation, dependency-version behavior, Python 3.14 file-URI handling, and filesystem fixtures; this update does not alter those paths. The fixed test file was restored byte-for-byte afterward. This is not a claim that the full local suite passed. Fresh hosted checks remain the cross-platform gate.

Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. (Bug fix tracked in [Bug] 微信ClawBot1的消息发送先于工具调用 #10236.)
  • 👀 My changes have been well-tested, and the verification results are provided above.
  • 📚 No WebUI navigation, page structure, or label changes, so no docs update is needed.
  • 🤓 No new dependencies.
  • 😮 My changes do not introduce malicious code.

Summary by Sourcery

Prevent whitespace-only tool-call preambles from producing empty intermediate messages while preserving meaningful and non-text content.

Bug Fixes:

  • Skip whitespace-only preambles when tool calls follow so they do not emit empty intermediate messages.
  • Preserve meaningful preambles, non-text result-chain content, and final responses during tool-loop execution.

Tests:

  • Add regression coverage for whitespace and meaningful preambles in both direct text and result-chain responses, including preservation of media content.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="941-943" />
<code_context>
                 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
</code_context>
<issue_to_address>
**issue (broader_impact):** The whitespace-only preamble is still yielded when the provider stores the response in `result_chain`, because the preceding `if llm_resp.result_chain` branch bypasses this new `completion_text` condition. Providers such as OpenAI populate `result_chain` for text responses, so the regression remains on those adapters and the new tests do not cover their representation.

**Triggers:** When a tool-calling response contains whitespace-only text in a non-empty `result_chain`.

**Suggested fix:** Apply the whitespace check to the `result_chain` path as well, while retaining chains that contain meaningful non-text content.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: astrbot/core/agent/runners/tool_loop_agent_runner.py:943


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Confirmed and fixed in 613a098. The non-streaming OpenAI path wraps the reply into MessageChain().message(completion_text), so the preamble arrived in result_chain and skipped past the completion_text guard. The result_chain branch now applies the same skip when the chain is only blank Plain components and tool calls follow; any chain carrying media or other components is yielded untouched.

Two regression tests added: a blank-text-only chain with tool calls produces no intermediate llm_result, and a chain with an At component plus blank text still flows.

pytest tests/test_tool_loop_agent_runner.py -q: 64 passed. ruff check / format clean.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

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 AstrBotDevs#10236
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.
@he-yufeng
he-yufeng force-pushed the fix/runner-whitespace-preamble branch from 613a098 to d315d17 Compare October 2, 2026 16:14
The only conflict was in tests/test_tool_loop_agent_runner.py and both sides
were purely additive where the base was empty: this branch's whitespace-preamble
rows and master's test_context_token_limit_is_isolated_per_run. Kept both, and
restored the @pytest.mark.asyncio decorator that the conflict split had taken
off master's test.

Master's copy of that test is not ruff format clean and CI runs
`ruff format --check .` over the tree, so the block is formatted here. Nothing
else in the file moved.

Verification on this merge: tests/test_tool_loop_agent_runner.py 65/65, ruff
check, ruff format and pyupgrade clean on the file. Full tests/ is 5308 passed,
14 skipped, with the same 2 failures in
test_fastapi_v1_dashboard.py::test_config_update_revokes_only_affected_shell_sessions
that fail identically on pristine origin/master (a6c2b31).
@he-yufeng

Copy link
Copy Markdown
Contributor Author

Merged master at d74d6e122, which clears the conflict.

Same shape as #10303: the only conflict was in tests/test_tool_loop_agent_runner.py, both sides purely additive where the base was empty, so I kept this branch's whitespace-preamble rows and master's test_context_token_limit_is_isolated_per_run. The conflict split had taken the @pytest.mark.asyncio decorator off master's test; it is restored.

Master's copy of that test is not ruff format clean and CI runs ruff format --check . over the tree, so keeping it verbatim would have gone red here. The block is formatted and nothing else in the file moved.

Verification on this merge, tests/ run with the repo venv against this worktree's source:

  • tests/test_tool_loop_agent_runner.py 65/65
  • ruff check, ruff format --check and pyupgrade --py310-plus clean on the file
  • full tests/ is 5308 passed, 14 skipped, 2 failed. The two are test_fastapi_v1_dashboard.py::test_config_update_revokes_only_affected_shell_sessions[member_execution] and [admin_removal], and I confirmed on a detached worktree at pristine origin/master (a6c2b31db) that they fail there identically, so they are pre-existing and outside this change.

Pushing re-requested review, so the earlier approval needs re-stamping.

@Soulter Soulter moved this to In Progress in AstrBot Roadmap Nov 2, 2026
…0261110

# Conflicts:
#	astrbot/core/agent/runners/tool_loop_agent_runner.py
#	tests/test_tool_loop_agent_runner.py
Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Merged current master (6ff0b083) into e5c81d4812.

The main branch now assembles typed output components rather than yielding the old native fragments. The whitespace guard is preserved in that flow for both result_chain and completion_text: skip an all-text blank preamble when tool calls follow, preserve media and non-Plain components, and leave final replies unchanged.

Ruff check, production Ruff format, py_compile, and the PR-relative diff check pass locally. All 23 hosted checks, including the Ubuntu, macOS, and Windows pytest jobs, are now SUCCESS.

@he-yufeng

Copy link
Copy Markdown
Contributor Author

@Soulter @RC-CHN Could you review e5c81d48?

A whitespace-only tool preamble should not be emitted as visible assistant content before the tool call. The patch skips that empty preamble while preserving meaningful text and the tool call itself.

Could you check both foreground and background tool execution so the runner does not produce an empty user-visible turn or suppress a real explanation?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

2 participants