Skip to content

feat(chatui): show failed speech and knowledge base model calls - #11304

Open
liquidtoy001 wants to merge 3 commits into
AstrBotDevs:masterfrom
liquidtoy001:feat/chatui-auxiliary-model-errors
Open

liquidtoy001 wants to merge 3 commits into
AstrBotDevs:masterfrom
liquidtoy001:feat/chatui-auxiliary-model-errors

Conversation

@liquidtoy001

@liquidtoy001 liquidtoy001 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Based on master 841295f; it merges cleanly with current master (bd403b8). Independent of my other open PRs (#11283, #11303); it merges cleanly with each of them.

Motivation / 动机

Speech-to-text, text-to-speech and knowledge base retrieval each depend on a model of their own, and each falls back quietly when that model fails:

  • Speech-to-text: the voice message is dropped and the chat model answers without it. This also happens when speech-to-text is enabled but no provider is selected.
  • Text-to-speech: the reply is sent as text.
  • Knowledge base: if an embedding or rerank call fails, or a knowledge base is unavailable, the answer comes without the retrieved knowledge or with unranked results.

In every case the cause (a mistyped model name, a rejected key, an unreachable endpoint) only reaches the log. In ChatUI the reply simply looks a little wrong, and nothing points to the model that needs fixing.

With this PR, ChatUI shows one warning card for all of these failures. The card's details name the model and the provider's error, and its button opens the model configuration. The reply still goes on as before. Other platforms are unchanged.

Modifications / 改动点

  • astrbot/core/auxiliary_model_errors.py (new): notify_auxiliary_model_failure(event, model, detail).
    • On WebChat it sends a chatui_error chain with the code auxiliaryModelFailed; on other platforms it does nothing.
    • If the card cannot be sent, the failure is only logged.
    • Sending the card does not count as the reply: the pipeline still runs the chat model after a speech-to-text card.
  • astrbot/core/pipeline/preprocess_stage/stage.py: a failed transcription shows the card with the speech-to-text provider's ID and error. A missing provider is reported only when the message contains voice. A message gets one card, however many recordings fail.
  • astrbot/core/pipeline/result_decorate/stage.py: when text-to-speech fails, the reply is still sent as text, as before. The reply gets one card, however many segments failed. Text-to-speech only runs for replies that are not streamed, so in ChatUI this card appears only when streaming output is off.
  • astrbot/core/knowledge_base/retrieval/manager.py, kb_mgr.py: retrieve() takes an optional errors list.
    • It collects the embedding searches and rerank calls that were skipped, and any unavailable knowledge base.
    • Callers that do not pass the list behave as before; this includes the dashboard's knowledge base retrieval test.
  • astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py, tools/knowledge_base_tools.py: both retrieval paths show the collected failures: the injected context and the agentic astr_kb_search tool. An exception from retrieval is shown too, including the failures collected before it.
  • ChatErrorCard.vue: a new auxiliaryModel category in the warning style, with the existing "Configure models" button. The text is translated for all four locales.
  • changelogs/unreleased.md: bilingual entry.

No WebUI navigation, page structure or labels change.

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

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

A text-to-speech provider that cannot be reached. The reply is sent as text, and the card's details show the provider and the error:

Speech or knowledge base model failure card

Verification (Windows 11, Python 3.12):

  • tests/unit/test_auxiliary_model_errors.py (13 tests) covers:

    • the card appears on WebChat only;
    • a card, sent or not, does not stop the reply (the event is not marked as answered);
    • speech-to-text that fails (one card for two failed recordings), and a missing speech-to-text provider (reported only for voice messages);
    • text-to-speech that fails: the reply falls back to text, with one card for two failed segments;
    • retrieval collects embedding and rerank failures and still returns results;
    • both knowledge base paths, including an exception from retrieval.

    With the call sites reverted, 6 behavior tests fail; the rest check that nothing is shown when nothing failed.

  • Related suites, 272 passed: tests/test_preprocess_stage.py, tests/unit/test_astr_main_agent.py and the knowledge base tests.

  • Full backend suite, merged with current master (f85ddf1): 5849 passed, 97 skipped.

  • Dashboard:

    • node --test tests/*.test.mjs: 133 passed.
    • vue-tsc --noEmit: passed.
    • pnpm i18n:check: passed.
  • ruff check and ruff format --check pass on all changed files.


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above. / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). / 已核对相关文档(无界面入口变化)。
  • 🤓 I have ensured that no new dependencies are introduced. / 我确保没有引入新依赖库。
  • 😮 My changes do not introduce malicious code. / 我的更改没有引入恶意代码。

Models used: Claude Fable 5.2, Claude Opus 5.5 (Claude Code), GPT-6 Astra (Codex).

Summary by Sourcery

Surface auxiliary model failures in ChatUI while allowing conversations to continue with their existing fallback behavior.

New Features:

  • Show ChatUI warning cards when speech-to-text, text-to-speech, or knowledge-base model calls fail, including the affected model and provider error with a path to model configuration.

Bug Fixes:

  • Preserve existing fallback behavior so failed auxiliary model calls do not stop replies or discard otherwise usable knowledge-base results.

Enhancements:

  • Collect and surface skipped knowledge-base embedding, reranking, and unavailable-database failures across both retrieval paths.
  • Localize the new auxiliary-model warning category across all supported dashboard locales.

Tests:

  • Add coverage for ChatUI-only notifications, reply continuation, speech and text-to-speech fallbacks, and knowledge-base retrieval failures.

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

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

## Individual Comments

### Comment 1
<location path="astrbot/core/auxiliary_model_errors.py" line_range="41" />
<code_context>
+                    Json(
+                        {
+                            "code": AUXILIARY_MODEL_ERROR_CODE,
+                            "message": f"{model}: {detail}",
+                        }
+                    )
</code_context>
<issue_to_address>
**Provider errors expose internal details**

When a provider or knowledge-base initialization exception includes a credential or other sensitive internal detail, `notify_auxiliary_model_failure` places the unfiltered exception or initialization-error text in the ChatUI card, so a WebChat user who triggers the failure sees any credentials, internal URLs, or filesystem details included in that text.

Redact credentials and sensitive endpoint or filesystem details before displaying provider errors to ChatUI users.

Also at `astrbot/core/knowledge_base/kb_mgr.py:319`.
</issue_to_address>

### Comment 2
<location path="astrbot/core/pipeline/preprocess_stage/stage.py" line_range="273" />
<code_context>
             logger.error("Error occurred while retrieving knowledge base: %s", exc)
+            errors.append(str(exc))
+        if errors:
+            await notify_auxiliary_model_failure(
+                event, "Knowledge base", "; ".join(errors)
+            )
</code_context>
<issue_to_address>
**Exhausted retries drop voice silently**

When the STT provider keeps raising `FileNotFoundError` through all five attempts, `_stt_record` returns `None` after the retries without calling the notifier, so the voice recording is dropped without a ChatUI failure card.

Notify ChatUI when the final `FileNotFoundError` retry fails.
</issue_to_address>

### Comment 3
<location path="astrbot/core/pipeline/preprocess_stage/stage.py" line_range="236" />
<code_context>
                     f"Session {event.unified_msg_origin} has no speech-to-text "
                     "provider configured.",
                 )
+                if any(isinstance(comp, Record) for comp in event.get_messages()):
+                    await notify_auxiliary_model_failure(
+                        event,
</code_context>
<issue_to_address>
**Quoted voice is skipped without warning**

When speech-to-text is enabled, no provider is selected, and a voice `Record` appears only inside a `Reply` chain, the missing-provider check scans only top-level components and returns before the reply-chain loop, so the referenced voice is dropped without a ChatUI warning.

Include records nested in `Reply` chains in the missing-provider check.
</issue_to_address>

### Comment 4
<location path="astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py" line_range="122" />
<code_context>
         if not query:
             return "error: Query parameter is empty."
+        errors: list[str] = []
         result = await retrieve_knowledge_base(
             query=query,
             umo=context.context.event.unified_msg_origin,
</code_context>
<issue_to_address>
**Retrieval exceptions skip failure cards**

When agentic knowledge-base retrieval raises, such as when every requested knowledge base is unavailable, `KnowledgeBaseQueryTool.call` awaits `retrieve_knowledge_base` before reaching the `if errors` notification, so the exception escapes without a ChatUI failure card.

Catch retrieval exceptions in `KnowledgeBaseQueryTool.call` and notify ChatUI before returning.

Also at `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:128-129`.
</issue_to_address>

### Comment 5
<location path="astrbot/core/knowledge_base/kb_mgr.py" line_range="315-319" />
<code_context>
                 if kb_helper.init_error:
                     unavailable_kbs.append((kb_name, kb_helper.init_error))
                     logger.warning(f"知识库 {kb_name} 不可用: {kb_helper.init_error}")
+                    if errors is not None:
+                        errors.append(
+                            f"Knowledge base {kb_name} is unavailable: "
+                            f"{kb_helper.init_error}"
+                        )
                     continue
                 kb_ids.append(kb_helper.kb.kb_id)
</code_context>
<issue_to_address>
**Missing knowledge bases go unreported**

When a configured knowledge-base name no longer resolves to a loaded knowledge base, `KnowledgeBaseManager.retrieve` skips unresolved names, and `check_all_kb` can return before errors are collected, so the configured knowledge base is silently omitted and ChatUI shows no warning.

Collect errors for unresolved names before early returns and pass them through the tool and injected-context retrieval paths.

Also at `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:45`, `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:79`, `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:122`, `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:126`, `astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:46`.
</issue_to_address>

### Comment 6
<location path="astrbot/core/pipeline/result_decorate/stage.py" line_range="374" />
<code_context>
+                ],
+            )
+        )
+    except Exception as exc:
+        logger.warning(f"Failed to show the {model} failure in ChatUI: {exc}")
</code_context>
<issue_to_address>
**Live speech failures lack cards**

When a ChatUI live response uses a TTS provider that fails, the new notification only covers the non-streaming result-decoration TTS loop. Live ChatUI output also invokes `stream_speech`, whose streaming and simulated TTS helpers log provider failures without notifying the event, so those failed calls remain invisible to the user.

Propagate live TTS failures to the event and show the same auxiliary-model warning card.
</issue_to_address>

### Comment 7
<location path="astrbot/core/pipeline/preprocess_stage/stage.py" line_range="273-277" />
<code_context>
             logger.error("Error occurred while retrieving knowledge base: %s", exc)
+            errors.append(str(exc))
+        if errors:
+            await notify_auxiliary_model_failure(
+                event, "Knowledge base", "; ".join(errors)
+            )
</code_context>
<issue_to_address>
**Multiple failures create duplicate cards**

When more than one recording in a message or its reply chain fails transcription, `_stt_record` sends a card for each failed recording, so one request produces multiple warning cards.

Aggregate STT failures and send one warning card per request.
</issue_to_address>

### Comment 8
<location path="astrbot/core/auxiliary_model_errors.py" line_range="34-47" />
<code_context>
+    if event.get_platform_name() != "webchat":
+        return
+    try:
+        await event.send(
+            MessageChain(
+                type="chatui_error",
+                chain=[
+                    Json(
+                        {
+                            "code": AUXILIARY_MODEL_ERROR_CODE,
+                            "message": f"{model}: {detail}",
+                        }
+                    )
+                ],
+            )
+        )
+    except Exception as exc:
+        logger.warning(f"Failed to show the {model} failure in ChatUI: {exc}")
</code_context>
<issue_to_address>
**Dropped cards are not logged**

When the WebChat queue rejects the card, for example because the request is no longer available, `WebChatMessageEvent._send` returns `None` when the WebChat queue rejects the card, but `WebChatMessageEvent.send` ignores that result and returns normally. `notify_auxiliary_model_failure` therefore logs nothing, leaving a failed notification invisible to operators.

Make the WebChat send path report a rejected queue insertion, or have the notifier detect and log a failed-send result.
</issue_to_address>

### Comment 9
<location path="astrbot/core/knowledge_base/retrieval/manager.py" line_range="245" />
<code_context>
                 )
+                if errors is not None:
+                    errors.append(
+                        f"Embedding search in knowledge base {kb_id} failed: "
+                        f"{type(e).__name__}: {e}"
+                    )
</code_context>
<issue_to_address>
**Knowledge-base cards omit provider identity**

When an embedding or rerank call fails and the exception text does not itself identify the configured provider, the collected embedding and rerank errors identify a knowledge base or only say “Rerank,” not the provider that failed, so users with multiple configured models cannot tell which configuration to fix from the card.

Include the relevant embedding or rerank provider ID in each collected failure detail.

Also at `astrbot/core/knowledge_base/retrieval/manager.py:197`.
</issue_to_address>

### Comment 10
<location path="tests/unit/test_auxiliary_model_errors.py" line_range="72" />
<code_context>
+async def test_a_card_that_cannot_be_sent_does_not_stop_the_reply():
+    event = _event()
+    event.send.side_effect = RuntimeError("stream closed")
+    await notify_auxiliary_model_failure(event, "Knowledge base", "down")
+
+
</code_context>
<issue_to_address>
**No-op notification passes the test**

When `notify_auxiliary_model_failure` regresses to returning without sending, `test_a_card_that_cannot_be_sent_does_not_stop_the_reply` only awaits the helper on line 72; it never asserts that `event.send` was attempted, so a no-op helper passes and the test does not verify that send failures are contained.

Assert that `event.send` was awaited once, while keeping the test’s no-exception check.
</issue_to_address>

### Comment 11
<location path="tests/unit/test_auxiliary_model_errors.py" line_range="1-255" />
<code_context>
+"""Failed speech and knowledge-base model calls are shown in ChatUI."""
</code_context>
<issue_to_address>
**A prohibited test file is added**

When this PR adds `tests/unit/test_auxiliary_model_errors.py`, the new `tests/unit/test_auxiliary_model_errors.py` adds a test file, directly breaking the repository rule against generating test files.

Remove the added test file.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 10 findings to address first, and on ChatUI, the card sends raw provider and retrieval exception text to the user; if an error includes credentials or other internal details, that information has already been disclosed once the card is delivered. Reverting stops future cards but cannot retract one already shown.

Blocking findings: astrbot/core/auxiliary_model_errors.py:41, astrbot/core/pipeline/preprocess_stage/stage.py:273, astrbot/core/pipeline/preprocess_stage/stage.py:236, astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:122, astrbot/core/knowledge_base/kb_mgr.py:319, and 5 more


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

Json(
{
"code": AUXILIARY_MODEL_ERROR_CODE,
"message": f"{model}: {detail}",

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.

🟡 Medium · Provider errors expose internal details

When a provider or knowledge-base initialization exception includes a credential or other sensitive internal detail, notify_auxiliary_model_failure places the unfiltered exception or initialization-error text in the ChatUI card, so a WebChat user who triggers the failure sees any credentials, internal URLs, or filesystem details included in that text.

Redact credentials and sensitive endpoint or filesystem details before displaying provider errors to ChatUI users.

Also at astrbot/core/knowledge_base/kb_mgr.py:319.

Prompt for AI agents
In `astrbot/core/auxiliary_model_errors.py` at line 41:

**Provider errors expose internal details**

When a provider or knowledge-base initialization exception includes a credential or other sensitive internal detail, `notify_auxiliary_model_failure` places the unfiltered exception or initialization-error text in the ChatUI card, so a WebChat user who triggers the failure sees any credentials, internal URLs, or filesystem details included in that text.

Redact credentials and sensitive endpoint or filesystem details before displaying provider errors to ChatUI users.

Also at `astrbot/core/knowledge_base/kb_mgr.py:319`.

logger.error(traceback.format_exc())
suffix = " (referenced message)" if is_reply else ""
logger.error(f"Speech-to-text{suffix} failed: {e}")
await notify_auxiliary_model_failure(

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.

🟡 Medium · Exhausted retries drop voice silently

When the STT provider keeps raising FileNotFoundError through all five attempts, _stt_record returns None after the retries without calling the notifier, so the voice recording is dropped without a ChatUI failure card.

Notify ChatUI when the final FileNotFoundError retry fails.

Prompt for AI agents
In `astrbot/core/pipeline/preprocess_stage/stage.py` at line 273:

**Exhausted retries drop voice silently**

When the STT provider keeps raising `FileNotFoundError` through all five attempts, `_stt_record` returns `None` after the retries without calling the notifier, so the voice recording is dropped without a ChatUI failure card.

Notify ChatUI when the final `FileNotFoundError` retry fails.

f"Session {event.unified_msg_origin} has no speech-to-text "
"provider configured.",
)
if any(isinstance(comp, Record) for comp in event.get_messages()):

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.

🟡 Medium · Quoted voice is skipped without warning

When speech-to-text is enabled, no provider is selected, and a voice Record appears only inside a Reply chain, the missing-provider check scans only top-level components and returns before the reply-chain loop, so the referenced voice is dropped without a ChatUI warning.

Include records nested in Reply chains in the missing-provider check.

Prompt for AI agents
In `astrbot/core/pipeline/preprocess_stage/stage.py` at line 236:

**Quoted voice is skipped without warning**

When speech-to-text is enabled, no provider is selected, and a voice `Record` appears only inside a `Reply` chain, the missing-provider check scans only top-level components and returns before the reply-chain loop, so the referenced voice is dropped without a ChatUI warning.

Include records nested in `Reply` chains in the missing-provider check.

Comment on lines +315 to +319
if errors is not None:
errors.append(
f"Knowledge base {kb_name} is unavailable: "
f"{kb_helper.init_error}"
)

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.

🟡 Medium · Missing knowledge bases go unreported

When a configured knowledge-base name no longer resolves to a loaded knowledge base, KnowledgeBaseManager.retrieve skips unresolved names, and check_all_kb can return before errors are collected, so the configured knowledge base is silently omitted and ChatUI shows no warning.

Collect errors for unresolved names before early returns and pass them through the tool and injected-context retrieval paths.

Also at astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:45, astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:79, astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:122, astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:126, astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:46.

Prompt for AI agents
In `astrbot/core/knowledge_base/kb_mgr.py` at lines 315-319:

**Missing knowledge bases go unreported**

When a configured knowledge-base name no longer resolves to a loaded knowledge base, `KnowledgeBaseManager.retrieve` skips unresolved names, and `check_all_kb` can return before errors are collected, so the configured knowledge base is silently omitted and ChatUI shows no warning.

Collect errors for unresolved names before early returns and pass them through the tool and injected-context retrieval paths.

Also at `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:45`, `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:79`, `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:122`, `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:126`, `astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:46`.

Comment on lines +34 to +47
await event.send(
MessageChain(
type="chatui_error",
chain=[
Json(
{
"code": AUXILIARY_MODEL_ERROR_CODE,
"message": f"{model}: {detail}",
}
)
],
)
)
except Exception as exc:

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.

🟡 Medium · Dropped cards are not logged

When the WebChat queue rejects the card, for example because the request is no longer available, WebChatMessageEvent._send returns None when the WebChat queue rejects the card, but WebChatMessageEvent.send ignores that result and returns normally. notify_auxiliary_model_failure therefore logs nothing, leaving a failed notification invisible to operators.

Make the WebChat send path report a rejected queue insertion, or have the notifier detect and log a failed-send result.

Prompt for AI agents
In `astrbot/core/auxiliary_model_errors.py` at lines 34-47:

**Dropped cards are not logged**

When the WebChat queue rejects the card, for example because the request is no longer available, `WebChatMessageEvent._send` returns `None` when the WebChat queue rejects the card, but `WebChatMessageEvent.send` ignores that result and returns normally. `notify_auxiliary_model_failure` therefore logs nothing, leaving a failed notification invisible to operators.

Make the WebChat send path report a rejected queue insertion, or have the notifier detect and log a failed-send result.

)
if errors is not None:
errors.append(
f"Embedding search in knowledge base {kb_id} failed: "

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.

🟡 Medium · Knowledge-base cards omit provider identity

When an embedding or rerank call fails and the exception text does not itself identify the configured provider, the collected embedding and rerank errors identify a knowledge base or only say “Rerank,” not the provider that failed, so users with multiple configured models cannot tell which configuration to fix from the card.

Include the relevant embedding or rerank provider ID in each collected failure detail.

Also at astrbot/core/knowledge_base/retrieval/manager.py:197.

Prompt for AI agents
In `astrbot/core/knowledge_base/retrieval/manager.py` at line 245:

**Knowledge-base cards omit provider identity**

When an embedding or rerank call fails and the exception text does not itself identify the configured provider, the collected embedding and rerank errors identify a knowledge base or only say “Rerank,” not the provider that failed, so users with multiple configured models cannot tell which configuration to fix from the card.

Include the relevant embedding or rerank provider ID in each collected failure detail.

Also at `astrbot/core/knowledge_base/retrieval/manager.py:197`.

Comment on lines +1 to +255
"""Failed speech and knowledge-base model calls are shown in ChatUI."""

import copy
import wave
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock

import pytest

from astrbot.core.astr_agent_runtime.main_agent import (
knowledge_base as knowledge_base_build,
)
from astrbot.core.astr_agent_runtime.main_agent.config import MainAgentBuildConfig
from astrbot.core.auxiliary_model_errors import (
AUXILIARY_MODEL_ERROR_CODE,
notify_auxiliary_model_failure,
)
from astrbot.core.config.default import DEFAULT_CONFIG
from astrbot.core.knowledge_base.retrieval.manager import RetrievalManager
from astrbot.core.knowledge_base.retrieval.rank_fusion import FusedResult
from astrbot.core.message.components import Plain, Record
from astrbot.core.message.message_event_result import (
MessageEventResult,
ResultContentType,
)
from astrbot.core.pipeline.preprocess_stage.stage import PreProcessStage
from astrbot.core.pipeline.result_decorate.stage import ResultDecorateStage
from astrbot.core.provider.entities import ProviderRequest


def _event(platform="webchat"):
event = MagicMock()
event.get_platform_name.return_value = platform
event.unified_msg_origin = f"{platform}:FriendMessage:user"
event.send = AsyncMock()
event.get_extra.return_value = None
event.is_stopped.return_value = False
event.plugins_name = None
return event


def _cards(event):
"""The ChatUI error cards an event sent, as their JSON payloads."""
return [
call.args[0].chain[0].data
for call in event.send.await_args_list
if call.args[0].type == "chatui_error"
]


@pytest.mark.asyncio
@pytest.mark.parametrize("platform", ["webchat", "aiocqhttp"])
async def test_card_is_shown_in_chatui_only(platform):
event = _event(platform)
await notify_auxiliary_model_failure(event, "Text-to-speech (tts)", "timeout")
assert _cards(event) == (
[
{
"code": AUXILIARY_MODEL_ERROR_CODE,
"message": "Text-to-speech (tts): timeout",
}
]
if platform == "webchat"
else []
)


@pytest.mark.asyncio
async def test_a_card_that_cannot_be_sent_does_not_stop_the_reply():
event = _event()
event.send.side_effect = RuntimeError("stream closed")
await notify_auxiliary_model_failure(event, "Knowledge base", "down")


def _voice(tmp_path):
path = tmp_path / "voice.wav"
with wave.open(str(path), "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(16000)
wav_file.writeframes(b"\x00\x00" * 160)
return path


async def _preprocess(provider, message):
config = {"provider_stt_settings": {"enable": True, "provider_id": "stt"}}
context = SimpleNamespace(
get_config=lambda **_: config,
get_using_stt_provider_async=AsyncMock(return_value=provider),
)
stage = PreProcessStage()
await stage.initialize(
SimpleNamespace(
astrbot_config=config, plugin_manager=SimpleNamespace(context=context)
)
)
event = _event()
event.message_obj = SimpleNamespace(message=message, message_str="")
event.message_str = ""
event.get_messages.return_value = message
await stage.process(event)
return event


@pytest.mark.asyncio
async def test_failed_speech_to_text_shows_the_provider_and_cause(tmp_path):
provider = SimpleNamespace(
provider_config={"id": "whisper"},
get_text=AsyncMock(side_effect=RuntimeError("model whisper-9 not found")),
)
event = await _preprocess(provider, [Record(file=str(_voice(tmp_path)))])
assert _cards(event) == [
{
"code": AUXILIARY_MODEL_ERROR_CODE,
"message": "Speech-to-text (whisper): model whisper-9 not found",
}
]


@pytest.mark.asyncio
@pytest.mark.parametrize("has_voice", [True, False])
async def test_missing_speech_to_text_provider_is_shown_only_for_voice(
tmp_path, has_voice
):
message = [Record(file=str(_voice(tmp_path)))] if has_voice else [Plain("hi")]
event = await _preprocess(None, message)
assert len(_cards(event)) == (1 if has_voice else 0)


@pytest.mark.asyncio
async def test_failed_text_to_speech_sends_text_and_one_card():
config = copy.deepcopy(DEFAULT_CONFIG)
config["provider_tts_settings"]["enable"] = True
provider = SimpleNamespace(
provider_config={"id": "edge"},
get_audio=AsyncMock(side_effect=RuntimeError("401 invalid key")),
)
context = SimpleNamespace(
get_config=lambda **_: config,
get_using_tts_provider_async=AsyncMock(return_value=provider),
)
stage = ResultDecorateStage()
await stage.initialize(
SimpleNamespace(
astrbot_config=config, plugin_manager=SimpleNamespace(context=context)
)
)
event = _event()
result = MessageEventResult(
chain=[Plain("first part"), Plain("second part")],
result_content_type=ResultContentType.LLM_RESULT,
)
event.get_result.return_value = result
async for _ in stage.process(event):
pass
# The reply falls back to text; both failed segments share one card.
assert [comp.text for comp in result.chain] == ["first part", "second part"]
assert _cards(event) == [
{
"code": AUXILIARY_MODEL_ERROR_CODE,
"message": "Text-to-speech (edge): 401 invalid key",
}
]


@pytest.mark.asyncio
async def test_retrieval_collects_skipped_embedding_and_rerank_failures():
vec_db = SimpleNamespace(
retrieve=AsyncMock(side_effect=RuntimeError("embedding 404")),
rerank_provider=SimpleNamespace(
rerank=AsyncMock(side_effect=RuntimeError("rerank 401"))
),
)
helper = SimpleNamespace(
kb=SimpleNamespace(
top_k_dense=5, top_k_sparse=5, top_m_final=5, rerank_provider_id="r"
),
vec_db=vec_db,
)
fused = FusedResult(
chunk_id="c", chunk_index=0, doc_id="d", kb_id="kb", content="text", score=1
)
manager = RetrievalManager(
sparse_retriever=SimpleNamespace(retrieve=AsyncMock(return_value=[])),
rank_fusion=SimpleNamespace(fuse=AsyncMock(return_value=[fused])),
kb_db=SimpleNamespace(
get_documents_with_metadata_batch=AsyncMock(
return_value={
"d": {
"document": SimpleNamespace(doc_name="doc"),
"knowledge_base": SimpleNamespace(kb_name="KB"),
}
}
)
),
)
errors: list[str] = []
results = await manager.retrieve(
query="q", kb_ids=["kb"], kb_id_helper_map={"kb": helper}, errors=errors
)
# Retrieval still answers from what worked.
assert [result.content for result in results] == ["text"]
assert errors == [
"Embedding search in knowledge base kb failed: RuntimeError: embedding 404",
"Rerank failed: RuntimeError: rerank 401",
]


@pytest.mark.asyncio
@pytest.mark.parametrize("raises", [False, True])
async def test_knowledge_base_failures_are_shown_without_dropping_results(
monkeypatch, raises
):
async def retrieve(query, umo, context, errors):
if raises:
raise ValueError("all knowledge bases are unavailable")
errors.append("Rerank failed: timeout")
return "fact"

monkeypatch.setattr(knowledge_base_build, "retrieve_knowledge_base", retrieve)
event = _event()
req = ProviderRequest(prompt="question")
await knowledge_base_build.apply_knowledge_base(
event,
req,
MagicMock(),
MainAgentBuildConfig(tool_call_timeout=60, kb_agentic_mode=False),
)
detail = (
"all knowledge bases are unavailable" if raises else "Rerank failed: timeout"
)
assert _cards(event) == [
{"code": AUXILIARY_MODEL_ERROR_CODE, "message": f"Knowledge base: {detail}"}
]
assert len(req.extra_user_content_parts) == (0 if raises else 1)


@pytest.mark.asyncio
async def test_knowledge_base_tool_shows_failures_and_still_answers(monkeypatch):
from astrbot.core.astr_agent_runtime.tools import knowledge_base_tools

async def retrieve(query, umo, context, errors):
errors.append("Knowledge base docs is unavailable: no embedding provider")
return "fact"

monkeypatch.setattr(knowledge_base_tools, "retrieve_knowledge_base", retrieve)
event = _event()
wrapper = SimpleNamespace(context=SimpleNamespace(event=event, context=None))
result = await knowledge_base_tools.KnowledgeBaseQueryTool().call(
wrapper, query="q"
)
assert result == "fact"
assert [card["message"] for card in _cards(event)] == [
"Knowledge base: Knowledge base docs is unavailable: no embedding provider"
]

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.

⚪ Low · A prohibited test file is added

When this PR adds tests/unit/test_auxiliary_model_errors.py, the new tests/unit/test_auxiliary_model_errors.py adds a test file, directly breaking the repository rule against generating test files.

Remove the added test file.

Prompt for AI agents
In `tests/unit/test_auxiliary_model_errors.py` at lines 1-255:

**A prohibited test file is added**

When this PR adds `tests/unit/test_auxiliary_model_errors.py`, the new `tests/unit/test_auxiliary_model_errors.py` adds a test file, directly breaking the repository rule against generating test files.

Remove the added test file.

From .github/copilot-instructions.md L27:

Do not generate test files for now.

Speech-to-text, text-to-speech and knowledge base retrieval fall back
quietly when their model fails: the voice message is dropped, the reply is
sent as text, or the answer is given without the retrieved knowledge. The
failure only reached the log, so a wrong model name or a rejected key went
unnoticed.

On WebChat, send one warning card for these failures. It names the model
and the provider's error, and links to the model configuration. The reply
still goes on. Retrieval collects the embedding and rerank failures it
skips, and an unavailable knowledge base, so the card can show them. A
missing speech-to-text provider is reported only for messages with voice.
Other platforms are unchanged.
@liquidtoy001
liquidtoy001 force-pushed the feat/chatui-auxiliary-model-errors branch from 41adc6f to 1d8126f Compare November 23, 2026 15:59
@mantoujun12
mantoujun12 requested a review from Soulter November 24, 2026 09:24
Sending the card marked the event as answered, so the pipeline skipped the
model and a ChatUI message whose voice part failed to transcribe got no
reply at all. The card is only a notice: the sent flag is restored after
it.
…speech-to-text card per message

When no knowledge base is usable, retrieval collects the reasons and then
raises, so the astr_kb_search tool lost them and showed no card. The card is
now sent in a finally block. Several failed recordings in one message now
give one speech-to-text card, like text-to-speech.

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

None yet

Development

Successfully merging this pull request may close these issues.

1 participant