Skip to content

feat(kb): add clean retrieval_query, score threshold gating, and hybrid retrieval mode - #11319

Open
JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:feat/kb-clean-retrieval-query-and-hybrid-mode
Open

JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:feat/kb-clean-retrieval-query-and-hybrid-mode

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Currently, knowledge-base retrieval in the main agent build pipeline has two practical limitations:

  1. Noisy or missing retrieval queries: apply_knowledge_base() always queries req.prompt before OnLLMRequestEvent hooks run. As a result:
    • Pure attachment/mention placeholders such as <attachment> or <提及自己> are embedded and sent to the vector index, injecting irrelevant chunks.
    • Quoted-only replies store the quoted text in req.extra_user_content_parts (<Quoted Message>) while req.prompt becomes "<attachment>", so the quoted text is not used for retrieval.
    • Configured prompt_prefix templates wrap req.prompt before retrieval, diluting the query.
    • Plugins that populate user text inside OnLLMRequestEvent (such as speech-to-text transcription or debounced follow-up merging) run too late for automatic KB retrieval to trigger.
  2. Binary auto vs. agentic tradeoff without relevance gating: kb_agentic_mode is strictly mutually exclusive (auto vs. agentic). In auto mode, every casual message unconditionally injects kb_final_top_k chunks with no minimum relevance floor; in agentic mode, automatic context is disabled entirely, so models with large tool catalogs rarely initiate astr_kb_search on their own.

