Repository navigation
feat(kb): add clean retrieval_query, score threshold gating, and hybrid retrieval mode - #11319
JosephTian876 wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
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
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…id retrieval mode
…x stripping, and docs
11e663d to
49469a8
Compare
|
Rebased onto latest |
Motivation
Currently, knowledge-base retrieval in the main agent build pipeline has two practical limitations:
apply_knowledge_base()always queriesreq.promptbeforeOnLLMRequestEventhooks run. As a result:<attachment>or<提及自己>are embedded and sent to the vector index, injecting irrelevant chunks.req.extra_user_content_parts(<Quoted Message>) whilereq.promptbecomes"<attachment>", so the quoted text is not used for retrieval.prompt_prefixtemplates wrapreq.promptbefore retrieval, diluting the query.OnLLMRequestEvent(such as speech-to-text transcription or debounced follow-up merging) run too late for automatic KB retrieval to trigger.kb_agentic_modeis strictly mutually exclusive (autovs.agentic). Inautomode, every casual message unconditionally injectskb_final_top_kchunks with no minimum relevance floor; inagenticmode, automatic context is disabled entirely, so models with large tool catalogs rarely initiateastr_kb_searchon 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):retrieval_query: str | None = NonetoProviderRequest(never included inassemble_context()LLM payloads).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()seedsreq.retrieval_queryfrom the raw user prompt and quoted text beforeapply_prompt_prefix()wrapsreq.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()prioritizesreq.retrieval_querywhen provided (with explicit""strictly suppressing automatic retrieval) and returns whether automatic retrieval already executed for the turn.req.retrieval_queryremainsNoneandPreparedRequest.default_retrieval_querypreventsprompt_prefixleakage) and anOnLLMRequestEventplugin populatesreq.retrieval_query(or updatesreq.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) &hybridretrieval 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):kb_min_score: float = 0.0(default0.0preserves existing behavior with zero filtering). When> 0.0, automatic retrieval filters out results below the threshold and returnsNonewhen nothing qualifies, while explicitastr_kb_searchtool calls passmin_score=0.0so active agentic lookups are not blocked by strict auto-injection gates.kb_retrieval_mode: str = ""supporting""(defers to legacykb_agentic_modefor 100% backward compatibility),"auto","agentic", and"hybrid"(auto-injects hits passingkb_min_scorewhile keepingastr_kb_searchavailable for active follow-up queries).astr_kb_searchand 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):prompt_prefixisolation, one-shot post-hook supplemental retrieval,kb_min_scorefiltering,hybridmode, legacykb_agentic_modecompatibility, builtin tool config status, and locale metadata parity.This is NOT a breaking change.
Verification & Test Results
ruff format --check .:599 files already formattedruff check .:All checks passed!git diff --check: cleanpytest: all 423 tests passed (including 23 new tests intests/unit/test_kb_retrieval_enhancements.pyand all existingtest_astr_main_agent.py,test_session_overrides.py, andtest_process_stage_images.pysuites).Backport Compatibility Note (
v4.29.4)This PR targets
master(astrbot/core/astr_agent_runtime/main_agent/). The same design maps cleanly tov4.29.4whereapply_knowledge_baselives inastrbot/core/astr_main_agent.py:_apply_kb(),retrieve_knowledge_baseinastrbot/core/tools/knowledge_base_tools.py, and the post-hook call site inastrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py.Checklist
en-US,zh-CN,ja-JP,ru-RU); no navigation entry points or page layouts were changed.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:
Bug Fixes:
Enhancements:
Documentation:
Tests: