fix(agent): exclude wiki-only KBs from quick-answer (RAG) mode

Quick-answer agent mode retrieves purely through vector/keyword chunk
search and ships with no `allowed_tools`, so the existing capability
filter (which only reads from `allowed_tools`) let wiki-only KBs through
in every entry point. End result: users could @-mention, select, and
receive suggested questions from wiki-only KBs in quick-answer mode,
but the underlying retrieval always returned empty.

Treat "RAG-only" as an implicit property of `agent_mode = quick-answer`
and union it with the tool-derived filter. The same predicate is now
used everywhere the user can pick or be steered toward a KB:

Backend
- `tools.DeriveKBFilterForAgent` / `KBSatisfiesAgentRequirements`
  layer the implicit quick-answer requirement on top of tool derivation.
- `ListKnowledgeBases`, `SearchKnowledge` (shared-agent `@file`),
  `resolveKnowledgeBasesFromAgent` (chat runtime), `/search` IM command,
  and `GetSuggestedQuestions` now all use the agent-mode-aware variant.
- `GetSuggestedQuestions` also skips the wiki-page fallback for
  quick-answer agents to cover the `selected` / explicit-kb-ids paths
  where a wiki-only KB could still slip through.

Frontend
- `deriveKbFilterForAgent` / `kbSatisfiesAgentRequirements` mirror the
  Go helpers.
- `@` mention dropdown (`Input-field.vue`) uses the new helper.
- Agent editor's "specified KB" picker (`AgentEditorModal.vue`) grays
  out wiki-only KBs for quick-answer agents with a tooltip, and the
  pre-save warning fires for quick-answer mode too.
- i18n: add `agentEditor.agentType.kbMismatch.quickAnswer` across all
  four locales.
