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
22 changes: 21 additions & 1 deletion astrbot/core/agent_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ class PreparedRequest:
images: dict[str, dict] = field(default_factory=dict)
captioned_refs: set[str] = field(default_factory=set)
image_max_size: int = IMAGE_COMPRESS_DEFAULT_MAX_SIZE
default_retrieval_query: str = ""


async def prepare_input_content(
Expand Down Expand Up @@ -303,6 +304,7 @@ async def prepare_input_content(
logger.error("Error occurred while applying file extract: %s", exc)

has_reply = any(isinstance(comp, Reply) for comp in event.message_obj.message)
raw_user_prompt = req.prompt

if not req.prompt and not req.image_urls and not req.audio_urls:
if has_reply or req.extra_user_content_parts:
Expand Down Expand Up @@ -337,6 +339,18 @@ async def prepare_input_content(
if event.get_extra("_default_event_prompt"):
event.set_extra("_default_event_prompt", False)
supplement_mention_display(event, req, prompt_has_text=prompt_has_text)
default_retrieval_query = ""
if req.retrieval_query is None:
from astrbot.core.astr_agent_runtime.main_agent.knowledge_base import (
extract_retrieval_query,
)

default_retrieval_query = extract_retrieval_query(
raw_user_prompt,
req.extra_user_content_parts,
)
if default_retrieval_query:
req.retrieval_query = default_retrieval_query
apply_prompt_prefix(req, cfg)
if (
req.conversation
Expand All @@ -357,7 +371,13 @@ async def prepare_input_content(
if not req.session_id:
req.session_id = event.unified_msg_origin
append_system_reminders(event, req, cfg, config.timezone)
return PreparedRequest(req, prepared_images, captioned_refs, max_size)
return PreparedRequest(
req,
prepared_images,
captioned_refs,
max_size,
default_retrieval_query=default_retrieval_query,
)


def collect_plugin_capabilities(
Expand Down
44 changes: 43 additions & 1 deletion astrbot/core/astr_agent_runtime/main_agent/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,13 @@ async def build_main_agent(

# Add session context before capability instructions.
await workspace.apply_workspace_instructions(event, req, plugin_context)
await knowledge_base.apply_knowledge_base(event, req, plugin_context, config)
kb_retrieved = await knowledge_base.apply_knowledge_base(
event,
req,
plugin_context,
config,
fallback_query=prepared.default_retrieval_query,
)

# Session plugin filtering precedes builtins, which have their own settings.
if req.func_tool is not None:
Expand Down Expand Up @@ -232,6 +238,7 @@ async def build_main_agent(
link_display=event.get_platform_name() == "webchat",
)
if config.call_request_hook:
prompt_before_hook = req.prompt
if await call_event_hook(
event,
EventType.OnLLMRequestEvent,
Expand All @@ -241,6 +248,41 @@ async def build_main_agent(
else None,
):
return None
# Trigger one-shot supplemental KB retrieval when pre-hook input had no
# substantive query and a hook populated retrieval_query or prompt.
# An explicit req.retrieval_query == "" strictly suppresses retrieval.
if not kb_retrieved and (
req.retrieval_query is not None or req.prompt != prompt_before_hook
):
supplemental_query = None
if req.retrieval_query is None:
clean_prompt = req.prompt if isinstance(req.prompt, str) else ""
if (
not prepared.default_retrieval_query
and isinstance(prompt_before_hook, str)
and (stripped_before := prompt_before_hook.strip())
):
if clean_prompt.startswith(prompt_before_hook):
clean_prompt = clean_prompt.removeprefix(prompt_before_hook)
elif clean_prompt.endswith(prompt_before_hook):
clean_prompt = clean_prompt.removesuffix(prompt_before_hook)
elif clean_prompt.startswith(stripped_before):
clean_prompt = clean_prompt.removeprefix(stripped_before)
elif clean_prompt.endswith(stripped_before):
clean_prompt = clean_prompt.removesuffix(stripped_before)
supplemental_query = knowledge_base.extract_retrieval_query(
clean_prompt,
req.extra_user_content_parts,
prompt_prefix=config.provider_settings.get("prompt_prefix"),
)
await knowledge_base.apply_knowledge_base(
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
event,
req,
plugin_context,
config,
add_tool=False,
fallback_query=supplemental_query,
)
# Hooks may add images; preserve the cache from input preparation.
await prepare_request_images(
req,
Expand Down
51 changes: 51 additions & 0 deletions astrbot/core/astr_agent_runtime/main_agent/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import copy
import math
from dataclasses import dataclass, field

from astrbot.core import logger
Expand Down Expand Up @@ -39,6 +40,11 @@ class MainAgentBuildConfig:
kb_agentic_mode: bool = False
"""Whether to use agentic mode for knowledge base retrieval.
This will inject the knowledge base query tool into the main agent's toolset to allow dynamic querying."""
kb_retrieval_mode: str = ""
"""Knowledge-base retrieval mode: '', 'auto', 'agentic', or 'hybrid'.
Empty string defers to ``kb_agentic_mode`` for backward compatibility."""
kb_min_score: float = 0.0
"""Minimum relevance score threshold for automatic KB injection (0.0 disables filtering)."""
file_extract_enabled: bool = False
"""Whether to enable file content extraction for uploaded files."""
file_extract_prov: str = "moonshotai"
Expand Down Expand Up @@ -81,6 +87,17 @@ class MainAgentBuildConfig:
"""Provide the delivery tool when a proactive trigger has a destination."""
group_message_history_enabled: bool = False

@property
def effective_kb_mode(self) -> str:
"""Resolve the effective knowledge-base retrieval mode.

Returns:
One of ``"auto"``, ``"agentic"``, or ``"hybrid"``.
"""
if self.kb_retrieval_mode in ("auto", "agentic", "hybrid"):
return self.kb_retrieval_mode
return "agentic" if self.kb_agentic_mode else "auto"

@classmethod
def from_config(cls, config: dict) -> MainAgentBuildConfig:
"""Resolve shared build settings from an AstrBot session configuration.
Expand All @@ -107,6 +124,38 @@ def from_config(cls, config: dict) -> MainAgentBuildConfig:
tool_schema_mode,
)
tool_schema_mode = "full"
raw_kb_mode = config.get("kb_retrieval_mode", "")
kb_retrieval_mode = (
raw_kb_mode.strip().lower() if isinstance(raw_kb_mode, str) else ""
)
if kb_retrieval_mode not in ("", "auto", "agentic", "hybrid"):
logger.warning(
"Unsupported kb_retrieval_mode: %s, fallback to kb_agentic_mode",
raw_kb_mode,
)
kb_retrieval_mode = ""
raw_kb_min_score = config.get("kb_min_score", 0.0)
kb_min_score = 0.0
if not isinstance(raw_kb_min_score, bool) and raw_kb_min_score is not None:
try:
parsed_score = float(raw_kb_min_score)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
if math.isfinite(parsed_score) and parsed_score >= 0.0:
kb_min_score = parsed_score
else:
logger.warning(
"Invalid kb_min_score: %s, fallback to 0.0",
raw_kb_min_score,
)
except (TypeError, ValueError, OverflowError):
logger.warning(
"Invalid kb_min_score: %s, fallback to 0.0",
raw_kb_min_score,
)
elif isinstance(raw_kb_min_score, bool):
logger.warning(
"Invalid kb_min_score: %s, fallback to 0.0",
raw_kb_min_score,
)
return cls(
tool_call_timeout=misc.get("tool_call_timeout", 120),
max_steps=coerce_int_config(
Expand All @@ -121,6 +170,8 @@ def from_config(cls, config: dict) -> MainAgentBuildConfig:
"sanitize_context_by_modalities", False
),
kb_agentic_mode=config.get("kb_agentic_mode", False),
kb_retrieval_mode=kb_retrieval_mode,
kb_min_score=kb_min_score,
file_extract_enabled=file_extract.get("enable", False),
file_extract_prov=file_extract.get("provider", "moonshotai"),
file_extract_msh_api_key=file_extract.get("moonshotai_api_key", ""),
Expand Down
153 changes: 135 additions & 18 deletions astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Knowledge-base retrieval and agentic query capability."""

import re
from collections.abc import Mapping, Sequence
from typing import Any

from astrbot.core import logger
from astrbot.core.agent.message import TextPart
from astrbot.core.agent.tool import ToolSet
Expand All @@ -13,40 +17,153 @@

from .config import MainAgentBuildConfig

KB_RESULTS_HEADER = "[Related Knowledge Base Results]:"
_QUOTED_PREFIX = "<Quoted Message>\n"
_QUOTED_SUFFIX = "\n</Quoted Message>"
_QUOTED_SENDER_RE = re.compile(r"^\([^()\n]{1,80}\):\s*")
_PLACEHOLDER_RE = re.compile(
r"(?:<attachment>|<提及自己>|\[提及机器人\]|\[Empty Text\]"
r"|\[图片\]|\[语音\]|\[音频\]|\[视频\]|\[文件\]"
r"|\[Image unavailable\]|\[Voice unavailable\])"
)
_MAX_QUOTED_EXCERPT_CHARS = 300


def extract_retrieval_query(
prompt: str | None,
extra_user_content_parts: Sequence[Any] = (),
*,
prompt_prefix: str | None = None,
) -> str:
"""Derive clean retrieval query text from user text and optional quoted content.

Pure placeholder tokens (such as ``<attachment>`` or ``<提及自己>``) and
optional configured ``prompt_prefix`` wrappers are stripped so empty
attachment/mention turns or prompt templates do not pollute vector lookups.

Args:
prompt: Raw or current user prompt text.
extra_user_content_parts: Additional user parts that may contain a
``<Quoted Message>`` block.
prompt_prefix: Optional configured ``prompt_prefix`` string or
``{{prompt}}`` template to strip from ``prompt`` before cleaning.

Returns:
Normalized retrieval query string, or an empty string if no substantive
text is present.
"""
raw_prompt = prompt if isinstance(prompt, str) else ""
if isinstance(prompt_prefix, str) and prompt_prefix and raw_prompt:
if "{{prompt}}" in prompt_prefix:
before, after = prompt_prefix.split("{{prompt}}", 1)
if not before or raw_prompt.startswith(before):
raw_prompt = raw_prompt.removeprefix(before)
if after and raw_prompt.endswith(after):
raw_prompt = raw_prompt.removesuffix(after)
elif raw_prompt.startswith(prompt_prefix):
raw_prompt = raw_prompt.removeprefix(prompt_prefix)
clean_prompt = " ".join(_PLACEHOLDER_RE.sub(" ", raw_prompt).split())

quoted_excerpt = ""
for part in extra_user_content_parts or ():
if isinstance(part, Mapping):
text = part.get("text") if part.get("type") == "text" else None
else:
text = (
getattr(part, "text", None)
if getattr(part, "type", None) == "text"
else None
)
if not (isinstance(text, str) and text.startswith(_QUOTED_PREFIX)):
continue
body = text[len(_QUOTED_PREFIX) :]
if body.endswith(_QUOTED_SUFFIX):
body = body[: -len(_QUOTED_SUFFIX)]
body = _QUOTED_SENDER_RE.sub("", body.strip(), count=1)
body = " ".join(_PLACEHOLDER_RE.sub(" ", body).split())
if body:
quoted_excerpt = body[:_MAX_QUOTED_EXCERPT_CHARS]
break

if clean_prompt and quoted_excerpt:
return f"{clean_prompt}\n{quoted_excerpt}"
return clean_prompt or quoted_excerpt


async def apply_knowledge_base(
event: AstrMessageEvent,
req: ProviderRequest,
plugin_context: Context,
config: MainAgentBuildConfig,
) -> None:
"""Choose agentic querying or inject retrieved knowledge for this turn.
*,
add_tool: bool = True,
fallback_query: str | None = None,
) -> bool:
"""Apply configured knowledge-base retrieval and/or agentic query tool.

Supports three effective modes resolved from ``config.effective_kb_mode``:
- ``auto``: automatic retrieval injection before the turn.
- ``agentic``: mount the ``astr_kb_search`` tool without automatic injection.
- ``hybrid``: mount ``astr_kb_search`` and automatically inject hits passing
``config.kb_min_score``.

Args:
event: Event identifying the session's knowledge bases.
req: Request receiving a query tool or temporary retrieved context.
plugin_context: Knowledge-base services.
config: Knowledge-base mode for this build.
config: Knowledge-base mode and score threshold for this build.
add_tool: Whether to attach the agentic query tool when enabled by mode.
fallback_query: Optional pre-extracted clean query used when
``req.retrieval_query`` is None, preventing ``prompt_prefix`` from
leaking into pre-hook retrieval on empty/placeholder turns.

Returns:
True if automatic retrieval was executed for this request, False
otherwise.
"""
if config.kb_agentic_mode:
mode = config.effective_kb_mode
if add_tool and mode in ("agentic", "hybrid"):
if req.func_tool is None:
req.func_tool = ToolSet()
req.func_tool.add_tool(KnowledgeBaseQueryTool())
kb_tool = KnowledgeBaseQueryTool()
if req.func_tool.get_tool(kb_tool.name) is None:
req.func_tool.add_tool(kb_tool)

if mode == "agentic":
return False

if getattr(req, "_kb_retrieved", False):
return True

if req.retrieval_query is not None:
query = extract_retrieval_query(req.retrieval_query)
elif fallback_query is not None:
query = extract_retrieval_query(fallback_query)
else:
if req.prompt is None or not req.prompt.strip():
return
try:
kb_result = await retrieve_knowledge_base(
query=req.prompt,
umo=event.unified_msg_origin,
context=plugin_context,
)
if not kb_result:
return
query = extract_retrieval_query(
req.prompt,
req.extra_user_content_parts,
prompt_prefix=config.provider_settings.get("prompt_prefix"),
)
if not query:
return False

try:
kb_result = await retrieve_knowledge_base(
query=query,
umo=event.unified_msg_origin,
context=plugin_context,
min_score=config.kb_min_score,
)
req._kb_retrieved = True
if kb_result:
req.extra_user_content_parts.append(
TextPart(
text=f"[Related Knowledge Base Results]:\n{kb_result}",
text=f"{KB_RESULTS_HEADER}\n{kb_result}",
).mark_as_temp()
)
except Exception as exc: # noqa: BLE001
logger.error("Error occurred while retrieving knowledge base: %s", exc)
return True
except Exception as exc: # noqa: BLE001
req._kb_retrieved = True
logger.error("Error occurred while retrieving knowledge base: %s", exc)
return True
Loading
Loading