Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
KnowledgeBaseQueryTool,
retrieve_knowledge_base,
)
from astrbot.core.auxiliary_model_errors import notify_auxiliary_model_failure
from astrbot.core.platform.astr_message_event import AstrMessageEvent
from astrbot.core.provider.entities import ProviderRequest
from astrbot.core.star.context import Context
Expand Down Expand Up @@ -35,18 +36,24 @@ async def apply_knowledge_base(
else:
if req.prompt is None or not req.prompt.strip():
return
errors: list[str] = []
try:
kb_result = await retrieve_knowledge_base(
query=req.prompt,
umo=event.unified_msg_origin,
context=plugin_context,
errors=errors,
)
if not kb_result:
return
req.extra_user_content_parts.append(
TextPart(
text=f"[Related Knowledge Base Results]:\n{kb_result}",
).mark_as_temp()
)
if kb_result:
req.extra_user_content_parts.append(
TextPart(
text=f"[Related Knowledge Base Results]:\n{kb_result}",
).mark_as_temp()
)
except Exception as exc: # noqa: BLE001
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)
)
35 changes: 29 additions & 6 deletions astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from astrbot.core.agent.run_context import ContextWrapper
from astrbot.core.agent.tool import FunctionTool, ToolExecResult
from astrbot.core.astr_agent_runtime.context import AstrAgentContext
from astrbot.core.auxiliary_model_errors import notify_auxiliary_model_failure
from astrbot.core.knowledge_base.kb_helper import KBHelper
from astrbot.core.star.context import Context

Expand Down Expand Up @@ -36,8 +37,19 @@ async def retrieve_knowledge_base(
query: str,
umo: str,
context: Context,
errors: list[str] | None = None,
) -> str | None:
"""Retrieve knowledge base context for the given query."""
"""Retrieve knowledge base context for the given query.

Args:
query: Text to search for.
umo: Session whose configured knowledge bases are searched.
context: Plugin context providing the knowledge-base manager.
errors: If given, collects failures that retrieval skipped.

Returns:
The formatted knowledge, or None when nothing was found.
"""
kb_mgr = context.kb_manager
config = context.get_config(umo=umo)