Modifications

  • ProviderRequest.retrieval_query & clean query extraction (astrbot/core/provider/entities.py, astrbot/core/agent_input.py, astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py):

    • Added optional retrieval_query: str | None = None to ProviderRequest (never included in assemble_context() LLM payloads).
    • Added extract_retrieval_query() to strip pure placeholders (<attachment>, <提及自己>, [提及机器人], [Empty Text], media placeholders) and include a bounded excerpt of <Quoted Message> content when present.
    • prepare_input_content() seeds req.retrieval_query from the raw user prompt and quoted text before apply_prompt_prefix() wraps req.prompt.
  • One-shot post-hook supplemental KB retrieval (astrbot/core/astr_agent_runtime/main_agent/builder.py, astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py):

    • apply_knowledge_base() prioritizes req.retrieval_query when provided (with explicit "" strictly suppressing automatic retrieval) and returns whether automatic retrieval already executed for the turn.
    • When pre-hook input had no substantive query (e.g., voice-only or empty placeholder turn, where req.retrieval_query remains None and PreparedRequest.default_retrieval_query prevents prompt_prefix leakage) and an OnLLMRequestEvent plugin populates req.retrieval_query (or updates req.prompt), build_main_agent() triggers a single supplemental retrieval pass without re-adding tools and guarantees at most one automatic retrieval per turn.
  • Relevance threshold gating (kb_min_score) & hybrid retrieval mode (astrbot/core/config/default.py, astrbot/core/astr_agent_runtime/main_agent/config.py, astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py, astrbot/core/astr_agent_runtime/tools/registry.py, dashboard/src/i18n/locales/*/features/config-metadata.json):

    • Added optional kb_min_score: float = 0.0 (default 0.0 preserves existing behavior with zero filtering). When > 0.0, automatic retrieval filters out results below the threshold and returns None when nothing qualifies, while explicit astr_kb_search tool calls pass min_score=0.0 so active agentic lookups are not blocked by strict auto-injection gates.
    • Added optional kb_retrieval_mode: str = "" supporting "" (defers to legacy kb_agentic_mode for 100% backward compatibility), "auto", "agentic", and "hybrid" (auto-injects hits passing kb_min_score while keeping astr_kb_search available for active follow-up queries).
    • Updated builtin tool config rule evaluation for astr_kb_search and added config metadata entries across all four dashboard locales (en-US, zh-CN, ja-JP, ru-RU).
  • Tests (tests/unit/test_kb_retrieval_enhancements.py):

    • Added comprehensive unit tests covering placeholder exclusion, quoted-text extraction, prompt_prefix isolation, one-shot post-hook supplemental retrieval, kb_min_score filtering, hybrid mode, legacy kb_agentic_mode compatibility, builtin tool config status, and locale metadata parity.
  • This is NOT a breaking change.

Verification & Test Results

ruff format --check .
ruff check .
git diff --check
pytest tests/unit/test_kb_retrieval_enhancements.py tests/unit/test_astr_main_agent.py tests/unit/test_session_overrides.py tests/test_process_stage_images.py -q
  • ruff format --check .: 599 files already formatted
  • ruff check .: All checks passed!
  • git diff --check: clean
  • pytest: all 423 tests passed (including 23 new tests in tests/unit/test_kb_retrieval_enhancements.py and all existing test_astr_main_agent.py, test_session_overrides.py, and test_process_stage_images.py suites).

Backport Compatibility Note (v4.29.4)

This PR targets master (astrbot/core/astr_agent_runtime/main_agent/). The same design maps cleanly to v4.29.4 where apply_knowledge_base lives in astrbot/core/astr_main_agent.py:_apply_kb(), retrieve_knowledge_base in astrbot/core/tools/knowledge_base_tools.py, and the post-hook call site in astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py.


Checklist

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. (additive, opt-in defaults with 100% backward compatibility)
  • 👀 My changes have been well-tested, and verification steps and test results have been provided above.
  • 📚 I checked the affected WebUI metadata/labels and updated all 4 dashboard i18n locale files (en-US, zh-CN, ja-JP, ru-RU); no navigation entry points or page layouts were changed.
  • 🤓 I have ensured that no new dependencies are introduced.
  • 😮 My changes do not introduce malicious code.

Summary by Sourcery

Improve knowledge-base retrieval quality and configurability with clean queries, relevance gating, and hybrid automatic/tool-based retrieval while preserving existing defaults.

New Features:

  • Add clean, placeholder-aware retrieval queries with quoted-message support and one-shot post-hook supplemental retrieval.
  • Add configurable automatic, agentic, and hybrid knowledge-base retrieval modes.
  • Add minimum relevance-score gating for automatic knowledge-base context injection while leaving explicit tool searches unrestricted.

Bug Fixes:

  • Prevent prompt prefixes, attachment placeholders, and other non-substantive input from polluting automatic knowledge-base queries.
  • Prevent duplicate automatic retrieval within a single request.

Enhancements:

  • Preserve legacy kb_agentic_mode behavior by default while exposing retrieval mode and score threshold configuration.
  • Expose calibrated relevance scores through retrieval results for threshold evaluation.

Documentation:

  • Document the new knowledge-base retrieval modes and minimum relevance threshold in English and Chinese user guides.
  • Add knowledge-base retrieval settings metadata and localized labels for all dashboard locales.

Tests:

  • Add comprehensive unit coverage for query cleaning, quoted content, post-hook retrieval, score gating, hybrid mode, backward compatibility, tool behavior, and locale metadata.

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

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

## Individual Comments

### Comment 1
<location path="astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py" line_range="131" />
<code_context>
+            if isinstance(part, Mapping)
+            else getattr(part, "text", None)
+        )
+        if isinstance(part_text, str) and KB_RESULTS_HEADER in part_text:
+            return True
+
</code_context>
<issue_to_address>
**Automatic retrieval is skipped**

When quoted or plugin-added extra content contains `[Related Knowledge Base Results]:` before automatic retrieval runs, `apply_knowledge_base()` treats the substring as proof that retrieval already ran and returns before calling `retrieve_knowledge_base()`, so the turn receives no retrieved knowledge-base context.

Only skip retrieval when the extra content is known to contain results retrieved for the current turn, not merely because it contains the header text.

Also at `astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:132-133`.
</issue_to_address>

### Comment 2
<location path="astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py" line_range="107" />
<code_context>
+                score = float(item.get("score", 0.0))
+            except (TypeError, ValueError):
+                continue
+            if math.isfinite(score) and score >= threshold:
+                filtered.append(item)
+        if not filtered:
</code_context>
<issue_to_address>
**Weak matches pass the score threshold**

When retrieval returns one candidate or candidates with identical raw scores, `RankFusion.fuse()` normalizes scores within the batch, assigning a score of `1.0` to a lone or tied candidate regardless of absolute relevance, so `retrieve_knowledge_base()` admits weak matches and injects unrelated context despite `kb_min_score`.

Apply the threshold to an absolute relevance score rather than the batch-normalized fusion score.
</issue_to_address>

### Comment 3
<location path="astrbot/core/astr_agent_runtime/main_agent/builder.py" line_range="258" />
<code_context>
+        if not kb_retrieved and (
+            req.retrieval_query is not None or req.prompt != prompt_before_hook
+        ):
+            await knowledge_base.apply_knowledge_base(
+                event,
+                req,
</code_context>
<issue_to_address>
**Prompt prefixes pollute retrieval queries**

When a hook appends substantive text to an already-prefixed prompt without setting `retrieval_query`, the supplemental `apply_knowledge_base()` call receives no clean fallback and extracts its query from the hook-mutated `req.prompt`, so the prefix is sent to the vector index and can dilute retrieval relevance.

Pass the clean fallback query to the supplemental `apply_knowledge_base()` call.

Also at `astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:139`.
</issue_to_address>

### Comment 4
<location path="astrbot/core/astr_agent_runtime/main_agent/config.py" line_range="141" />
<code_context>
+        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)
+                if math.isfinite(parsed_score) and parsed_score >= 0.0:
+                    kb_min_score = parsed_score
</code_context>
<issue_to_address>
**Large thresholds abort retrieval**

When `kb_min_score` is configured as an integer too large to convert to a float, `float()` raises `OverflowError` for an extremely large integer threshold, which these handlers do not catch, so config resolution or retrieval aborts instead of falling back to zero and the agent request fails.

Catch `OverflowError` alongside `TypeError` and `ValueError` in both conversions and retain the zero-threshold fallback.

Also at `astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:71`.
</issue_to_address>

### Comment 5
<location path="astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py" line_range="152" />
<code_context>
+
+    try:
+        if config.kb_min_score > 0.0:
+            kb_result = await retrieve_knowledge_base(
+                query=query,
+                umo=event.unified_msg_origin,
</code_context>
<issue_to_address>
**Zero threshold override ignored**

When a per-turn `MainAgentBuildConfig` sets `kb_min_score=0.0` while the session configuration has a positive threshold, `retrieve_knowledge_base()` receives no `min_score`, so it reads the session configuration’s threshold instead of the per-turn build configuration; results below the intended zero-threshold floor are filtered out.

Pass `min_score=config.kb_min_score` in both branches so an explicit zero disables session-level filtering.
</issue_to_address>

### Comment 6
<location path="astrbot/core/config/default.py" line_range="3802-3813" />
<code_context>
                         "type": "bool",
                         "hint": "启用后,知识库检索将作为 LLM Tool,由模型自主决定何时调用知识库进行查询。需要模型支持函数调用能力。",
                     },
+                    "kb_retrieval_mode": {
+                        "description": "知识库检索模式",
+                        "type": "string",
+                        "options": ["", "auto", "agentic", "hybrid"],
+                        "labels": [
+                            "跟随 Agentic 开关(默认)",
+                            "自动注入 (auto)",
+                            "仅工具主动检索 (agentic)",
+                            "混合模式 (hybrid)",
+                        ],
+                        "hint": "留空时完全兼容原有 Agentic 开关;hybrid 模式在命中高相关度结果时自动注入,同时保留 astr_kb_search 工具供模型主动深挖。",
+                    },
                 },
                 "condition": {
</code_context>
<issue_to_address>
**New setting labels lack docs**

When the PR adds user-facing WebUI setting labels and options, the new user-facing retrieval-mode labels and options have no corresponding update to the WebUI instructions in `docs/zh` and `docs/en`, leaving the documented settings workflow incomplete.

Update the affected WebUI instructions in `docs/zh` and `docs/en` to cover the new settings.
</issue_to_address>

### Comment 7
<location path="tests/unit/test_kb_retrieval_enhancements.py" line_range="74" />
<code_context>
+        ]
+        query = kb_mod.extract_retrieval_query("<提及自己> explain this", parts)
+        assert query.startswith("explain this\n")
+        assert len(query.split("\n", 1)[1]) == kb_mod._MAX_QUOTED_EXCERPT_CHARS
+
+    def test_ignores_empty_text_quoted_placeholder(self):
</code_context>
<issue_to_address>
**Wrong quoted excerpt passes**

When the extractor truncates from the wrong part of a longer quote, when extraction selects the wrong 300-character segment, `test_combines_clean_prompt_and_quoted_excerpt_with_truncation` still passes: its quote is 400 identical `A`s, and the assertions check only the prompt prefix and excerpt length, so incorrect excerpt content goes unnoticed.

Use distinct text across the quote and assert the exact expected 300-character excerpt.
</issue_to_address>

### Comment 8
<location path="tests/unit/test_kb_retrieval_enhancements.py" line_range="110-112" />
<code_context>
+            kb_locale = data["ai_group"]["knowledgebase"]
+            assert "kb_min_score" in kb_locale
+            assert "kb_retrieval_mode" in kb_locale
+            assert len(kb_locale["kb_retrieval_mode"]["labels"]) == len(
+                expected_options
+            )
+
+    def test_from_config_preserves_legacy_agentic_mode_and_validates_inputs(self):
</code_context>
<issue_to_address>
**Blank mode labels pass**

When locale metadata contains blank mode labels, when every locale's mode labels are blank but the list still has four entries, `test_default_config_and_metadata_locales_in_sync` passes its length assertion, leaving the dashboard's mode choices unlabeled without a test failure.

Assert that each locale's mode labels are non-empty and correspond to the supported options.
</issue_to_address>

### Comment 9
<location path="tests/unit/test_kb_retrieval_enhancements.py" line_range="1" />
<code_context>
+"""Unit tests for clean KB retrieval queries, score gating, and hybrid mode."""
+
+from __future__ import annotations
</code_context>
<issue_to_address>
**Test file added**

When the change adds `tests/unit/test_kb_retrieval_enhancements.py`, the pull request adds a unit-test file, contrary to the repository rule against generating test files.

Remove the added test file.
</issue_to_address>

Sourcery assessment

Approval pending. 7 findings to address first.

Blocking findings: astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:131, astrbot/core/astr_agent_runtime/tools/knowledge_base_tools.py:107, astrbot/core/astr_agent_runtime/main_agent/builder.py:258, astrbot/core/astr_agent_runtime/main_agent/config.py:141, astrbot/core/astr_agent_runtime/main_agent/knowledge_base.py:152, and 2 more


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

Comment thread astrbot/core/config/default.py Resolved
This was referenced Nov 22, 2026
@codecov-commenter

codecov-commenter commented Nov 22, 2026 •

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 94.82759% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/astr_agent_runtime/tools/knowledge_base_tools.py 90.47% 4 Missing ⚠️
...rbot/core/astr_agent_runtime/main_agent/builder.py 82.35% 3 Missing ⚠️
...re/astr_agent_runtime/main_agent/knowledge_base.py 96.87% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

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

@JosephTian876
JosephTian876 force-pushed the feat/kb-clean-retrieval-query-and-hybrid-mode branch from 11e663d to 49469a8 Compare November 27, 2026 02:28
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Rebased onto latest master (f37e158) and adapted astr_kb_search mounting to the removal of astr_agent_runtime/tools/registry.py in #11335 (KnowledgeBaseQueryTool is now instantiated directly in apply_knowledge_base, matching upstream master).

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.

2 participants