This commit is contained in:
wizardchen
2026-05-12 15:41:47 +08:00
committed by lyingbug
parent a082c04d28
commit d199628701
13 changed files with 185 additions and 23 deletions
+11 -4
View File
@@ -20,8 +20,8 @@ import { getConversationConfig, updateConversationConfig, type ConversationConfi
import { useI18n } from 'vue-i18n';
import AttachmentUpload, { type AttachmentFile } from './AttachmentUpload.vue';
import {
kbSatisfiesToolRequirements,
deriveKbFilterFromTools,
kbSatisfiesAgentRequirements,
deriveKbFilterForAgent,
toolsConsumeFiles,
type ScopeCapabilities,
} from '@/utils/tool-capabilities';
@@ -303,12 +303,19 @@ const kbToScopeCaps = (kb: any): Partial<ScopeCapabilities> => {
};
};
// 当前智能体的 agent_mode(quick-answer / smart-reasoning),用于把
// "RAG-only 模式不能 @ wiki-only 知识库"这种隐式约束带进 KB 过滤。
const agentMode = computed(() => {
if (!hasAgentConfig.value) return '';
return currentAgentConfig.value?.agent_mode || '';
});
// "all" 模式 + 智能体工具有 KB 依赖时的兼容性过滤;'selected'/'none' 不在这里二次过滤
// (selected 由编辑器负责,none 已经空表)。
const isKbCompatibleWithAgent = (kb: any): boolean => {
if (!hasAgentConfig.value) return true;
if (agentKBSelectionMode.value !== 'all') return true;
return kbSatisfiesToolRequirements(kbToScopeCaps(kb), agentAllowedTools.value);
return kbSatisfiesAgentRequirements(kbToScopeCaps(kb), agentMode.value, agentAllowedTools.value);
};
// 仅在用户没输入搜索词、且是因智能体工具兼容性把列表清空的场景展示专用空态文案
@@ -318,7 +325,7 @@ const mentionEmptyHint = computed(() => {
if (agentKBSelectionMode.value !== 'all') return '';
// 列表为空 && 兼容性过滤器其实是有效的(否则"全部"不会被剔空)
if (mentionItems.value.length !== 0) return '';
const filter = deriveKbFilterFromTools(agentAllowedTools.value);
const filter = deriveKbFilterForAgent(agentMode.value, agentAllowedTools.value);
if (!filter) return '';
return t('mentionDetail.noCompatibleKbForAgent');
});
+1
View File
@@ -3933,6 +3933,7 @@ export default {
wikiQa: 'Wiki not enabled',
hybridRagWiki: 'No retrieval surface enabled',
dataAnalysis: 'Requires RAG (FAQ not supported)',
quickAnswer: 'Quick Answer mode requires RAG retrieval',
generic: 'Not compatible with current type',
},
kbIncompatibleWarn: '{count} selected KB(s) are not compatible with this type, please adjust manually.',
+1
View File
@@ -4000,6 +4000,7 @@ export default {
wikiQa: 'Wiki 비활성화',
hybridRagWiki: '활성화된 검색 수단 없음',
dataAnalysis: 'RAG 필요 (FAQ 미지원)',
quickAnswer: '빠른 답변 모드는 RAG 검색이 필요합니다',
generic: '현재 유형과 호환 안 됨',
},
kbIncompatibleWarn: '선택된 {count}개의 지식 베이스가 현재 유형과 호환되지 않습니다. 수동으로 조정해 주세요.',
+1
View File
@@ -3609,6 +3609,7 @@ export default {
wikiQa: 'Wiki отключён',
hybridRagWiki: 'Поиск не включён',
dataAnalysis: 'Требуется RAG (не FAQ)',
quickAnswer: 'Быстрый ответ требует RAG-поиск',
generic: 'Несовместимо с типом',
},
kbIncompatibleWarn: 'Выбранные базы знаний ({count}) несовместимы с текущим типом. Настройте вручную.'
+1
View File
@@ -3929,6 +3929,7 @@ export default {
wikiQa: "未启用 Wiki",
hybridRagWiki: "未启用任何检索能力",
dataAnalysis: "需启用 RAG(不支持 FAQ)",
quickAnswer: "快速问答模式需启用 RAG 检索",
generic: "不适用于当前类型",
},
kbIncompatibleWarn: "已选的 {count} 个知识库不适用于当前类型,请手动调整",
+51
View File
@@ -165,6 +165,57 @@ export function deriveKbFilterFromTools(
return { any_of: Array.from(caps) };
}
/**
* Implicit KB capability requirement for the "quick-answer" (RAG) agent
* mode. Quick-answer drives retrieval purely through vector/keyword chunk
* search and ships with NO `allowed_tools`, so the tool-derived filter
* alone would let wiki-only KBs through even though they can't contribute
* anything to a RAG answer. Treat this as a property of the agent MODE.
*/
const QUICK_ANSWER_KB_FILTER: { any_of: KBCapability[] } = {
any_of: ['vector', 'keyword'],
};
/**
* Agent-mode aware version of `deriveKbFilterFromTools`: unions the
* tool-derived `any_of` with the implicit requirement of `agentMode`
* (currently: quick-answer → vector|keyword).
*
* Returns `null` when neither the agent mode nor the tools impose any
* capability constraint (i.e. any KB is acceptable).
*/
export function deriveKbFilterForAgent(
agentMode: string | undefined | null,
allowedTools: string[] | undefined | null,
): { any_of: KBCapability[] } | null {
const caps = new Set<KBCapability>();
if (agentMode === 'quick-answer') {
QUICK_ANSWER_KB_FILTER.any_of.forEach(c => caps.add(c));
}
const fromTools = deriveKbFilterFromTools(allowedTools || []);
fromTools?.any_of.forEach(c => caps.add(c));
if (caps.size === 0) return null;
return { any_of: Array.from(caps) };
}
/**
* Agent-mode aware version of `kbSatisfiesToolRequirements`: ALSO honours
* the implicit capability requirement of `agentMode` (quick-answer needs
* vector or keyword indexing). Use this anywhere the user is choosing a
* KB for an agent — agent editor "specified KB" dropdown, chat `@`
* mention list, etc.
*/
export function kbSatisfiesAgentRequirements(
kbCaps: Partial<ScopeCapabilities> | undefined | null,
agentMode: string | undefined | null,
allowedTools: string[] | undefined | null,
): boolean {
const filter = deriveKbFilterForAgent(agentMode, allowedTools);
if (!filter) return true;
if (!kbCaps) return false;
return filter.any_of.some(c => !!kbCaps[c]);
}
/**
* Decide whether a single KB is compatible with an agent's tool set.
*
+21 -4
View File
@@ -2019,21 +2019,38 @@ const kbSatisfiesPresetFilter = (kb: { capabilities?: KBCapabilities; ragEnabled
return { ok: true, reason: '' };
};
// "快速问答 / RAG 模式"对 KB 的隐式要求:必须有 vector 或 keyword 索引。
// 这里跟 `activeAgentTypePreset` 解耦——quick-answer 没有 agent_type,
// 所以预设链路恒为 null,但 wiki-only KB 在 RAG 模式下检索结果永远为空,
// 必须在 UI 上 disable + 提示,避免用户白选。
const kbSatisfiesQuickAnswerMode = (kb: { capabilities?: KBCapabilities; ragEnabled?: boolean }): { ok: boolean; reason: string } => {
if (agentMode.value !== 'quick-answer') return { ok: true, reason: '' };
const hasRag = kb.capabilities
? (!!kb.capabilities.vector || !!kb.capabilities.keyword)
: !!kb.ragEnabled;
if (hasRag) return { ok: true, reason: '' };
return { ok: false, reason: t('agentEditor.agentType.kbMismatch.quickAnswer') };
};
// KB 过滤后的选项(用于"指定知识库"下拉)— 不满足的仍保留但标记 disabled + tooltip
const filteredKbOptionsForPreset = computed(() => {
const preset = activeAgentTypePreset.value;
return kbOptions.value.map(kb => {
const { ok, reason } = kbSatisfiesPresetFilter(kb, preset);
const presetResult = kbSatisfiesPresetFilter(kb, preset);
const modeResult = kbSatisfiesQuickAnswerMode(kb);
const ok = presetResult.ok && modeResult.ok;
const reason = !presetResult.ok ? presetResult.reason : (!modeResult.ok ? modeResult.reason : '');
return { ...kb, disabled: !ok, disabledReason: reason };
});
});
const filteredMyKbOptions = computed(() => filteredKbOptionsForPreset.value.filter(kb => !kb.shared));
const filteredSharedKbOptions = computed(() => filteredKbOptionsForPreset.value.filter(kb => kb.shared));
// 当前选中的 KB 中,有多少个在新预设下会被禁用(用于保存前提示)
// 当前选中的 KB 中,有多少个在新预设 / 模式下会被禁用(用于保存前提示)。
// quick-answer 模式下 preset 恒为 null,但 wiki-only KB 仍属"被禁用",
// 所以这里不再依赖 preset 是否存在,直接看是否有被 disable 的选中项。
const incompatibleSelectedKbCount = computed(() => {
const preset = activeAgentTypePreset.value;
if (!preset || kbSelectionMode.value !== 'selected') return 0;
if (kbSelectionMode.value !== 'selected') return 0;
const selected = new Set(formData.value.config.knowledge_bases || []);
return filteredKbOptionsForPreset.value.filter(kb => selected.has(kb.value) && kb.disabled).length;
});
+57
View File
@@ -152,6 +152,63 @@ func KBSatisfiesToolRequirements(caps types.KBCapabilities, allowedTools []strin
return false
}
// quickAnswerKBFilter is the implicit capability requirement for the
// "quick-answer" (RAG) agent mode. Quick-answer drives retrieval purely
// through vector/keyword chunk search, so a KB with neither chunk index
// (e.g. wiki-only) cannot contribute any context and should be filtered
// out everywhere the user can pick a KB (agent KB scope, `@` mention list,
// chat KB selector).
//
// We treat this as a property of the agent MODE rather than of any
// specific tool, because quick-answer mode doesn't ship with an
// `allowed_tools` list — its retrieval is implicit.
var quickAnswerKBFilter = KBFilter{AnyOf: []KBCapability{CapVector, CapKeyword}}
// DeriveKBFilterForAgent derives the effective KB capability filter for a
// given agent configuration. It combines the implicit constraint from
// `agentMode` (quick-answer forces vector|keyword) with the tool-derived
// filter (any_of capabilities required by some allowed tool).
//
// The returned filter is the UNION of both contributions, which matches
// the existing any_of semantics: a KB passes iff it exposes at least one
// of the listed capabilities.
func DeriveKBFilterForAgent(agentMode string, allowedTools []string) KBFilter {
seen := make(map[KBCapability]struct{})
if agentMode == "quick-answer" {
for _, c := range quickAnswerKBFilter.AnyOf {
seen[c] = struct{}{}
}
}
for _, c := range DeriveKBFilterFromTools(allowedTools).AnyOf {
seen[c] = struct{}{}
}
if len(seen) == 0 {
return KBFilter{}
}
out := make([]KBCapability, 0, len(seen))
for c := range seen {
out = append(out, c)
}
return KBFilter{AnyOf: out}
}
// KBSatisfiesAgentRequirements is the agent-aware variant of
// KBSatisfiesToolRequirements: it also enforces the implicit capability
// constraints of `agentMode` (currently: quick-answer requires vector or
// keyword indexing on the KB).
func KBSatisfiesAgentRequirements(caps types.KBCapabilities, agentMode string, allowedTools []string) bool {
f := DeriveKBFilterForAgent(agentMode, allowedTools)
if f.IsEmpty() {
return true
}
for _, c := range f.AnyOf {
if hasCap(caps, c) {
return true
}
}
return false
}
// ToolsConsumeFiles reports whether any tool in the allowed-tools list can
// use user-provided file references. Used to gate the `@file` listing in
// the chat input (and potentially SearchKnowledge defensively on the
@@ -7,6 +7,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -477,7 +478,16 @@ func (s *customAgentService) GetSuggestedQuestions(
// Return what we have so far (agent_config suggestions)
return s.truncateQuestions(result, limit), nil
}
// Honor the agent's implicit/explicit capability requirements so
// e.g. a quick-answer (RAG-only) agent doesn't surface wiki-only
// KBs whose wiki pages it could never answer from. Same filter
// the @ mention dropdown applies on the frontend.
capFilter := tools.DeriveKBFilterForAgent(agent.Config.AgentMode, agent.Config.AllowedTools)
for _, kb := range kbs {
if !capFilter.IsEmpty() &&
!tools.KBSatisfiesAgentRequirements(kb.Capabilities(), agent.Config.AgentMode, agent.Config.AllowedTools) {
continue
}
effectiveKBIDs = append(effectiveKBIDs, kb.ID)
}
case "selected":
@@ -575,6 +585,14 @@ func (s *customAgentService) GetSuggestedQuestions(
// when the KB does not need an embedding model). knowledge_id filter is
// intentionally ignored here because wiki pages are authored at the KB level
// and are not 1:1 with source knowledge items.
//
// Skip entirely for quick-answer (RAG-only) agents: those can't ever
// retrieve a wiki page, so surfacing wiki-derived suggestions would lure
// the user into asking questions the agent will then answer with empty
// context. Smart-reasoning agents that opt in to wiki tools keep this.
if agent.Config.AgentMode == types.AgentModeQuickAnswer {
queryKBIDs = nil
}
if len(queryKBIDs) > 0 && s.wikiPageRepo != nil {
wikiPages, err := s.wikiPageRepo.ListRecentForSuggestions(ctx, tenantID, queryKBIDs, fetchLimit)
if err != nil {
@@ -334,7 +334,7 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
// trust the client here: a stale session payload or API caller could
// still ask us to retrieve against an incompatible KB and we'd rather
// just drop it (and log) than feed it to tools that would no-op.
capFilter := tools.DeriveKBFilterFromTools(customAgent.Config.AllowedTools)
capFilter := tools.DeriveKBFilterForAgent(customAgent.Config.AgentMode, customAgent.Config.AllowedTools)
accept := func(kb *types.KnowledgeBase) bool {
if kb == nil {
return false
@@ -342,7 +342,7 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
if capFilter.IsEmpty() {
return true
}
return tools.KBSatisfiesToolRequirements(kb.Capabilities(), customAgent.Config.AllowedTools)
return tools.KBSatisfiesAgentRequirements(kb.Capabilities(), customAgent.Config.AgentMode, customAgent.Config.AllowedTools)
}
// Get own knowledge bases (uses ctx TenantID = agent's tenant)
+6 -4
View File
@@ -1517,14 +1517,16 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
}
// `all` mode: authoritative server-side capability filter. Mirrors the
// logic in ListKnowledgeBases so @file search, KB listing, and runtime
// all agree on what "mode=all" actually means for this agent.
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
// all agree on what "mode=all" actually means for this agent. The
// filter is agent-mode aware so quick-answer (RAG-only) skips
// wiki-only KBs even though it has no `allowed_tools`.
filter := tools.DeriveKBFilterForAgent(agent.Config.AgentMode, agent.Config.AllowedTools)
removed := 0
for _, kb := range kbs {
if kb == nil || kb.Type != types.KnowledgeBaseTypeDocument {
continue
}
if !filter.IsEmpty() && !tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
if !filter.IsEmpty() && !tools.KBSatisfiesAgentRequirements(kb.Capabilities(), agent.Config.AgentMode, agent.Config.AllowedTools) {
removed++
continue
}
@@ -1532,7 +1534,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
}
if removed > 0 {
logger.Infof(ctx,
"SearchKnowledge(agent=%s, mode=all): tool-capability filter removed %d KBs",
"SearchKnowledge(agent=%s, mode=all): capability filter removed %d KBs",
agentID, removed)
}
}
+8 -5
View File
@@ -357,21 +357,24 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
// `all` mode: authoritative server-side capability filter so a client
// that bypassed the frontend (old tab, curl, rogue plugin) can't @ a
// KB whose capabilities don't match any allowed tool of this agent.
// KB whose capabilities don't match this agent. The filter combines
// tool-derived requirements (smart-reasoning) with the implicit
// RAG-only requirement of quick-answer mode (which has no
// `allowed_tools` but still needs vector/keyword chunks to work).
// Non-`all` modes already constrain the scope explicitly.
if mode == "all" && len(agent.Config.AllowedTools) > 0 {
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
if mode == "all" {
filter := tools.DeriveKBFilterForAgent(agent.Config.AgentMode, agent.Config.AllowedTools)
if !filter.IsEmpty() {
before := len(kbs)
kept := make([]*types.KnowledgeBase, 0, before)
for _, kb := range kbs {
if tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
if tools.KBSatisfiesAgentRequirements(kb.Capabilities(), agent.Config.AgentMode, agent.Config.AllowedTools) {
kept = append(kept, kb)
}
}
if removed := before - len(kept); removed > 0 {
logger.Infof(ctx,
"ListKnowledgeBases(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
"ListKnowledgeBases(agent=%s, mode=all): capability filter removed %d of %d KBs",
agentID, removed, before)
}
kbs = kept
+7 -4
View File
@@ -52,14 +52,17 @@ func (c *SearchCommand) Execute(ctx context.Context, cmdCtx *CommandContext, arg
case "all":
allKBs, err := c.kbService.ListKnowledgeBases(ctx)
if err == nil {
// Same tool-capability filter as the QA pipeline's
// Same capability filter as the QA pipeline's
// resolveKnowledgeBasesFromAgent (`all` branch) so `/search`
// agrees with what the agent's tools can actually reach.
filter := tools.DeriveKBFilterFromTools(cmdCtx.CustomAgent.Config.AllowedTools)
// Agent-mode aware: quick-answer enforces RAG-only KBs.
agentMode := cmdCtx.CustomAgent.Config.AgentMode
allowed := cmdCtx.CustomAgent.Config.AllowedTools
filter := tools.DeriveKBFilterForAgent(agentMode, allowed)
skipped := 0
for _, kb := range allKBs {
if !filter.IsEmpty() &&
!tools.KBSatisfiesToolRequirements(kb.Capabilities(), cmdCtx.CustomAgent.Config.AllowedTools) {
!tools.KBSatisfiesAgentRequirements(kb.Capabilities(), agentMode, allowed) {
skipped++
continue
}
@@ -67,7 +70,7 @@ func (c *SearchCommand) Execute(ctx context.Context, cmdCtx *CommandContext, arg
}
if skipped > 0 {
logger.Infof(ctx,
"/search(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
"/search(agent=%s, mode=all): capability filter removed %d of %d KBs",
cmdCtx.CustomAgent.ID, skipped, len(allKBs))
}
}