Expand All @@ -59,6 +71,7 @@ async def retrieve_knowledge_base(
kb_names=kb_names,
top_k_fusion=top_k_fusion,
top_m_final=top_k,
errors=errors,
)
if not kb_context:
return None
Expand Down Expand Up @@ -99,11 +112,21 @@ async def call(
query = kwargs.get("query", "")
if not query:
return "error: Query parameter is empty."
result = await retrieve_knowledge_base(
query=query,
umo=context.context.event.unified_msg_origin,
context=context.context.context,
)
errors: list[str] = []
try:
result = await retrieve_knowledge_base(
query=query,
umo=context.context.event.unified_msg_origin,
context=context.context.context,
errors=errors,
)
finally:
# Retrieval raises when no knowledge base is usable; the failures
# collected before that are still shown.
if errors:
await notify_auxiliary_model_failure(
context.context.event, "Knowledge base", "; ".join(errors)
)
if not result:
return "No relevant knowledge found."
return result
Expand Down
53 changes: 53 additions & 0 deletions astrbot/core/auxiliary_model_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Show failed speech and knowledge-base model calls in ChatUI.

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. Other platforms
keep that behavior; ChatUI also shows a card, so the user knows which model to
fix instead of finding only a log line.
"""

from astrbot.core import logger
from astrbot.core.message.components import Json
from astrbot.core.message.message_event_result import MessageChain
from astrbot.core.platform.astr_message_event import AstrMessageEvent

AUXILIARY_MODEL_ERROR_CODE = "auxiliaryModelFailed"


async def notify_auxiliary_model_failure(
event: AstrMessageEvent, model: str, detail: str
) -> None:
"""Show a ChatUI card for a failed speech or knowledge-base model call.

The reply goes on without the model, so a failure to show the card is only
logged.

Args:
event: Message event whose reply the failure affects.
model: Which model failed, e.g. "Speech-to-text (whisper)".
detail: The provider's error, shown under the card's details.
"""
if event.get_platform_name() != "webchat":
return
# Sending marks the event as answered, and the pipeline then skips the
# model. The card is only a notice: keep the reply going.
has_sent = event._has_send_oper
try:
await event.send(
MessageChain(
type="chatui_error",
chain=[
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`.

}
)
],
)
)
except Exception as exc:
Comment on lines +37 to +50

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.

logger.warning(f"Failed to show the {model} failure in ChatUI: {exc}")
finally:
event._has_send_oper = has_sent
25 changes: 24 additions & 1 deletion astrbot/core/knowledge_base/kb_mgr.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,25 @@ async def retrieve(
kb_names: list[str],
top_k_fusion: int = 20,
top_m_final: int = 5,
errors: list[str] | None = None,
) -> dict | None:
"""从指定知识库中检索相关内容"""
"""从指定知识库中检索相关内容

Args:
query: Text to search for.
kb_names: Names of the knowledge bases to search.
top_k_fusion: Results kept after rank fusion.
top_m_final: Results returned.
errors: If given, collects failures that were skipped (an
unavailable knowledge base, a failed embedding or rerank call).

Returns:
The context text and results, an empty dict when no knowledge base
was requested, or None when nothing matched.

Raises:
ValueError: Every requested knowledge base is unavailable.
"""
kb_ids = []
kb_id_helper_map = {}
unavailable_kbs = []
Expand All @@ -295,6 +312,11 @@ async def retrieve(
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}"
)
Comment on lines +315 to +319

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`.

continue
kb_ids.append(kb_helper.kb.kb_id)
kb_id_helper_map[kb_helper.kb.kb_id] = kb_helper
Expand All @@ -313,6 +335,7 @@ async def retrieve(
kb_id_helper_map=kb_id_helper_map,
top_k_fusion=top_k_fusion,
top_m_final=top_m_final,
errors=errors,
)
if not results:
return None
Expand Down
13 changes: 13 additions & 0 deletions astrbot/core/knowledge_base/retrieval/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ async def retrieve(
kb_id_helper_map: dict[str, KBHelper],
top_k_fusion: int = 20,
top_m_final: int = 5,
errors: list[str] | None = None,
) -> list[RetrievalResult]:
"""混合检索

Expand All @@ -82,6 +83,8 @@ async def retrieve(
kb_ids: 知识库 ID 列表
top_m_final: 最终返回数量
enable_rerank: 是否启用 Rerank
errors: If given, collects embedding and rerank failures that were
skipped, so the caller can report them.

Returns:
List[RetrievalResult]: 检索结果列表
Expand Down Expand Up @@ -115,6 +118,7 @@ async def retrieve(
query=query,
kb_ids=kb_ids,
kb_options=kb_options,
errors=errors,
)
time_end = time.time()
logger.debug(
Expand Down Expand Up @@ -189,6 +193,8 @@ async def retrieve(
)
except Exception as e:
logger.warning(f"Rerank 执行失败,已跳过重排序并使用融合结果: {e}")
if errors is not None:
errors.append(f"Rerank failed: {type(e).__name__}: {e}")

return retrieval_results[:top_m_final]

Expand All @@ -197,6 +203,7 @@ async def _dense_retrieve(
query: str,
kb_ids: list[str],
kb_options: dict,
errors: list[str] | None = None,
):
"""稠密检索 (向量相似度)

Expand All @@ -206,6 +213,7 @@ async def _dense_retrieve(
query: 查询文本
kb_ids: 知识库 ID 列表
top_k: 返回结果数量
errors: If given, collects the failure of each skipped knowledge base.

Returns:
List[Result]: 检索结果列表
Expand All @@ -232,6 +240,11 @@ async def _dense_retrieve(
f"知识库 {kb_id} 稠密检索失败: {type(e).__name__}: {e}",
exc_info=True,
)
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`.

f"{type(e).__name__}: {e}"
)
# skip the faulty KB and continue

# 按相似度排序并返回 top_k
Expand Down
19 changes: 19 additions & 0 deletions astrbot/core/pipeline/preprocess_stage/stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from pathlib import Path

from astrbot.core import logger
from astrbot.core.auxiliary_model_errors import notify_auxiliary_model_failure
from astrbot.core.message.components import Image, Plain, Record, Reply
from astrbot.core.platform.astr_message_event import AstrMessageEvent
from astrbot.core.utils.astrbot_path import get_astrbot_temp_path
Expand Down Expand Up @@ -232,10 +233,20 @@ async def process(
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.

await notify_auxiliary_model_failure(
event,
"Speech-to-text",
"Speech-to-text is enabled, but no provider is selected.",
)
return

# One card per message, however many recordings fail.
stt_failure_shown = False

async def _stt_record(record_comp: Record, is_reply: bool = False):
"""对单个 Record 组件执行语音转文本,成功返回 Plain,失败返回 None。"""
nonlocal stt_failure_shown
prefix = "referenced " if is_reply else ""
try:
path = await record_comp.convert_to_file_path()
Expand Down Expand Up @@ -263,6 +274,14 @@ async def _stt_record(record_comp: Record, is_reply: bool = False):
logger.error(traceback.format_exc())
suffix = " (referenced message)" if is_reply else ""
logger.error(f"Speech-to-text{suffix} failed: {e}")
if not stt_failure_shown:
stt_failure_shown = True
await notify_auxiliary_model_failure(
event,
"Speech-to-text "
f"({stt_provider.provider_config.get('id', 'unknown')})",
str(e),
)
break
return None

Expand Down
14 changes: 13 additions & 1 deletion astrbot/core/pipeline/result_decorate/stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from collections.abc import AsyncGenerator

from astrbot.core import file_token_service, html_renderer, logger
from astrbot.core.auxiliary_model_errors import notify_auxiliary_model_failure
from astrbot.core.i18n import get_config_locale, translate
from astrbot.core.message.components import At, Image, Json, Node, Plain, Record, Reply
from astrbot.core.message.message_event_result import ResultContentType
Expand Down Expand Up @@ -326,6 +327,8 @@ async def process(

if should_tts and tts_provider:
new_chain = []
# The first failed segment shows one ChatUI card for the reply.
tts_error = None
for comp in result.chain:
if isinstance(comp, Plain) and len(comp.text) > 1:
try:
Expand All @@ -337,6 +340,7 @@ async def process(
"Failed to convert the message segment to speech "
f"because no TTS audio file was found: {comp.text}",
)
tts_error = tts_error or "No audio file was returned."
new_chain.append(comp)
continue

Expand Down Expand Up @@ -367,13 +371,21 @@ async def process(
)
if dual_output:
new_chain.append(comp)
except Exception:
except Exception as exc:
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
logger.error(traceback.format_exc())
logger.error("TTS failed; sending text instead.")
tts_error = tts_error or str(exc)
new_chain.append(comp)
else:
new_chain.append(comp)
result.chain = new_chain
if tts_error:
await notify_auxiliary_model_failure(
event,
"Text-to-speech "
f"({tts_provider.provider_config.get('id', 'unknown')})",
tts_error,
)

# 文本转图片
elif (
Expand Down
2 changes: 2 additions & 0 deletions changelogs/unreleased.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Unreleased

- QQ Official: failed image uploads no longer log base64 payloads, avoiding dashboard freezes from oversized log entries. Retry attempts decrease from five to three, with one summary warning.
- ChatUI:语音转文字、语音合成或知识库检索(嵌入、重排序)的模型调用失败时,回复照常继续,同时显示一张「语音或知识库模型调用失败」卡片,详情中注明是哪个模型和原因,并可直接跳转到模型配置。此前这些失败只写入日志。其他平台行为不变。
- ChatUI: When the model for speech-to-text, text-to-speech or knowledge base retrieval (embedding, rerank) fails, the reply still goes on and a "speech or knowledge base model failed" card names the model and the cause, with a link to the model configuration. These failures were previously only logged. Other platforms are unchanged.

- 「插件 → 管理行为 → 函数工具」现在只列出插件工具。Agent 运行时工具由配置文件的 AI 功能设置控制,MCP 工具可在「插件 → MCP」查看。
- Extensions → Handlers → Function Tools now lists plugin tools. Configure Agent runtime tools in the profile's AI capability settings and view MCP tools under Extensions → MCP Servers.
Expand Down
Loading
Loading