Skip to content

fix(agent): ask once for the final answer when a run would end empty - #10303

Open
he-yufeng wants to merge 5 commits into
AstrBotDevs:masterfrom
he-yufeng:fix/empty-final-response-repair
Open

he-yufeng wants to merge 5 commits into
AstrBotDevs:masterfrom
he-yufeng:fix/empty-final-response-repair

Conversation

@he-yufeng

@he-yufeng he-yufeng commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What

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 reports it on every transfer_to_* delegation with kimi-k3.

Two layers let the shape through today:

  • the OpenAI-compatible parser only raises EmptyModelOutputError when a response has no text, no reasoning, and no tool calls, so a reasoning-only final is parsed as a valid response with empty completion_text;
  • the plain tool-loop path then finalizes it silently (_complete_with_assistant_response + no llm_result yielded), while the skills_like re-query path already has a repair retry for exactly this "no tool calls and no usable reply" shape.

Fix

Before finalizing an empty, tool-less response, ask for the answer once: append an EMPTY_FINAL_REPAIR_PROMPT user message and run one more step. Guards that keep intentional silences intact:

  • at most one repair per run; if the retry also comes back empty, the run finishes exactly as before;
  • no repair when the model already delivered through send_message_to_user this run (its empty final is deliberate);
  • a final carrying media but no text still counts as a real answer.

Tests

Four new cases in tests/test_tool_loop_agent_runner.py: empty final after tool work is repaired once and the repaired answer reaches llm_result; a second empty answer finishes quietly with exactly one repair attempt; empty final after send_message_to_user is left silent; media-only final is left alone. Red-green checked: the repair tests fail without the runner change.

Local run: pytest tests/, 3635 passed, 2 failed in test_config_update_revokes_only_affected_shell_sessions, which fail identically on clean master (pre-existing, unrelated). ruff format and ruff check clean.

Refs #10298

Summary by Sourcery

Prevent tool-loop runs from ending silently by requesting one final answer when no user-visible response was delivered.

Bug Fixes:

  • Repair empty, tool-less final responses once so users receive an answer instead of silence.
  • Preserve intentional silence after successful delivery through send_message_to_user and treat media-only responses as valid answers.

Enhancements:

  • Apply the one-shot empty-final repair consistently to regular and forced-final tool-loop paths, including session-aware delivery checks.

Tests:

  • Add coverage for repaired empty finals, single-attempt termination, message-tool delivery, media-only responses, forced final steps, cross-session sends, and skills-like media re-queries.

@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 3 issues

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="951-954" />
<code_context>
+                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)

</code_context>
<issue_to_address>
**issue (bug_risk):** When the first empty final occurs during the forced final step after `step_until_done` exhausts its budget, this branch appends the repair prompt and returns, but `step_until_done` performs no subsequent step, leaving the runner in `RUNNING` rather than `DONE` and yielding no final answer.

**Triggers:** When the run reaches `max_step` immediately before producing an empty final.

**Suggested fix:** Let the forced-final path execute the one allowed empty-final repair step and, if needed, its retry, or finalize the run after the forced step when the repair cannot be scheduled.
</issue_to_address>

### Comment 2
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="938-941" />
<code_context>
+            # 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
</code_context>
<issue_to_address>
**issue (broader_impact):** The new media/empty-final guard does not cover the `skills_like` re-query path, whose `_has_meaningful_assistant_reply` check considers only text; a media-only re-query response is therefore treated as unusable and triggers an unnecessary repair request instead of being accepted as the final answer.

**Triggers:** When `tool_schema_mode` is `skills_like` and the re-query returns a final containing media but no text.

**Suggested fix:** Make `_has_meaningful_assistant_reply` recognize non-empty media result chains, or route the re-query result through the same media-aware final-response predicate.
</issue_to_address>

### Comment 3
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="1456-1460" />
<code_context>
+            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
</code_context>
<issue_to_address>
**issue (bug_risk):** A successful `send_message_to_user` call targeting another session sets `_delivered_via_message_tool` and suppresses the repair for the current run, even though the current user received no message and still sees silence.

**Triggers:** When `send_message_to_user` is invoked with a `session` argument for a different session.

**Suggested fix:** Set the guard only when the tool successfully sends to the current run's session, using the tool arguments and the current session identity.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: astrbot/core/agent/runners/tool_loop_agent_runner.py:954, astrbot/core/agent/runners/tool_loop_agent_runner.py:941, astrbot/core/agent/runners/tool_loop_agent_runner.py:1460


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

@he-yufeng

Copy link
Copy Markdown
Contributor Author

All three findings checked out against the code; fixed in d318356.

  1. Forced-final dead end: real. When the empty final landed on the forced step after max_step, the repair prompt was queued but no step consumed it, so the run stayed RUNNING and yielded nothing. step_until_done now drives that one repair step when the forced step armed it.
  2. skills_like re-query: real. _has_meaningful_assistant_reply now accepts a media-only reply, same predicate as the main final path.
  3. Cross-session send_message_to_user: real. A successful send aimed at another session no longer counts as delivering this run's reply; only a send to the current session does, and an unverifiable target plays it safe and still repairs.

Regression tests added for each: forced-final repair completes the run (5 calls, one repair prompt, final answer delivered), cross-session send still repairs, media-only re-query stops at the second call.

pytest tests/test_tool_loop_agent_runner.py -q: 67 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 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 (AstrBotDevs#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 AstrBotDevs#10298
…-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.
@he-yufeng
he-yufeng force-pushed the fix/empty-final-response-repair branch from d318356 to 92fbbb6 Compare October 2, 2026 16:15
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 empty-final repair
tests and master's test_context_token_limit_is_isolated_per_run. Kept both.

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

Verification on this merge: tests/test_tool_loop_agent_runner.py 68/68, ruff
check and ruff format clean. Full tests/ is 5311 passed, 14 skipped, with 2
failures in test_fastapi_v1_dashboard.py::test_config_update_revokes_only_affected_shell_sessions.
Those two fail identically on pristine origin/master (a6c2b31) in a detached
baseline worktree, so they are pre-existing and outside this change.
@he-yufeng

Copy link
Copy Markdown
Contributor Author

Merged master at f15367997, which clears the conflict.

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 empty-final repair tests and master's test_context_token_limit_is_isolated_per_run. I kept both.

One thing worth flagging: master's copy of that test was not ruff format clean, and CI runs ruff format --check . over the whole tree, so keeping it verbatim would have turned the format check red on this branch. The block is formatted here and nothing else in the file moved. Worth a look upstream, since master's own format check should be catching that.

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

  • tests/test_tool_loop_agent_runner.py 68/68, including the merged test_context_token_limit_is_isolated_per_run and this branch's repair rows
  • ruff check, ruff format --check and pyupgrade --py310-plus all clean on the file
  • full tests/ is 5311 passed, 14 skipped, 2 failed. The two failures are test_fastapi_v1_dashboard.py::test_config_update_revokes_only_affected_shell_sessions[member_execution] and [admin_removal], asserting a shell session's process is still alive after a config update. I ran them on a detached worktree at pristine origin/master (a6c2b31db) and they fail there identically, so they are pre-existing and outside this change.

Pushing re-requested review, so the earlier approval needs to be re-stamped.

…0261110

# Conflicts:
#	astrbot/core/agent/runners/tool_loop_agent_runner.py
@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

❌ Patch coverage is 96.42857% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...trbot/core/agent/runners/tool_loop_agent_runner.py 96.42% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@he-yufeng

Copy link
Copy Markdown
Contributor Author

Merged current master (6ff0b083) into 59e7b18ecd.

The import conflict now keeps both Plain and ConversationPersistenceError, and drops imports that are unused on the merged tree. The PR-relative diff still contains only tool_loop_agent_runner.py and its tests.

Local Ruff check, production Ruff format, py_compile, and the PR-relative diff check all pass. 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 59e7b18e?

A run that would otherwise end with no user-visible answer should ask once for a final response, not repeatedly re-enter the tool loop or fabricate a completion.

Could you check the single-request boundary and what happens if that follow-up also returns no answer? The intended behavior is one bounded recovery attempt while preserving the original run state.

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